'+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Add new element(s) to the buffer. Variadic: takes one or more arguments. If an array is passed as a single\n * argument, its elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive).\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive).\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = startIdx | 0;\n beforeIdx = beforeIdx || this.buffer.length;\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst DB_VERSION = 1;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = (event) => {\n resolve(event.target.result);\n };\n trx.onerror = (event) => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {Object} query - parameters of the message range to retrieve.\n * @param {number=} query.since - the least message ID to retrieve (inclusive).\n * @param {number=} query.before - the greatest message ID to retrieve (exclusive).\n * @param {number=} query.limit - the maximum number of messages to retrieve.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n const result = [];\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n const trx = this.db.transaction(['message']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev').onsuccess = (event) => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Private methods.\n\n // Serializable topic fields.\n static #topic_fields = ['created', 'updated', 'deleted', 'read', 'recv', 'seq', 'clear', 'defacs',\n 'creds', 'public', 'trusted', 'private', 'touched', '_deleted'\n ];\n\n // Copy data from src to Topic object.\n static #deserializeTopic(topic, src) {\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n topic[f] = src[f];\n }\n });\n if (Array.isArray(src.tags)) {\n topic._tags = src.tags;\n }\n if (src.acs) {\n topic.setAccessMode(src.acs);\n }\n topic.seq |= 0;\n topic.read |= 0;\n topic.unread = Math.max(0, topic.seq - topic.read);\n }\n\n // Copy values from 'src' to 'dst'. Allocate dst if it's null or undefined.\n static #serializeTopic(dst, src) {\n const res = dst || {\n name: src.name\n };\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n res[f] = src[f];\n }\n });\n if (Array.isArray(src._tags)) {\n res.tags = src._tags;\n }\n if (src.acs) {\n res.acs = src.getAccessMode().jsonHelper();\n }\n return res;\n }\n\n static #serializeSubscription(dst, topicName, uid, sub) {\n const fields = ['updated', 'mode', 'read', 'recv', 'clear', 'lastSeen', 'userAgent'];\n const res = dst || {\n topic: topicName,\n uid: uid\n };\n\n fields.forEach((f) => {\n if (sub.hasOwnProperty(f)) {\n res[f] = sub[f];\n }\n });\n\n return res;\n }\n\n static #serializeMessage(dst, msg) {\n // Serializable fields.\n const fields = ['topic', 'seq', 'ts', '_status', 'from', 'head', 'content'];\n const res = dst || {};\n fields.forEach((f) => {\n if (msg.hasOwnProperty(f)) {\n res[f] = msg[f];\n }\n });\n return res;\n }\n\n /**\n * To use DB in a non browser context, supply indexedDB provider.\n * @static\n * @memberof DB\n * @param idbProvider indexedDB provider, e.g. for node require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * Supports conversion of user keyboard input to formatted text:
\n * \n * - *abc* → abc
\n * - _abc_ → abc
\n * - ~abc~ →
abc \n * - `abc` → abc
\n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * \n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '
';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '',\n close: _ => ''\n },\n // Row: logic grouping of elements\n RW: {\n open: _ => '',\n close: _ => ''\n },\n // Quoted block.\n QQ: {\n open: _ => '',\n close: _ => '',\n props: (data) => {\n return data ? {} : null;\n },\n },\n // Video call\n VC: {\n open: _ => '',\n close: _ => '',\n props: data => {\n if (!data) return {};\n return {\n 'data-duration': data.duration,\n 'data-state': data.state,\n };\n }\n },\n // Video.\n VD: {\n open: data => {\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = data.ref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * @typedef Drafty.ImageDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the image, e.g. \"image/png\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded image content. Could be null/undefined.\n * @param {string} preview - base64-encoded thumbnail of the image.\n * @param {integer} width - width of the image.\n * @param {integer} height - height of the image.\n * @param {string} filename - file name suggestion for downloading the image.\n * @param {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.VideoDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @param {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @param {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @param {integer} width - width of the video.\n * @param {integer} height - height of the video.\n * @param {integer} duration - duration of the video.\n * @param {string} filename - file name suggestion for downloading the video.\n * @param {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @param {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.AudioDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded audio content. Could be null/undefined.\n * @param {integer} duration - duration of the record in milliseconds.\n * @param {string} preview - base64 encoded short array of amplitude values 0..100.\n * @param {string} filename - file name suggestion for downloading the audio.\n * @param {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * @typedef Drafty.AttachmentDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @param {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @param {string} filename - file name suggestion for downloading the attachment.\n * @param {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @param {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n mergeObj,\n mergeToCache,\n normalizeArray\n} from './utils.js';\n\nexport class Topic {\n /**\n * @callback Tinode.Topic.onData\n * @param {Data} data - Data packet\n */\n /**\n * Topic is a class representing a logical communication channel.\n * @class Topic\n * @memberof Tinode\n *\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {Tinode.Topic.onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic is subscribed.\n * @memberof Tinode.Topic#\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data && data.ref) {\n attachments.push(data.ref);\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {boolean} forward if true, request newer messages.\n */\n getMessagesPage(limit, forward) {\n let query = forward ?\n this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n\n // First try fetching from DB, then from the server.\n return this._loadMessages(this._tinode._db, query.extract('data'))\n .then((count) => {\n if (count == limit) {\n // Got enough messages from local cache.\n return Promise.resolve({\n topic: this.name,\n code: 200,\n params: {\n count: count\n }\n });\n }\n\n // Reduce the count of requested messages.\n limit -= count;\n // Update query with new values loaded from DB.\n query = forward ? this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n let promise = this.getMeta(query.build());\n if (!forward) {\n promise = promise.then(ctrl => {\n if (ctrl && ctrl.params && !ctrl.params.count) {\n this._noEarlierMsgs = true;\n }\n });\n }\n return promise;\n });\n }\n /**\n * Update topic metadata.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n if (params.tags) {\n params.tags = normalizeArray(params.tags);\n }\n // Send Set message, handle async response.\n return this._tinode.setMeta(this.name, params)\n .then(ctrl => {\n if (ctrl && ctrl.code >= 300) {\n // Not modified\n return ctrl;\n }\n\n if (params.sub) {\n params.sub.topic = this.name;\n if (ctrl.params && ctrl.params.acs) {\n params.sub.acs = ctrl.params.acs;\n params.sub.updated = ctrl.ts;\n }\n if (!params.sub.user) {\n // This is a subscription update of the current user.\n // Assign user ID otherwise the update will be ignored by _processMetaSub.\n params.sub.user = this._tinode.getCurrentUserID();\n if (!params.desc) {\n // Force update to topic's asc.\n params.desc = {};\n }\n }\n params.sub._noForwarding = true;\n this._processMetaSub([params.sub]);\n }\n\n if (params.desc) {\n if (ctrl.params && ctrl.params.acs) {\n params.desc.acs = ctrl.params.acs;\n params.desc.updated = ctrl.ts;\n }\n this._processMetaDesc(params.desc);\n }\n\n if (params.tags) {\n this._processMetaTags(params.tags);\n }\n if (params.cred) {\n this._processMetaCreds([params.cred], true);\n }\n\n return ctrl;\n });\n }\n /**\n * Update access mode of the current user or of another topic subsriber.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - UID of the user to update or null to update current user.\n * @param {string} update - the update value, full or delta.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n updateMode(uid, update) {\n const user = uid ? this.subscriber(uid) : null;\n const am = user ?\n user.acs.updateGiven(update).getGiven() :\n this.getAccessMode().updateWant(update).getWant();\n\n return this.setMeta({\n sub: {\n user: uid,\n mode: am\n }\n });\n }\n /**\n * Create new topic subscription. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to invite\n * @param {string=} mode - Access mode. null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.DelRange[]} ranges - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessages(ranges, hard) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete messages in inactive topic\"));\n }\n\n // Sort ranges in accending order by low, the descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n let tosend = ranges.reduce((out, r) => {\n if (r.low < Const.LOCAL_SEQID) {\n if (!r.hi || r.hi < Const.LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: this._maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n\n // Send {del} message, return promise\n let result;\n if (tosend.length > 0) {\n result = this._tinode.delMessages(this.name, tosend, hard);\n } else {\n result = Promise.resolve({\n params: {\n del: 0\n }\n });\n }\n // Update local cache.\n return result.then(ctrl => {\n if (ctrl.params.del > this._maxDel) {\n this._maxDel = ctrl.params.del;\n }\n\n ranges.forEach((r) => {\n if (r.hi) {\n this.flushMessageRange(r.low, r.hi);\n } else {\n this.flushMessage(r.low);\n }\n });\n\n if (this.onData) {\n // Calling with no parameters to indicate the messages were deleted.\n this.onData();\n }\n return ctrl;\n });\n }\n /**\n * Delete all messages. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesAll(hardDel) {\n if (!this._maxSeq || this._maxSeq <= 0) {\n // There are no messages to delete.\n return Promise.resolve();\n }\n return this.delMessages([{\n low: 1,\n hi: this._maxSeq + 1,\n _all: true\n }], hardDel);\n }\n\n /**\n * Delete multiple messages defined by their IDs. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {Array.} list - list of seq IDs to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesList(list, hardDel) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n let ranges = list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n // Send {del} message, return promise\n return this.delMessages(ranges, hardDel);\n }\n\n /**\n * Delete original message and edited variants. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delMessagesEdits(seq, hardDel) {\n const list = [seq];\n this.messageVersions(seq, msg => list.push(msg.seq));\n // Send {del} message, return promise\n return this.delMessagesList(list, hardDel);\n }\n\n /**\n * Delete topic. Requires Owner permission. Wrapper for {@link Tinode#delTopic}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hard - had-delete topic.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delTopic(hard) {\n if (this._deleted) {\n // The topic is already deleted at the server, just remove from DB.\n this._gone();\n return Promise.resolve(null);\n }\n\n return this._tinode.delTopic(this.name, hard).then(ctrl => {\n this._deleted = true;\n this._resetSub();\n this._gone();\n return ctrl;\n });\n }\n /**\n * Delete subscription. Requires Share permission. Wrapper for {@link Tinode#delSubscription}.\n * @memberof Tinode.Topic#\n *\n * @param {string} user - ID of the user to remove subscription for.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delSubscription(user) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete subscription in inactive topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delSubscription(this.name, user).then(ctrl => {\n // Remove the object from the subscription cache;\n delete this._users[user];\n // Notify listeners\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n return ctrl;\n });\n }\n /**\n * Send a read/recv notification.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what notification to send: recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.} a copy of tags\n */\n tags() {\n // Return a copy.\n return this._tags.slice(0);\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (this._isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by seq.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} newer - if true, check for newer messages only.\n */\n msgHasMoreMessages(newer) {\n return newer ? this.seq > this._maxSeq :\n // _minSeq could be more than 1, but earlier messages could have been deleted.\n (this._minSeq > 1 && !this._noEarlierMsgs);\n }\n /**\n * Check if the given seq Id is id of the most recent message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to check\n */\n isNewMessage(seqId) {\n return this._maxSeq <= seqId;\n }\n /**\n * Remove one message from local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to remove from cache.\n * @returns {Message} removed message or undefined if such message was not found.\n */\n flushMessage(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n delete this._messageVersions[seqId];\n if (idx >= 0) {\n this._tinode._db.remMessages(this.name, seqId);\n return this._messages.delAt(idx);\n }\n return undefined;\n }\n /**\n * Remove a range of messages from the local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} fromId seq ID of the first message to remove (inclusive).\n * @param {number} untilId seqID of the last message to remove (exclusive).\n *\n * @returns {Message[]} array of removed messages (could be empty).\n */\n flushMessageRange(fromId, untilId) {\n // Remove range from persistent cache.\n this._tinode._db.remMessages(this.name, fromId, untilId);\n\n // Remove all versions keyed by IDs in the range.\n for (let i = fromId; i < untilId; i++) {\n delete this._messageVersions[i];\n }\n\n // start, end: find insertion points (nearest == true).\n const since = this._messages.find({\n seq: fromId\n }, true);\n return since >= 0 ? this._messages.delRange(since, this._messages.find({\n seq: untilId\n }, true)) : [];\n }\n /**\n * Update message's seqId.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub message object.\n * @param {number} newSeqId new seq id for pub.\n */\n swapMessageId(pub, newSeqId) {\n const idx = this._messages.find(pub);\n const numMessages = this._messages.length();\n if (0 <= idx && idx < numMessages) {\n // Remove message with the old seq ID.\n this._messages.delAt(idx);\n this._tinode._db.remMessages(this.name, pub.seq);\n // Add message with the new seq ID.\n pub.seq = newSeqId;\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n }\n }\n /**\n * Attempt to stop message from being sent.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to stop sending and remove from cache.\n *\n * @returns {boolean} true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n _isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!this._isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags.length == 1 && tags[0] == Const.DEL_CHAR) {\n tags = [];\n }\n this._tags = tags;\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n const topic = this;\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(function(range) {\n if (!range.hi) {\n count++;\n topic.flushMessage(range.low);\n } else {\n for (let i = range.low; i < range.hi; i++) {\n count++;\n topic.flushMessage(i);\n }\n }\n });\n }\n\n if (count > 0) {\n // this._updateDeletedRanges();\n\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, params) {\n const {\n since,\n before,\n limit\n } = params || {};\n return db.readMessages(this.name, {\n since: since,\n before: before,\n limit: limit || Const.DEFAULT_MESSAGES_PAGE\n })\n .then(msgs => {\n msgs.forEach((data) => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n return msgs.length;\n });\n }\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n\n/**\n * @class TopicFnd - special case of {@link Tinode.Topic} for searching for\n * contacts and group topics.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter(function(item, pos, ary) {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n","export const PACKAGE_VERSION = \"0.21.0\";\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n Topic,\n TopicMe,\n TopicFnd\n} from './topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format /\n this._appName = config.appName || \"Undefined\";\n\n // API Key.\n this._apiKey = config.apiKey;\n\n // Name and version of the browser.\n this._platform = config.platform || 'web';\n // Underlying OS.\n if (typeof navigator != 'undefined') {\n this._browser = getBrowserInfo(navigator.userAgent, navigator.product);\n this._hwos = navigator.platform;\n // This is the default language. It could be changed by client.\n this._humanLanguage = navigator.language || 'en-US';\n }\n\n Connection.logger = this.logger;\n Drafty.logger = this.logger;\n\n // WebSocket or long polling network connection.\n if (config.transport != 'lp' && config.transport != 'ws') {\n config.transport = detectTransport();\n }\n this._connection = new Connection(config, Const.PROTOCOL_VERSION, /* autoreconnect */ true);\n this._connection.onMessage = (data) => {\n // Call the main message dispatcher.\n this.#dispatchMessage(data);\n }\n\n // Ready to start sending.\n this._connection.onOpen = _ => this.#connectionOpen();\n this._connection.onDisconnect = (err, code) => this.#disconnected(err, code);\n\n // Wrapper for the reconnect iterator callback.\n this._connection.onAutoreconnectIteration = (timeout, promise) => {\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout, promise);\n }\n }\n\n this._persist = config.persist;\n // Initialize object regardless. It simplifies the code.\n this._db = new DBCache(err => {\n this.logger('DB', err);\n }, this.logger);\n\n if (this._persist) {\n // Create the persistent cache.\n // Store promises to be resolved when messages load into memory.\n const prom = [];\n this._db.initDatabase().then(_ => {\n // First load topics into memory.\n return this._db.mapTopics((data) => {\n let topic = this.#cacheGet('topic', data.name);\n if (topic) {\n return;\n }\n if (data.name == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (data.name == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(data.name);\n }\n this._db.deserializeTopic(topic, data);\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Topic loaded from DB is not new.\n delete topic._new;\n // Request to load messages and save the promise.\n prom.push(topic._loadMessages(this._db));\n });\n }).then(_ => {\n // Then load users.\n return this._db.mapUsers((data) => {\n this.#cachePut('user', data.uid, mergeObj({}, data.public));\n });\n }).then(_ => {\n // Now wait for all messages to finish loading.\n return Promise.all(prom);\n }).then(_ => {\n if (onComplete) {\n onComplete();\n }\n this.logger(\"Persistent cache initialized.\");\n }).catch(err => {\n if (onComplete) {\n onComplete(err);\n }\n this.logger(\"Failed to initialize persistent cache:\", err);\n });\n } else {\n this._db.deleteDatabase().then(_ => {\n if (onComplete) {\n onComplete();\n }\n });\n }\n }\n\n // Private methods.\n\n // Console logger. Babel somehow fails to parse '...rest' parameter.\n logger(str, ...args) {\n if (this._loggingEnabled) {\n const d = new Date();\n const dateString = ('0' + d.getUTCHours()).slice(-2) + ':' +\n ('0' + d.getUTCMinutes()).slice(-2) + ':' +\n ('0' + d.getUTCSeconds()).slice(-2) + '.' +\n ('00' + d.getUTCMilliseconds()).slice(-3);\n\n console.log('[' + dateString + ']', str, args.join(' '));\n }\n }\n\n // Generator of default promises for sent packets.\n #makePromise(id) {\n let promise = null;\n if (id) {\n promise = new Promise((resolve, reject) => {\n // Stored callbacks will be called when the response packet with this Id arrives\n this._pendingPromises[id] = {\n 'resolve': resolve,\n 'reject': reject,\n 'ts': new Date()\n };\n });\n }\n return promise;\n };\n\n // Resolve or reject a pending promise.\n // Unresolved promises are stored in _pendingPromises.\n #execPromise(id, code, onOK, errorText) {\n const callbacks = this._pendingPromises[id];\n if (callbacks) {\n delete this._pendingPromises[id];\n if (code >= 200 && code < 400) {\n if (callbacks.resolve) {\n callbacks.resolve(onOK);\n }\n } else if (callbacks.reject) {\n callbacks.reject(new CommError(errorText, code));\n }\n }\n }\n\n // Send a packet. If packet id is provided return a promise.\n #send(pkt, id) {\n let promise;\n if (id) {\n promise = this.#makePromise(id);\n }\n pkt = simplify(pkt);\n let msg = JSON.stringify(pkt);\n this.logger(\"out: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : msg));\n try {\n this._connection.sendText(msg);\n } catch (err) {\n // If sendText throws, wrap the error in a promise or rethrow.\n if (id) {\n this.#execPromise(id, Connection.NETWORK_ERROR, null, err.message);\n } else {\n throw err;\n }\n }\n return promise;\n }\n\n // The main message dispatcher.\n #dispatchMessage(data) {\n // Skip empty response. This happens when LP times out.\n if (!data)\n return;\n\n this._inPacketCount++;\n\n // Send raw message to listener\n if (this.onRawMessage) {\n this.onRawMessage(data);\n }\n\n if (data === '0') {\n // Server response to a network probe.\n if (this.onNetworkProbe) {\n this.onNetworkProbe();\n }\n // No processing is necessary.\n return;\n }\n\n let pkt = JSON.parse(data, jsonParseHelper);\n if (!pkt) {\n this.logger(\"in: \" + data);\n this.logger(\"ERROR: failed to parse data\");\n } else {\n this.logger(\"in: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : data));\n\n // Send complete packet to listener\n if (this.onMessage) {\n this.onMessage(pkt);\n }\n\n if (pkt.ctrl) {\n // Handling {ctrl} message\n if (this.onCtrlMessage) {\n this.onCtrlMessage(pkt.ctrl);\n }\n\n // Resolve or reject a pending promise, if any\n if (pkt.ctrl.id) {\n this.#execPromise(pkt.ctrl.id, pkt.ctrl.code, pkt.ctrl, pkt.ctrl.text);\n }\n setTimeout(_ => {\n if (pkt.ctrl.code == 205 && pkt.ctrl.text == 'evicted') {\n // User evicted from topic.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._resetSub();\n if (pkt.ctrl.params && pkt.ctrl.params.unsub) {\n topic._gone();\n }\n }\n } else if (pkt.ctrl.code < 300 && pkt.ctrl.params) {\n if (pkt.ctrl.params.what == 'data') {\n // code=208, all messages received: \"params\":{\"count\":11,\"what\":\"data\"},\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._allMessagesReceived(pkt.ctrl.params.count);\n }\n } else if (pkt.ctrl.params.what == 'sub') {\n // code=204, the topic has no (refreshed) subscriptions.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n // Trigger topic.onSubsUpdated.\n topic._processMetaSub([]);\n }\n }\n }\n }, 0);\n } else {\n setTimeout(_ => {\n if (pkt.meta) {\n // Handling a {meta} message.\n // Preferred API: Route meta to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.meta.topic);\n if (topic) {\n topic._routeMeta(pkt.meta);\n }\n\n if (pkt.meta.id) {\n this.#execPromise(pkt.meta.id, 200, pkt.meta, 'META');\n }\n\n // Secondary API: callback\n if (this.onMetaMessage) {\n this.onMetaMessage(pkt.meta);\n }\n } else if (pkt.data) {\n // Handling {data} message\n // Preferred API: Route data to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.data.topic);\n if (topic) {\n topic._routeData(pkt.data);\n }\n\n // Secondary API: Call callback\n if (this.onDataMessage) {\n this.onDataMessage(pkt.data);\n }\n } else if (pkt.pres) {\n // Handling {pres} message\n // Preferred API: Route presence to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.pres.topic);\n if (topic) {\n topic._routePres(pkt.pres);\n }\n\n // Secondary API - callback\n if (this.onPresMessage) {\n this.onPresMessage(pkt.pres);\n }\n } else if (pkt.info) {\n // {info} message - read/received notifications and key presses\n // Preferred API: Route {info}} to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.info.topic);\n if (topic) {\n topic._routeInfo(pkt.info);\n }\n\n // Secondary API - callback\n if (this.onInfoMessage) {\n this.onInfoMessage(pkt.info);\n }\n } else {\n this.logger(\"ERROR: Unknown packet received.\");\n }\n }, 0);\n }\n }\n }\n\n // Connection open, ready to start sending.\n #connectionOpen() {\n if (!this._expirePromises) {\n // Reject promises which have not been resolved for too long.\n this._expirePromises = setInterval(_ => {\n const err = new CommError(\"timeout\", 504);\n const expires = new Date(new Date().getTime() - Const.EXPIRE_PROMISES_TIMEOUT);\n for (let id in this._pendingPromises) {\n let callbacks = this._pendingPromises[id];\n if (callbacks && callbacks.ts < expires) {\n this.logger(\"Promise expired\", id);\n delete this._pendingPromises[id];\n if (callbacks.reject) {\n callbacks.reject(err);\n }\n }\n }\n }, Const.EXPIRE_PROMISES_PERIOD);\n }\n this.hello();\n }\n\n #disconnected(err, code) {\n this._inPacketCount = 0;\n this._serverInfo = null;\n this._authenticated = false;\n\n if (this._expirePromises) {\n clearInterval(this._expirePromises);\n this._expirePromises = null;\n }\n\n // Mark all topics as unsubscribed\n this.#cacheMap('topic', (topic, key) => {\n topic._resetSub();\n });\n\n // Reject all pending promises\n for (let key in this._pendingPromises) {\n const callbacks = this._pendingPromises[key];\n if (callbacks && callbacks.reject) {\n callbacks.reject(err);\n }\n }\n this._pendingPromises = {};\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n }\n\n // Get User Agent string\n #getUserAgent() {\n return this._appName + ' (' + (this._browser ? this._browser + '; ' : '') + this._hwos + '); ' + Const.LIBRARY;\n }\n\n // Generator of packets stubs\n #initPacket(type, topic) {\n switch (type) {\n case 'hi':\n return {\n 'hi': {\n 'id': this.getNextUniqueId(),\n 'ver': Const.VERSION,\n 'ua': this.#getUserAgent(),\n 'dev': this._deviceToken,\n 'lang': this._humanLanguage,\n 'platf': this._platform\n }\n };\n\n case 'acc':\n return {\n 'acc': {\n 'id': this.getNextUniqueId(),\n 'user': null,\n 'scheme': null,\n 'secret': null,\n 'tmpscheme': null,\n 'tmpsecret': null,\n 'login': false,\n 'tags': null,\n 'desc': {},\n 'cred': {}\n }\n };\n\n case 'login':\n return {\n 'login': {\n 'id': this.getNextUniqueId(),\n 'scheme': null,\n 'secret': null\n }\n };\n\n case 'sub':\n return {\n 'sub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'set': {},\n 'get': {}\n }\n };\n\n case 'leave':\n return {\n 'leave': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'unsub': false\n }\n };\n\n case 'pub':\n return {\n 'pub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'noecho': false,\n 'head': null,\n 'content': {}\n }\n };\n\n case 'get':\n return {\n 'get': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'desc': {},\n 'sub': {},\n 'data': {}\n }\n };\n\n case 'set':\n return {\n 'set': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'desc': {},\n 'sub': {},\n 'tags': [],\n 'ephemeral': {}\n }\n };\n\n case 'del':\n return {\n 'del': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'delseq': null,\n 'user': null,\n 'hard': false\n }\n };\n\n case 'note':\n return {\n 'note': {\n // no id by design (except calls).\n 'topic': topic,\n 'what': null, // one of \"recv\", \"read\", \"kp\", \"call\"\n 'seq': undefined // the server-side message id acknowledged as received or read.\n }\n };\n\n default:\n throw new Error(`Unknown packet type requested: ${type}`);\n }\n }\n\n // Cache management\n #cachePut(type, name, obj) {\n this._cache[type + ':' + name] = obj;\n }\n #cacheGet(type, name) {\n return this._cache[type + ':' + name];\n }\n #cacheDel(type, name) {\n delete this._cache[type + ':' + name];\n }\n\n // Enumerate all items in cache, call func for each item.\n // Enumeration stops if func returns true.\n #cacheMap(type, func, context) {\n const key = type ? type + ':' : undefined;\n for (let idx in this._cache) {\n if (!key || idx.indexOf(key) == 0) {\n if (func.call(context, this._cache[idx], idx)) {\n break;\n }\n }\n }\n }\n\n // Make limited cache management available to topic.\n // Caching user.public only. Everything else is per-topic.\n #attachCacheToTopic(topic) {\n topic._tinode = this;\n\n topic._cacheGetUser = (uid) => {\n const pub = this.#cacheGet('user', uid);\n if (pub) {\n return {\n user: uid,\n public: mergeObj({}, pub)\n };\n }\n return undefined;\n };\n topic._cachePutUser = (uid, user) => {\n this.#cachePut('user', uid, mergeObj({}, user.public));\n };\n topic._cacheDelUser = (uid) => {\n this.#cacheDel('user', uid);\n };\n topic._cachePutSelf = _ => {\n this.#cachePut('topic', topic.name, topic);\n };\n topic._cacheDelSelf = _ => {\n this.#cacheDel('topic', topic.name);\n };\n }\n\n // On successful login save server-provided data.\n #loginSuccessful(ctrl) {\n if (!ctrl.params || !ctrl.params.user) {\n return ctrl;\n }\n // This is a response to a successful login,\n // extract UID and security token, save it in Tinode module\n this._myUID = ctrl.params.user;\n this._authenticated = (ctrl && ctrl.code >= 200 && ctrl.code < 300);\n if (ctrl.params && ctrl.params.token && ctrl.params.expires) {\n this._authToken = {\n token: ctrl.params.token,\n expires: ctrl.params.expires\n };\n } else {\n this._authToken = null;\n }\n\n if (this.onLogin) {\n this.onLogin(ctrl.code, ctrl.text);\n }\n\n return ctrl;\n }\n\n // Static methods.\n /**\n * Helper method to package account credential.\n *\n * @param {string | Credential} meth - validation method or object with validation data.\n * @param {string=} val - validation value (e.g. email or phone number).\n * @param {Object=} params - validation parameters.\n * @param {string=} resp - validation response.\n *\n * @returns {Array.} array with a single credential or null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.} tags - array of string tags for user discovery.\n * @property {string} scheme - Temporary authentication scheme for password reset.\n * @property {string} secret - Temporary authentication secret for password reset.\n * @property {Array.=} attachments - Array of references to out of band attachments used in account description.\n */\n /**\n * @typedef DefAcs\n * @type {Object}\n * @property {string=} auth - Access mode for me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.=} attachments - URLs of out of band attachments used in parameters.\n */\n /**\n * @typedef SetDesc\n * @type {Object}\n * @property {DefAcs=} defacs - Default access mode.\n * @property {Object=} public - Free-form topic description, publically accessible.\n * @property {Object=} private - Free-form topic description accessible only to the owner.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n */\n /**\n * @typedef SetSub\n * @type {Object}\n * @property {string=} user - UID of the user affected by the request. Default (empty) - current user.\n * @property {string=} mode - User access mode, either requested or assigned dependent on context.\n */\n /**\n * Send a topic subscription request.\n *\n * @param {string} topic - Name of the topic to subscribe to.\n * @param {GetQuery=} getParams - Optional subscription metadata query\n * @param {SetParams=} setParams - Optional initialization parameters\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n subscribe(topicName, getParams, setParams) {\n const pkt = this.#initPacket('sub', topicName)\n if (!topicName) {\n topicName = Const.TOPIC_NEW;\n }\n\n pkt.sub.get = getParams;\n\n if (setParams) {\n if (setParams.sub) {\n pkt.sub.set.sub = setParams.sub;\n }\n\n if (setParams.desc) {\n const desc = setParams.desc;\n if (Tinode.isNewGroupTopicName(topicName)) {\n // Full set.desc params are used for new topics only\n pkt.sub.set.desc = desc;\n } else if (Tinode.isP2PTopicName(topicName) && desc.defacs) {\n // Use optional default permissions only.\n pkt.sub.set.desc = {\n defacs: desc.defacs\n };\n }\n }\n\n // See if external objects were used in topic description.\n if (Array.isArray(setParams.attachments) && setParams.attachments.length > 0) {\n pkt.extra = {\n attachments: setParams.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n\n if (setParams.tags) {\n pkt.sub.set.tags = setParams.tags;\n }\n }\n return this.#send(pkt, pkt.sub.id);\n }\n\n /**\n * Detach and optionally unsubscribe from the topic\n *\n * @param {string} topic - Topic to detach from.\n * @param {boolean} unsub - If true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.=} attachments - array of URLs with attachments.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publishMessage(pub, attachments) {\n // Make a shallow copy. Needed in order to clear locally-assigned temp values;\n pub = Object.assign({}, pub);\n pub.seq = undefined;\n pub.from = undefined;\n pub.ts = undefined;\n const msg = {\n pub: pub,\n };\n if (attachments) {\n msg.extra = {\n attachments: attachments.filter(ref => isUrlRelative(ref))\n };\n }\n return this.#send(msg, pub.id);\n }\n\n /**\n * Out of band notification: notify topic that an external (push) notification was recived by the client.\n *\n * @param {object} data - notification payload.\n * @param {string} data.what - notification type, 'msg', 'read', 'sub'.\n * @param {string} data.topic - name of the updated topic.\n * @param {number=} data.seq - seq ID of the affected message.\n * @param {string=} data.xfrom - UID of the sender.\n * @param {object=} data.given - new subscription 'given', e.g. 'ASWP...'.\n * @param {object=} data.want - new subscription 'want', e.g. 'RWJ...'.\n */\n oobNotification(data) {\n this.logger('oob: ' + (this._trimLongStrings ? JSON.stringify(data, jsonLoggerHelper) : data));\n\n switch (data.what) {\n case 'msg':\n if (!data.seq || data.seq < 1 || !data.topic) {\n // Server sent invalid data.\n break;\n }\n\n if (!this.isConnected()) {\n // Let's ignore the message if there is no connection: no connection means there are no open\n // tabs with Tinode.\n break;\n }\n\n const topic = this.#cacheGet('topic', data.topic);\n if (!topic) {\n // TODO: check if there is a case when a message can arrive from an unknown topic.\n break;\n }\n\n if (topic.isSubscribed()) {\n // No need to fetch: topic is already subscribed and got data through normal channel.\n break;\n }\n\n if (topic.maxMsgSeq() < data.seq) {\n if (topic.isChannelType()) {\n topic._updateReceived(data.seq, 'fake-uid');\n }\n\n // New message.\n if (data.xfrom && !this.#cacheGet('user', data.xfrom)) {\n // Message from unknown sender, fetch description from the server.\n // Sending asynchronously without a subscription.\n this.getMeta(data.xfrom, new MetaGetBuilder().withDesc().build()).catch(err => {\n this.logger(\"Failed to get the name of a new sender\", err);\n });\n }\n\n topic.subscribe(null).then(_ => {\n return topic.getMeta(new MetaGetBuilder(topic).withLaterData(24).withLaterDel(24).build());\n }).then(_ => {\n // Allow data fetch to complete and get processed successfully.\n topic.leaveDelayed(false, 1000);\n }).catch(err => {\n this.logger(\"On push data fetch failed\", err);\n }).finally(_ => {\n this.getMeTopic()._refreshContact('msg', topic);\n });\n }\n break;\n\n case 'read':\n this.getMeTopic()._routePres({\n what: 'read',\n seq: data.seq\n });\n break;\n\n case 'sub':\n if (!this.isMe(data.xfrom)) {\n // TODO: handle updates from other users.\n break;\n }\n\n const mode = {\n given: data.modeGiven,\n want: data.modeWant\n };\n const acs = new AccessMode(mode);\n const pres = (!acs.mode || acs.mode == AccessMode._NONE) ?\n // Subscription deleted.\n {\n what: 'gone',\n src: data.topic\n } :\n // New subscription or subscription updated.\n {\n what: 'acs',\n src: data.topic,\n dacs: mode\n };\n this.getMeTopic()._routePres(pres);\n break;\n\n default:\n this.logger(\"Unknown push type ignored\", data.what);\n }\n }\n\n /**\n * @typedef GetQuery\n * @type {Object}\n * @property {GetOptsType=} desc - If provided (even if empty), fetch topic description.\n * @property {GetOptsType=} sub - If provided (even if empty), fetch topic subscriptions.\n * @property {GetDataType=} data - If provided (even if empty), get messages.\n */\n\n /**\n * @typedef GetOptsType\n * @type {Object}\n * @property {Date=} ims - \"If modified since\", fetch data only it was was modified since stated date.\n * @property {number=} limit - Maximum number of results to return. Ignored when querying topic description.\n */\n\n /**\n * @typedef GetDataType\n * @type {Object}\n * @property {number=} since - Load messages with seq id equal or greater than this value.\n * @property {number=} before - Load messages with seq id lower than this number.\n * @property {number=} limit - Maximum number of results to return.\n */\n\n /**\n * Request topic metadata\n *\n * @param {string} topic - Name of the topic to query.\n * @param {GetQuery} params - Parameters of the query. Use {@link Tinode.MetaGetBuilder} to generate.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n getMeta(topic, params) {\n const pkt = this.#initPacket('get', topic);\n\n pkt.get = mergeObj(pkt.get, params);\n\n return this.#send(pkt, pkt.get.id);\n }\n\n /**\n * Update topic's metadata: description, subscribtions.\n *\n * @param {string} topic - Topic to update.\n * @param {SetParams} params - topic metadata to update.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n setMeta(topic, params) {\n const pkt = this.#initPacket('set', topic);\n const what = [];\n\n if (params) {\n ['desc', 'sub', 'tags', 'cred', 'ephemeral'].forEach(function(key) {\n if (params.hasOwnProperty(key)) {\n what.push(key);\n pkt.set[key] = params[key];\n }\n });\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n if (what.length == 0) {\n return Promise.reject(new Error(\"Invalid {set} parameters\"));\n }\n\n return this.#send(pkt, pkt.set.id);\n }\n\n /**\n * Range of message IDs to delete.\n *\n * @typedef DelRange\n * @type {Object}\n * @property {number} low - low end of the range, inclusive (closed).\n * @property {number=} hi - high end of the range, exclusive (open).\n */\n /**\n * Delete some or all messages in a topic.\n *\n * @param {string} topic - Topic name to delete messages from.\n * @param {DelRange[]} list - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delMessages(topic, ranges, hard) {\n const pkt = this.#initPacket('del', topic);\n\n pkt.del.what = 'msg';\n pkt.del.delseq = ranges;\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete the topic alltogether. Requires Owner permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {boolean} hard - hard-delete topic.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delTopic(topicName, hard) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'topic';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete subscription. Requires Share permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delSubscription(topicName, user) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'sub';\n pkt.del.user = user;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete credential. Always sent on 'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n"],"names":["AccessMode","constructor","acs","given","decode","want","mode","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","i","length","bit","charAt","toUpperCase","encode","val","_INVALID","res","update","upd","action","val0","parts","split","diff","a1","a2","toString","jsonHelper","setMode","m","updateMode","u","getMode","setGiven","g","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","side","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","flag","includes","Error","CBuffer","compare_","unique_","undefined","a","b","getAt","at","buffer","getLast","put","insert","arguments","Array","isArray","idx","delAt","r","splice","delRange","since","before","reset","forEach","callback","startIdx","beforeIdx","context","call","find","elem","nearest","filter","count","isEmpty","arr","exact","start","end","pivot","found","CommError","message","code","name","PACKAGE_VERSION","PROTOCOL_VERSION","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_SYS","TOPIC_CHAN","TOPIC_GRP","TOPIC_P2P","USER_NEW","LOCAL_SEQID","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","EXPIRE_PROMISES_TIMEOUT","EXPIRE_PROMISES_PERIOD","RECV_TIMEOUT","DEFAULT_MESSAGES_PAGE","DEL_CHAR","jsonParseHelper","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","url","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","initialized","setNetworkProviders","wsProvider","xhrProvider","logger","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","_","prom","catch","XDR_UNSENT","XDR_OPENED","XDR_HEADERS_RECEIVED","XDR_LOADING","XDR_DONE","_lpURL","_poller","_sender","lp_sender","url_","sender","onreadystatechange","evt","readyState","status","open","lp_poller","resolve","poller","promiseCompleted","pkt","JSON","parse","responseText","ctrl","params","sid","send","onOpen","onMessage","onDisconnect","text","abort","err","OPEN","close","conn","onerror","onopen","onclose","onmessage","data","DB_VERSION","DB_NAME","IDBProvider","DB","onError","initDatabase","req","onsuccess","event","db","target","result","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","get","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","src","updUser","uid","pub","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","mapSubscriptions","getAll","addMessage","add","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","limit","openCursor","cursor","value","push","continue","setDatabaseProvider","idbProvider","source","f","hasOwnProperty","tags","_tags","setAccessMode","read","unread","max","dst","getAccessMode","fields","MAX_FORM_ELEMENTS","MAX_PREVIEW_ATTACHMENTS","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","DRAFTY_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","test","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","bin","atob","buf","ArrayBuffer","Uint8Array","charCodeAt","URL","createObjectURL","Blob","type","base64toDataUrl","DECORATORS","props","href","id","act","ref","mime","Drafty","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","init","plainText","content","lines","entityMap","entityIndex","blx","line","spans","entities","tag","concat","spannify","block","sort","toSpanTree","chunks","chunkify","drafty","draftify","extractEntities","ranges","entity","index","unique","tp","offset","len","key","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","Object","assign","quote","header","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","indexOf","appendButton","attachJSON","UNSAFE_toHTML","doc","tree","draftyToTree","htmlFormatter","values","join","treeBottomUp","format","original","formatter","shorten","light","shortenTree","lightEntity","treeToDrafty","forwardedContent","rmMention","node","parent","treeTopDown","lTrim","replyContent","convMNnQQnBR","startsWith","children","attachmentsToEnd","forwarding","toPlainText","isPlainText","toMarkdown","mdFormatter","def","isValid","txt_type","hasAttachments","attachments","hasEntities","styles","sanitizeEntities","copyEntData","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","span","chunk","chld","re_start","re_end","exec","start_offset","lastIndexOf","end_offset","last","spansToTree","flatten","child","addNode","n","substring","att","subspans","inner","keymap","c","keys","newKey","transformer","stack","pop","tail","shortener","allow","lightCopy","trimStart","shift","match","extracted","el","startAt","plain","entries","dc","module","exports","isUrlRelative","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","e","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","window","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","setNetworkProvider","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","withTags","withCred","withDel","withLaterDel","_maxDel","extract","build","getOwnPropertyNames","updated","isP2PType","Const","mergeObj","mergeToCache","normalizeArray","Topic","callbacks","created","touched","Date","private","trusted","_users","_queuedSeqId","_noEarlierMsgs","_recvNotificationTimer","_credentials","_messageVersions","_messages","_attached","_new","_delayedLeaveTimer","onData","onMeta","onPres","onInfo","onMetaDesc","onMetaSub","onSubsUpdated","onTagsUpdated","onCredsUpdated","onDeleteTopic","onAllMessagesReceived","topicType","types","isMeTopicName","isGroupTopicName","isP2PTopicName","isCommTopicName","isNewGroupTopicName","isChannelTopicName","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","desc","_noForwarding","_processMetaDesc","createMessage","noEcho","publish","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_db","_cancelled","_fatal","leave","unsub","_resetSub","_gone","leaveDelayed","delay","getMeta","getMessagesPage","forward","startMetaQuery","_loadMessages","promise","setMeta","_processMetaSub","_processMetaTags","cred","_processMetaCreds","subscriber","am","invite","archive","arch","delMessages","hard","r1","r2","low","hi","tosend","reduce","out","del","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","list","prev","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","_refreshContact","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","recv","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","cb","origSeq","versions","messages","sinceId","beforeId","msgs","unused1","unused2","_isReplacementMsg","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","msgHasMoreMessages","newer","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isArchived","isMeType","isChannelType","isGroupType","isCommType","isMe","head","replace","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","clear","delseq","_routePres","pres","online","isTopicCached","dacs","_routeInfo","info","subs","deleted","_updateCachedUser","creds","_allMessagesReceived","obj","cached","_cachePutUser","_updateReceived","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","updateCount","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","method","contacts","getContact","getCredentials","TopicFnd","_contacts","indexBy","getPrototypeOf","prototype","date","isNaN","isValidDate","d","getTime","rfc3339DateString","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","ignore","prop","cache","newval","simplify","t","trim","toLowerCase","item","pos","ary","DBCache","WebSocket","XMLHttpRequest","IndexedDBProvider","indexedDB","initForNonBrowserApp","chars","btoa","global","input","output","charCode","bc","bs","String","fromCharCode","detectTransport","b64EncodeUnicode","encodeURIComponent","toSolidBytes","p1","jsonBuildHelper","jsonLoggerHelper","getBrowserInfo","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","Tinode","onComplete","floor","_appName","appName","_platform","platform","navigator","_browser","userAgent","_hwos","_humanLanguage","language","_connection","_persist","persist","all","_loggingEnabled","dateString","args","console","log","credential","getVersion","getLibrary","isNullValue","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","searchParams","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","hello","_serverInfo","onConnect","setDeviceToken","dt","sent","_deviceToken","loginBasic","uname","_login","loginToken","requestResetAuthSecret","expires","now","setAuthToken","dft","oobNotification","_trimLongStrings","stringify","xfrom","finally","modeGiven","modeWant","delCurrentUser","func","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_pendingPromises","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_cache","_cacheDelUser","onLogin","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"tinode.dev.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;ACLa;AAAA;AAAA;AAcE,MAAMA,UAAU,CAAC;EAC9BC,WAAW,CAACC,GAAG,EAAE;IACf,IAAIA,GAAG,EAAE;MACP,IAAI,CAACC,KAAK,GAAG,O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I22B,CAAC,EAAE;QACLA,CAAC,GAAGA,CAAC,CAACC,IAAI,EAAE,CAACC,WAAW,EAAE;QAC1B,IAAIF,CAAC,CAAC12B,MAAM,GAAG,CAAC,EAAE;UAChBqtB,GAAG,CAAC1b,IAAI,CAAC+kB,CAAC,CAAC;QACb;MACF;IACF;IACArJ,GAAG,CAAC/U,IAAI,EAAE,CAACrT,MAAM,CAAC,UAAS4xB,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAE;MACzC,OAAO,CAACD,GAAG,IAAID,IAAI,IAAIE,GAAG,CAACD,GAAG,GAAG,CAAC,CAAC;IACrC,CAAC,CAAC;EACJ;EACA,IAAIzJ,GAAG,CAACrtB,MAAM,IAAI,CAAC,EAAE;IAGnBqtB,GAAG,CAAC1b,IAAI,CAAClK,gDAAQ,CAAC;EACpB;EACA,OAAO4lB,GAAG;AACZ;;;;;;;;;;;;;;AC3KO,MAAMvnB,eAAe,GAAG,QAAQ;;;;;;UCAvC;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;;;;WCtBA;WACA;WACA;WACA;WACA;WACA,iCAAiC,WAAW;WAC5C;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,yCAAyC,wCAAwC;WACjF;WACA;WACA;;;;;WCPA;WACA;WACA;WACA;WACA,GAAG;WACH;WACA;WACA,CAAC;;;;;WCPD;;;;;WCAA;WACA;WACA;WACA,uDAAuD,iBAAiB;WACxE;WACA,gDAAgD,aAAa;WAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;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;AAAA;AAAA;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DAA0B;AACxD8R,MAAM,CAAChyB,mBAAmB,GAAGkgB,2DAAyB;AACtD8R,MAAM,CAAC/xB,uBAAuB,GAAGigB,+DAA6B;AAC9D8R,MAAM,CAAC9xB,mBAAmB,GAAGggB,2DAAyB;AACtD8R,MAAM,CAAC7xB,oBAAoB,GAAG+f,4DAA0B;AAGxD8R,MAAM,CAACxxB,QAAQ,GAAG0f,gDAAc;AAGhC8R,MAAM,CAAC2G,gBAAgB,GAAG,gBAAgB;AAC1C3G,MAAM,CAAC4G,oBAAoB,GAAG,oBAAoB;AAClD5G,MAAM,CAAC6G,aAAa,GAAG,aAAa;AACpC7G,MAAM,CAAC8G,oBAAoB,GAAG,mBAAmB;AACjD9G,MAAM,CAAC+G,mBAAmB,GAAG,SAAS,C","sources":["webpack://tinode/webpack/universalModuleDefinition","webpack://tinode/./src/access-mode.js","webpack://tinode/./src/cbuffer.js","webpack://tinode/./src/comm-error.js","webpack://tinode/./src/config.js","webpack://tinode/./src/connection.js","webpack://tinode/./src/db.js","webpack://tinode/./src/drafty.js","webpack://tinode/./src/large-file.js","webpack://tinode/./src/meta-builder.js","webpack://tinode/./src/topic.js","webpack://tinode/./src/utils.js","webpack://tinode/./version.js","webpack://tinode/webpack/bootstrap","webpack://tinode/webpack/runtime/compat get default export","webpack://tinode/webpack/runtime/define property getters","webpack://tinode/webpack/runtime/global","webpack://tinode/webpack/runtime/hasOwnProperty shorthand","webpack://tinode/webpack/runtime/make namespace object","webpack://tinode/./src/tinode.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"tinode\"] = factory();\n\telse\n\t\troot[\"tinode\"] = factory();\n})(this, () => {\nreturn ","/**\n * @file Access control model.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\n/**\n * Helper class for handling access mode.\n *\n * @class AccessMode\n * @memberof Tinode\n *\n * @param {AccessMode|Object=} acs - AccessMode to copy or access mode object received from the server.\n */\nexport default class AccessMode {\n constructor(acs) {\n if (acs) {\n this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);\n this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);\n this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :\n (this.given & this.want);\n }\n }\n\n static #checkFlag(val, side, flag) {\n side = side || 'mode';\n if (['given', 'want', 'mode'].includes(side)) {\n return ((val[side] & flag) != 0);\n }\n throw new Error(`Invalid AccessMode component '${side}'`);\n }\n /**\n * Parse string into an access mode value.\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {string | Number} mode - either a String representation of the access mode to parse or a set of bits to assign.\n * @returns {number} - Access mode as a numeric value.\n */\n static decode(str) {\n if (!str) {\n return null;\n } else if (typeof str == 'number') {\n return str & AccessMode._BITMASK;\n } else if (str === 'N' || str === 'n') {\n return AccessMode._NONE;\n }\n\n const bitmask = {\n 'J': AccessMode._JOIN,\n 'R': AccessMode._READ,\n 'W': AccessMode._WRITE,\n 'P': AccessMode._PRES,\n 'A': AccessMode._APPROVE,\n 'S': AccessMode._SHARE,\n 'D': AccessMode._DELETE,\n 'O': AccessMode._OWNER\n };\n\n let m0 = AccessMode._NONE;\n\n for (let i = 0; i < str.length; i++) {\n const bit = bitmask[str.charAt(i).toUpperCase()];\n if (!bit) {\n // Unrecognized bit, skip.\n continue;\n }\n m0 |= bit;\n }\n return m0;\n }\n /**\n * Convert numeric representation of the access mode into a string.\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to convert to a string.\n * @returns {string} - Access mode as a string.\n */\n static encode(val) {\n if (val === null || val === AccessMode._INVALID) {\n return null;\n } else if (val === AccessMode._NONE) {\n return 'N';\n }\n\n const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];\n let res = '';\n for (let i = 0; i < bitmask.length; i++) {\n if ((val & (1 << i)) != 0) {\n res = res + bitmask[i];\n }\n }\n return res;\n }\n /**\n * Update numeric representation of access mode with the new value. The value\n * is one of the following:\n * - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Add new element(s) to the buffer. Variadic: takes one or more arguments. If an array is passed as a single\n * argument, its elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive).\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive).\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = startIdx | 0;\n beforeIdx = beforeIdx || this.buffer.length;\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst DB_VERSION = 1;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = (event) => {\n resolve(event.target.result);\n };\n trx.onerror = (event) => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {Object} query - parameters of the message range to retrieve.\n * @param {number=} query.since - the least message ID to retrieve (inclusive).\n * @param {number=} query.before - the greatest message ID to retrieve (exclusive).\n * @param {number=} query.limit - the maximum number of messages to retrieve.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n const result = [];\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n const trx = this.db.transaction(['message']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev').onsuccess = (event) => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Private methods.\n\n // Serializable topic fields.\n static #topic_fields = ['created', 'updated', 'deleted', 'read', 'recv', 'seq', 'clear', 'defacs',\n 'creds', 'public', 'trusted', 'private', 'touched', '_deleted'\n ];\n\n // Copy data from src to Topic object.\n static #deserializeTopic(topic, src) {\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n topic[f] = src[f];\n }\n });\n if (Array.isArray(src.tags)) {\n topic._tags = src.tags;\n }\n if (src.acs) {\n topic.setAccessMode(src.acs);\n }\n topic.seq |= 0;\n topic.read |= 0;\n topic.unread = Math.max(0, topic.seq - topic.read);\n }\n\n // Copy values from 'src' to 'dst'. Allocate dst if it's null or undefined.\n static #serializeTopic(dst, src) {\n const res = dst || {\n name: src.name\n };\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n res[f] = src[f];\n }\n });\n if (Array.isArray(src._tags)) {\n res.tags = src._tags;\n }\n if (src.acs) {\n res.acs = src.getAccessMode().jsonHelper();\n }\n return res;\n }\n\n static #serializeSubscription(dst, topicName, uid, sub) {\n const fields = ['updated', 'mode', 'read', 'recv', 'clear', 'lastSeen', 'userAgent'];\n const res = dst || {\n topic: topicName,\n uid: uid\n };\n\n fields.forEach((f) => {\n if (sub.hasOwnProperty(f)) {\n res[f] = sub[f];\n }\n });\n\n return res;\n }\n\n static #serializeMessage(dst, msg) {\n // Serializable fields.\n const fields = ['topic', 'seq', 'ts', '_status', 'from', 'head', 'content'];\n const res = dst || {};\n fields.forEach((f) => {\n if (msg.hasOwnProperty(f)) {\n res[f] = msg[f];\n }\n });\n return res;\n }\n\n /**\n * To use DB in a non browser context, supply indexedDB provider.\n * @static\n * @memberof DB\n * @param idbProvider indexedDB provider, e.g. for node require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * Supports conversion of user keyboard input to formatted text:
\n * \n * - *abc* → abc
\n * - _abc_ → abc
\n * - ~abc~ →
abc \n * - `abc` → abc
\n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * \n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '
';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '',\n close: _ => ''\n },\n // Row: logic grouping of elements\n RW: {\n open: _ => '',\n close: _ => ''\n },\n // Quoted block.\n QQ: {\n open: _ => '',\n close: _ => '',\n props: (data) => {\n return data ? {} : null;\n },\n },\n // Video call\n VC: {\n open: _ => '',\n close: _ => '',\n props: data => {\n if (!data) return {};\n return {\n 'data-duration': data.duration,\n 'data-state': data.state,\n };\n }\n },\n // Video.\n VD: {\n open: data => {\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = data.ref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * @typedef Drafty.ImageDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the image, e.g. \"image/png\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded image content. Could be null/undefined.\n * @param {string} preview - base64-encoded thumbnail of the image.\n * @param {integer} width - width of the image.\n * @param {integer} height - height of the image.\n * @param {string} filename - file name suggestion for downloading the image.\n * @param {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.VideoDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @param {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @param {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @param {integer} width - width of the video.\n * @param {integer} height - height of the video.\n * @param {integer} duration - duration of the video.\n * @param {string} filename - file name suggestion for downloading the video.\n * @param {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @param {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.AudioDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded audio content. Could be null/undefined.\n * @param {integer} duration - duration of the record in milliseconds.\n * @param {string} preview - base64 encoded short array of amplitude values 0..100.\n * @param {string} filename - file name suggestion for downloading the audio.\n * @param {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * @typedef Drafty.AttachmentDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @param {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @param {string} filename - file name suggestion for downloading the attachment.\n * @param {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @param {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n mergeObj,\n mergeToCache,\n normalizeArray\n} from './utils.js';\n\nexport class Topic {\n /**\n * @callback Tinode.Topic.onData\n * @param {Data} data - Data packet\n */\n /**\n * Topic is a class representing a logical communication channel.\n * @class Topic\n * @memberof Tinode\n *\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {Tinode.Topic.onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic is subscribed.\n * @memberof Tinode.Topic#\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data) {\n if (data.ref) {\n attachments.push(data.ref);\n }\n if (data.preref) {\n attachments.push(data.preref);\n }\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {boolean} forward if true, request newer messages.\n */\n getMessagesPage(limit, forward) {\n let query = forward ?\n this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n\n // First try fetching from DB, then from the server.\n return this._loadMessages(this._tinode._db, query.extract('data'))\n .then((count) => {\n if (count == limit) {\n // Got enough messages from local cache.\n return Promise.resolve({\n topic: this.name,\n code: 200,\n params: {\n count: count\n }\n });\n }\n\n // Reduce the count of requested messages.\n limit -= count;\n // Update query with new values loaded from DB.\n query = forward ? this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n let promise = this.getMeta(query.build());\n if (!forward) {\n promise = promise.then(ctrl => {\n if (ctrl && ctrl.params && !ctrl.params.count) {\n this._noEarlierMsgs = true;\n }\n });\n }\n return promise;\n });\n }\n /**\n * Update topic metadata.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n if (params.tags) {\n params.tags = normalizeArray(params.tags);\n }\n // Send Set message, handle async response.\n return this._tinode.setMeta(this.name, params)\n .then(ctrl => {\n if (ctrl && ctrl.code >= 300) {\n // Not modified\n return ctrl;\n }\n\n if (params.sub) {\n params.sub.topic = this.name;\n if (ctrl.params && ctrl.params.acs) {\n params.sub.acs = ctrl.params.acs;\n params.sub.updated = ctrl.ts;\n }\n if (!params.sub.user) {\n // This is a subscription update of the current user.\n // Assign user ID otherwise the update will be ignored by _processMetaSub.\n params.sub.user = this._tinode.getCurrentUserID();\n if (!params.desc) {\n // Force update to topic's asc.\n params.desc = {};\n }\n }\n params.sub._noForwarding = true;\n this._processMetaSub([params.sub]);\n }\n\n if (params.desc) {\n if (ctrl.params && ctrl.params.acs) {\n params.desc.acs = ctrl.params.acs;\n params.desc.updated = ctrl.ts;\n }\n this._processMetaDesc(params.desc);\n }\n\n if (params.tags) {\n this._processMetaTags(params.tags);\n }\n if (params.cred) {\n this._processMetaCreds([params.cred], true);\n }\n\n return ctrl;\n });\n }\n /**\n * Update access mode of the current user or of another topic subsriber.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - UID of the user to update or null to update current user.\n * @param {string} update - the update value, full or delta.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n updateMode(uid, update) {\n const user = uid ? this.subscriber(uid) : null;\n const am = user ?\n user.acs.updateGiven(update).getGiven() :\n this.getAccessMode().updateWant(update).getWant();\n\n return this.setMeta({\n sub: {\n user: uid,\n mode: am\n }\n });\n }\n /**\n * Create new topic subscription. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to invite\n * @param {string=} mode - Access mode. null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.DelRange[]} ranges - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessages(ranges, hard) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete messages in inactive topic\"));\n }\n\n // Sort ranges in accending order by low, the descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n let tosend = ranges.reduce((out, r) => {\n if (r.low < Const.LOCAL_SEQID) {\n if (!r.hi || r.hi < Const.LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: this._maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n\n // Send {del} message, return promise\n let result;\n if (tosend.length > 0) {\n result = this._tinode.delMessages(this.name, tosend, hard);\n } else {\n result = Promise.resolve({\n params: {\n del: 0\n }\n });\n }\n // Update local cache.\n return result.then(ctrl => {\n if (ctrl.params.del > this._maxDel) {\n this._maxDel = ctrl.params.del;\n }\n\n ranges.forEach((r) => {\n if (r.hi) {\n this.flushMessageRange(r.low, r.hi);\n } else {\n this.flushMessage(r.low);\n }\n });\n\n if (this.onData) {\n // Calling with no parameters to indicate the messages were deleted.\n this.onData();\n }\n return ctrl;\n });\n }\n /**\n * Delete all messages. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesAll(hardDel) {\n if (!this._maxSeq || this._maxSeq <= 0) {\n // There are no messages to delete.\n return Promise.resolve();\n }\n return this.delMessages([{\n low: 1,\n hi: this._maxSeq + 1,\n _all: true\n }], hardDel);\n }\n\n /**\n * Delete multiple messages defined by their IDs. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {Array.} list - list of seq IDs to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesList(list, hardDel) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n let ranges = list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n // Send {del} message, return promise\n return this.delMessages(ranges, hardDel);\n }\n\n /**\n * Delete original message and edited variants. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delMessagesEdits(seq, hardDel) {\n const list = [seq];\n this.messageVersions(seq, msg => list.push(msg.seq));\n // Send {del} message, return promise\n return this.delMessagesList(list, hardDel);\n }\n\n /**\n * Delete topic. Requires Owner permission. Wrapper for {@link Tinode#delTopic}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hard - had-delete topic.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delTopic(hard) {\n if (this._deleted) {\n // The topic is already deleted at the server, just remove from DB.\n this._gone();\n return Promise.resolve(null);\n }\n\n return this._tinode.delTopic(this.name, hard).then(ctrl => {\n this._deleted = true;\n this._resetSub();\n this._gone();\n return ctrl;\n });\n }\n /**\n * Delete subscription. Requires Share permission. Wrapper for {@link Tinode#delSubscription}.\n * @memberof Tinode.Topic#\n *\n * @param {string} user - ID of the user to remove subscription for.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delSubscription(user) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete subscription in inactive topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delSubscription(this.name, user).then(ctrl => {\n // Remove the object from the subscription cache;\n delete this._users[user];\n // Notify listeners\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n return ctrl;\n });\n }\n /**\n * Send a read/recv notification.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what notification to send: recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.} a copy of tags\n */\n tags() {\n // Return a copy.\n return this._tags.slice(0);\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (this._isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by seq.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} newer - if true, check for newer messages only.\n */\n msgHasMoreMessages(newer) {\n return newer ? this.seq > this._maxSeq :\n // _minSeq could be more than 1, but earlier messages could have been deleted.\n (this._minSeq > 1 && !this._noEarlierMsgs);\n }\n /**\n * Check if the given seq Id is id of the most recent message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to check\n */\n isNewMessage(seqId) {\n return this._maxSeq <= seqId;\n }\n /**\n * Remove one message from local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to remove from cache.\n * @returns {Message} removed message or undefined if such message was not found.\n */\n flushMessage(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n delete this._messageVersions[seqId];\n if (idx >= 0) {\n this._tinode._db.remMessages(this.name, seqId);\n return this._messages.delAt(idx);\n }\n return undefined;\n }\n /**\n * Remove a range of messages from the local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} fromId seq ID of the first message to remove (inclusive).\n * @param {number} untilId seqID of the last message to remove (exclusive).\n *\n * @returns {Message[]} array of removed messages (could be empty).\n */\n flushMessageRange(fromId, untilId) {\n // Remove range from persistent cache.\n this._tinode._db.remMessages(this.name, fromId, untilId);\n\n // Remove all versions keyed by IDs in the range.\n for (let i = fromId; i < untilId; i++) {\n delete this._messageVersions[i];\n }\n\n // start, end: find insertion points (nearest == true).\n const since = this._messages.find({\n seq: fromId\n }, true);\n return since >= 0 ? this._messages.delRange(since, this._messages.find({\n seq: untilId\n }, true)) : [];\n }\n /**\n * Update message's seqId.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub message object.\n * @param {number} newSeqId new seq id for pub.\n */\n swapMessageId(pub, newSeqId) {\n const idx = this._messages.find(pub);\n const numMessages = this._messages.length();\n if (0 <= idx && idx < numMessages) {\n // Remove message with the old seq ID.\n this._messages.delAt(idx);\n this._tinode._db.remMessages(this.name, pub.seq);\n // Add message with the new seq ID.\n pub.seq = newSeqId;\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n }\n }\n /**\n * Attempt to stop message from being sent.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to stop sending and remove from cache.\n *\n * @returns {boolean} true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n _isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!this._isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags.length == 1 && tags[0] == Const.DEL_CHAR) {\n tags = [];\n }\n this._tags = tags;\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n const topic = this;\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(function(range) {\n if (!range.hi) {\n count++;\n topic.flushMessage(range.low);\n } else {\n for (let i = range.low; i < range.hi; i++) {\n count++;\n topic.flushMessage(i);\n }\n }\n });\n }\n\n if (count > 0) {\n // this._updateDeletedRanges();\n\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, params) {\n const {\n since,\n before,\n limit\n } = params || {};\n return db.readMessages(this.name, {\n since: since,\n before: before,\n limit: limit || Const.DEFAULT_MESSAGES_PAGE\n })\n .then(msgs => {\n msgs.forEach((data) => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n return msgs.length;\n });\n }\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n\n/**\n * @class TopicFnd - special case of {@link Tinode.Topic} for searching for\n * contacts and group topics.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter(function(item, pos, ary) {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n","export const PACKAGE_VERSION = \"0.21.0\";\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n Topic,\n TopicMe,\n TopicFnd\n} from './topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format /\n this._appName = config.appName || \"Undefined\";\n\n // API Key.\n this._apiKey = config.apiKey;\n\n // Name and version of the browser.\n this._platform = config.platform || 'web';\n // Underlying OS.\n if (typeof navigator != 'undefined') {\n this._browser = getBrowserInfo(navigator.userAgent, navigator.product);\n this._hwos = navigator.platform;\n // This is the default language. It could be changed by client.\n this._humanLanguage = navigator.language || 'en-US';\n }\n\n Connection.logger = this.logger;\n Drafty.logger = this.logger;\n\n // WebSocket or long polling network connection.\n if (config.transport != 'lp' && config.transport != 'ws') {\n config.transport = detectTransport();\n }\n this._connection = new Connection(config, Const.PROTOCOL_VERSION, /* autoreconnect */ true);\n this._connection.onMessage = (data) => {\n // Call the main message dispatcher.\n this.#dispatchMessage(data);\n }\n\n // Ready to start sending.\n this._connection.onOpen = _ => this.#connectionOpen();\n this._connection.onDisconnect = (err, code) => this.#disconnected(err, code);\n\n // Wrapper for the reconnect iterator callback.\n this._connection.onAutoreconnectIteration = (timeout, promise) => {\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout, promise);\n }\n }\n\n this._persist = config.persist;\n // Initialize object regardless. It simplifies the code.\n this._db = new DBCache(err => {\n this.logger('DB', err);\n }, this.logger);\n\n if (this._persist) {\n // Create the persistent cache.\n // Store promises to be resolved when messages load into memory.\n const prom = [];\n this._db.initDatabase().then(_ => {\n // First load topics into memory.\n return this._db.mapTopics((data) => {\n let topic = this.#cacheGet('topic', data.name);\n if (topic) {\n return;\n }\n if (data.name == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (data.name == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(data.name);\n }\n this._db.deserializeTopic(topic, data);\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Topic loaded from DB is not new.\n delete topic._new;\n // Request to load messages and save the promise.\n prom.push(topic._loadMessages(this._db));\n });\n }).then(_ => {\n // Then load users.\n return this._db.mapUsers((data) => {\n this.#cachePut('user', data.uid, mergeObj({}, data.public));\n });\n }).then(_ => {\n // Now wait for all messages to finish loading.\n return Promise.all(prom);\n }).then(_ => {\n if (onComplete) {\n onComplete();\n }\n this.logger(\"Persistent cache initialized.\");\n }).catch(err => {\n if (onComplete) {\n onComplete(err);\n }\n this.logger(\"Failed to initialize persistent cache:\", err);\n });\n } else {\n this._db.deleteDatabase().then(_ => {\n if (onComplete) {\n onComplete();\n }\n });\n }\n }\n\n // Private methods.\n\n // Console logger. Babel somehow fails to parse '...rest' parameter.\n logger(str, ...args) {\n if (this._loggingEnabled) {\n const d = new Date();\n const dateString = ('0' + d.getUTCHours()).slice(-2) + ':' +\n ('0' + d.getUTCMinutes()).slice(-2) + ':' +\n ('0' + d.getUTCSeconds()).slice(-2) + '.' +\n ('00' + d.getUTCMilliseconds()).slice(-3);\n\n console.log('[' + dateString + ']', str, args.join(' '));\n }\n }\n\n // Generator of default promises for sent packets.\n #makePromise(id) {\n let promise = null;\n if (id) {\n promise = new Promise((resolve, reject) => {\n // Stored callbacks will be called when the response packet with this Id arrives\n this._pendingPromises[id] = {\n 'resolve': resolve,\n 'reject': reject,\n 'ts': new Date()\n };\n });\n }\n return promise;\n };\n\n // Resolve or reject a pending promise.\n // Unresolved promises are stored in _pendingPromises.\n #execPromise(id, code, onOK, errorText) {\n const callbacks = this._pendingPromises[id];\n if (callbacks) {\n delete this._pendingPromises[id];\n if (code >= 200 && code < 400) {\n if (callbacks.resolve) {\n callbacks.resolve(onOK);\n }\n } else if (callbacks.reject) {\n callbacks.reject(new CommError(errorText, code));\n }\n }\n }\n\n // Send a packet. If packet id is provided return a promise.\n #send(pkt, id) {\n let promise;\n if (id) {\n promise = this.#makePromise(id);\n }\n pkt = simplify(pkt);\n let msg = JSON.stringify(pkt);\n this.logger(\"out: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : msg));\n try {\n this._connection.sendText(msg);\n } catch (err) {\n // If sendText throws, wrap the error in a promise or rethrow.\n if (id) {\n this.#execPromise(id, Connection.NETWORK_ERROR, null, err.message);\n } else {\n throw err;\n }\n }\n return promise;\n }\n\n // The main message dispatcher.\n #dispatchMessage(data) {\n // Skip empty response. This happens when LP times out.\n if (!data)\n return;\n\n this._inPacketCount++;\n\n // Send raw message to listener\n if (this.onRawMessage) {\n this.onRawMessage(data);\n }\n\n if (data === '0') {\n // Server response to a network probe.\n if (this.onNetworkProbe) {\n this.onNetworkProbe();\n }\n // No processing is necessary.\n return;\n }\n\n let pkt = JSON.parse(data, jsonParseHelper);\n if (!pkt) {\n this.logger(\"in: \" + data);\n this.logger(\"ERROR: failed to parse data\");\n } else {\n this.logger(\"in: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : data));\n\n // Send complete packet to listener\n if (this.onMessage) {\n this.onMessage(pkt);\n }\n\n if (pkt.ctrl) {\n // Handling {ctrl} message\n if (this.onCtrlMessage) {\n this.onCtrlMessage(pkt.ctrl);\n }\n\n // Resolve or reject a pending promise, if any\n if (pkt.ctrl.id) {\n this.#execPromise(pkt.ctrl.id, pkt.ctrl.code, pkt.ctrl, pkt.ctrl.text);\n }\n setTimeout(_ => {\n if (pkt.ctrl.code == 205 && pkt.ctrl.text == 'evicted') {\n // User evicted from topic.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._resetSub();\n if (pkt.ctrl.params && pkt.ctrl.params.unsub) {\n topic._gone();\n }\n }\n } else if (pkt.ctrl.code < 300 && pkt.ctrl.params) {\n if (pkt.ctrl.params.what == 'data') {\n // code=208, all messages received: \"params\":{\"count\":11,\"what\":\"data\"},\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._allMessagesReceived(pkt.ctrl.params.count);\n }\n } else if (pkt.ctrl.params.what == 'sub') {\n // code=204, the topic has no (refreshed) subscriptions.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n // Trigger topic.onSubsUpdated.\n topic._processMetaSub([]);\n }\n }\n }\n }, 0);\n } else {\n setTimeout(_ => {\n if (pkt.meta) {\n // Handling a {meta} message.\n // Preferred API: Route meta to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.meta.topic);\n if (topic) {\n topic._routeMeta(pkt.meta);\n }\n\n if (pkt.meta.id) {\n this.#execPromise(pkt.meta.id, 200, pkt.meta, 'META');\n }\n\n // Secondary API: callback\n if (this.onMetaMessage) {\n this.onMetaMessage(pkt.meta);\n }\n } else if (pkt.data) {\n // Handling {data} message\n // Preferred API: Route data to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.data.topic);\n if (topic) {\n topic._routeData(pkt.data);\n }\n\n // Secondary API: Call callback\n if (this.onDataMessage) {\n this.onDataMessage(pkt.data);\n }\n } else if (pkt.pres) {\n // Handling {pres} message\n // Preferred API: Route presence to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.pres.topic);\n if (topic) {\n topic._routePres(pkt.pres);\n }\n\n // Secondary API - callback\n if (this.onPresMessage) {\n this.onPresMessage(pkt.pres);\n }\n } else if (pkt.info) {\n // {info} message - read/received notifications and key presses\n // Preferred API: Route {info}} to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.info.topic);\n if (topic) {\n topic._routeInfo(pkt.info);\n }\n\n // Secondary API - callback\n if (this.onInfoMessage) {\n this.onInfoMessage(pkt.info);\n }\n } else {\n this.logger(\"ERROR: Unknown packet received.\");\n }\n }, 0);\n }\n }\n }\n\n // Connection open, ready to start sending.\n #connectionOpen() {\n if (!this._expirePromises) {\n // Reject promises which have not been resolved for too long.\n this._expirePromises = setInterval(_ => {\n const err = new CommError(\"timeout\", 504);\n const expires = new Date(new Date().getTime() - Const.EXPIRE_PROMISES_TIMEOUT);\n for (let id in this._pendingPromises) {\n let callbacks = this._pendingPromises[id];\n if (callbacks && callbacks.ts < expires) {\n this.logger(\"Promise expired\", id);\n delete this._pendingPromises[id];\n if (callbacks.reject) {\n callbacks.reject(err);\n }\n }\n }\n }, Const.EXPIRE_PROMISES_PERIOD);\n }\n this.hello();\n }\n\n #disconnected(err, code) {\n this._inPacketCount = 0;\n this._serverInfo = null;\n this._authenticated = false;\n\n if (this._expirePromises) {\n clearInterval(this._expirePromises);\n this._expirePromises = null;\n }\n\n // Mark all topics as unsubscribed\n this.#cacheMap('topic', (topic, key) => {\n topic._resetSub();\n });\n\n // Reject all pending promises\n for (let key in this._pendingPromises) {\n const callbacks = this._pendingPromises[key];\n if (callbacks && callbacks.reject) {\n callbacks.reject(err);\n }\n }\n this._pendingPromises = {};\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n }\n\n // Get User Agent string\n #getUserAgent() {\n return this._appName + ' (' + (this._browser ? this._browser + '; ' : '') + this._hwos + '); ' + Const.LIBRARY;\n }\n\n // Generator of packets stubs\n #initPacket(type, topic) {\n switch (type) {\n case 'hi':\n return {\n 'hi': {\n 'id': this.getNextUniqueId(),\n 'ver': Const.VERSION,\n 'ua': this.#getUserAgent(),\n 'dev': this._deviceToken,\n 'lang': this._humanLanguage,\n 'platf': this._platform\n }\n };\n\n case 'acc':\n return {\n 'acc': {\n 'id': this.getNextUniqueId(),\n 'user': null,\n 'scheme': null,\n 'secret': null,\n 'tmpscheme': null,\n 'tmpsecret': null,\n 'login': false,\n 'tags': null,\n 'desc': {},\n 'cred': {}\n }\n };\n\n case 'login':\n return {\n 'login': {\n 'id': this.getNextUniqueId(),\n 'scheme': null,\n 'secret': null\n }\n };\n\n case 'sub':\n return {\n 'sub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'set': {},\n 'get': {}\n }\n };\n\n case 'leave':\n return {\n 'leave': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'unsub': false\n }\n };\n\n case 'pub':\n return {\n 'pub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'noecho': false,\n 'head': null,\n 'content': {}\n }\n };\n\n case 'get':\n return {\n 'get': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'desc': {},\n 'sub': {},\n 'data': {}\n }\n };\n\n case 'set':\n return {\n 'set': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'desc': {},\n 'sub': {},\n 'tags': [],\n 'ephemeral': {}\n }\n };\n\n case 'del':\n return {\n 'del': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'delseq': null,\n 'user': null,\n 'hard': false\n }\n };\n\n case 'note':\n return {\n 'note': {\n // no id by design (except calls).\n 'topic': topic,\n 'what': null, // one of \"recv\", \"read\", \"kp\", \"call\"\n 'seq': undefined // the server-side message id acknowledged as received or read.\n }\n };\n\n default:\n throw new Error(`Unknown packet type requested: ${type}`);\n }\n }\n\n // Cache management\n #cachePut(type, name, obj) {\n this._cache[type + ':' + name] = obj;\n }\n #cacheGet(type, name) {\n return this._cache[type + ':' + name];\n }\n #cacheDel(type, name) {\n delete this._cache[type + ':' + name];\n }\n\n // Enumerate all items in cache, call func for each item.\n // Enumeration stops if func returns true.\n #cacheMap(type, func, context) {\n const key = type ? type + ':' : undefined;\n for (let idx in this._cache) {\n if (!key || idx.indexOf(key) == 0) {\n if (func.call(context, this._cache[idx], idx)) {\n break;\n }\n }\n }\n }\n\n // Make limited cache management available to topic.\n // Caching user.public only. Everything else is per-topic.\n #attachCacheToTopic(topic) {\n topic._tinode = this;\n\n topic._cacheGetUser = (uid) => {\n const pub = this.#cacheGet('user', uid);\n if (pub) {\n return {\n user: uid,\n public: mergeObj({}, pub)\n };\n }\n return undefined;\n };\n topic._cachePutUser = (uid, user) => {\n this.#cachePut('user', uid, mergeObj({}, user.public));\n };\n topic._cacheDelUser = (uid) => {\n this.#cacheDel('user', uid);\n };\n topic._cachePutSelf = _ => {\n this.#cachePut('topic', topic.name, topic);\n };\n topic._cacheDelSelf = _ => {\n this.#cacheDel('topic', topic.name);\n };\n }\n\n // On successful login save server-provided data.\n #loginSuccessful(ctrl) {\n if (!ctrl.params || !ctrl.params.user) {\n return ctrl;\n }\n // This is a response to a successful login,\n // extract UID and security token, save it in Tinode module\n this._myUID = ctrl.params.user;\n this._authenticated = (ctrl && ctrl.code >= 200 && ctrl.code < 300);\n if (ctrl.params && ctrl.params.token && ctrl.params.expires) {\n this._authToken = {\n token: ctrl.params.token,\n expires: ctrl.params.expires\n };\n } else {\n this._authToken = null;\n }\n\n if (this.onLogin) {\n this.onLogin(ctrl.code, ctrl.text);\n }\n\n return ctrl;\n }\n\n // Static methods.\n /**\n * Helper method to package account credential.\n *\n * @param {string | Credential} meth - validation method or object with validation data.\n * @param {string=} val - validation value (e.g. email or phone number).\n * @param {Object=} params - validation parameters.\n * @param {string=} resp - validation response.\n *\n * @returns {Array.} array with a single credential or null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.} tags - array of string tags for user discovery.\n * @property {string} scheme - Temporary authentication scheme for password reset.\n * @property {string} secret - Temporary authentication secret for password reset.\n * @property {Array.=} attachments - Array of references to out of band attachments used in account description.\n */\n /**\n * @typedef DefAcs\n * @type {Object}\n * @property {string=} auth - Access mode for me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.=} attachments - URLs of out of band attachments used in parameters.\n */\n /**\n * @typedef SetDesc\n * @type {Object}\n * @property {DefAcs=} defacs - Default access mode.\n * @property {Object=} public - Free-form topic description, publically accessible.\n * @property {Object=} private - Free-form topic description accessible only to the owner.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n */\n /**\n * @typedef SetSub\n * @type {Object}\n * @property {string=} user - UID of the user affected by the request. Default (empty) - current user.\n * @property {string=} mode - User access mode, either requested or assigned dependent on context.\n */\n /**\n * Send a topic subscription request.\n *\n * @param {string} topic - Name of the topic to subscribe to.\n * @param {GetQuery=} getParams - Optional subscription metadata query\n * @param {SetParams=} setParams - Optional initialization parameters\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n subscribe(topicName, getParams, setParams) {\n const pkt = this.#initPacket('sub', topicName)\n if (!topicName) {\n topicName = Const.TOPIC_NEW;\n }\n\n pkt.sub.get = getParams;\n\n if (setParams) {\n if (setParams.sub) {\n pkt.sub.set.sub = setParams.sub;\n }\n\n if (setParams.desc) {\n const desc = setParams.desc;\n if (Tinode.isNewGroupTopicName(topicName)) {\n // Full set.desc params are used for new topics only\n pkt.sub.set.desc = desc;\n } else if (Tinode.isP2PTopicName(topicName) && desc.defacs) {\n // Use optional default permissions only.\n pkt.sub.set.desc = {\n defacs: desc.defacs\n };\n }\n }\n\n // See if external objects were used in topic description.\n if (Array.isArray(setParams.attachments) && setParams.attachments.length > 0) {\n pkt.extra = {\n attachments: setParams.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n\n if (setParams.tags) {\n pkt.sub.set.tags = setParams.tags;\n }\n }\n return this.#send(pkt, pkt.sub.id);\n }\n\n /**\n * Detach and optionally unsubscribe from the topic\n *\n * @param {string} topic - Topic to detach from.\n * @param {boolean} unsub - If true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.=} attachments - array of URLs with attachments.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publishMessage(pub, attachments) {\n // Make a shallow copy. Needed in order to clear locally-assigned temp values;\n pub = Object.assign({}, pub);\n pub.seq = undefined;\n pub.from = undefined;\n pub.ts = undefined;\n const msg = {\n pub: pub,\n };\n if (attachments) {\n msg.extra = {\n attachments: attachments.filter(ref => isUrlRelative(ref))\n };\n }\n return this.#send(msg, pub.id);\n }\n\n /**\n * Out of band notification: notify topic that an external (push) notification was recived by the client.\n *\n * @param {object} data - notification payload.\n * @param {string} data.what - notification type, 'msg', 'read', 'sub'.\n * @param {string} data.topic - name of the updated topic.\n * @param {number=} data.seq - seq ID of the affected message.\n * @param {string=} data.xfrom - UID of the sender.\n * @param {object=} data.given - new subscription 'given', e.g. 'ASWP...'.\n * @param {object=} data.want - new subscription 'want', e.g. 'RWJ...'.\n */\n oobNotification(data) {\n this.logger('oob: ' + (this._trimLongStrings ? JSON.stringify(data, jsonLoggerHelper) : data));\n\n switch (data.what) {\n case 'msg':\n if (!data.seq || data.seq < 1 || !data.topic) {\n // Server sent invalid data.\n break;\n }\n\n if (!this.isConnected()) {\n // Let's ignore the message if there is no connection: no connection means there are no open\n // tabs with Tinode.\n break;\n }\n\n const topic = this.#cacheGet('topic', data.topic);\n if (!topic) {\n // TODO: check if there is a case when a message can arrive from an unknown topic.\n break;\n }\n\n if (topic.isSubscribed()) {\n // No need to fetch: topic is already subscribed and got data through normal channel.\n break;\n }\n\n if (topic.maxMsgSeq() < data.seq) {\n if (topic.isChannelType()) {\n topic._updateReceived(data.seq, 'fake-uid');\n }\n\n // New message.\n if (data.xfrom && !this.#cacheGet('user', data.xfrom)) {\n // Message from unknown sender, fetch description from the server.\n // Sending asynchronously without a subscription.\n this.getMeta(data.xfrom, new MetaGetBuilder().withDesc().build()).catch(err => {\n this.logger(\"Failed to get the name of a new sender\", err);\n });\n }\n\n topic.subscribe(null).then(_ => {\n return topic.getMeta(new MetaGetBuilder(topic).withLaterData(24).withLaterDel(24).build());\n }).then(_ => {\n // Allow data fetch to complete and get processed successfully.\n topic.leaveDelayed(false, 1000);\n }).catch(err => {\n this.logger(\"On push data fetch failed\", err);\n }).finally(_ => {\n this.getMeTopic()._refreshContact('msg', topic);\n });\n }\n break;\n\n case 'read':\n this.getMeTopic()._routePres({\n what: 'read',\n seq: data.seq\n });\n break;\n\n case 'sub':\n if (!this.isMe(data.xfrom)) {\n // TODO: handle updates from other users.\n break;\n }\n\n const mode = {\n given: data.modeGiven,\n want: data.modeWant\n };\n const acs = new AccessMode(mode);\n const pres = (!acs.mode || acs.mode == AccessMode._NONE) ?\n // Subscription deleted.\n {\n what: 'gone',\n src: data.topic\n } :\n // New subscription or subscription updated.\n {\n what: 'acs',\n src: data.topic,\n dacs: mode\n };\n this.getMeTopic()._routePres(pres);\n break;\n\n default:\n this.logger(\"Unknown push type ignored\", data.what);\n }\n }\n\n /**\n * @typedef GetQuery\n * @type {Object}\n * @property {GetOptsType=} desc - If provided (even if empty), fetch topic description.\n * @property {GetOptsType=} sub - If provided (even if empty), fetch topic subscriptions.\n * @property {GetDataType=} data - If provided (even if empty), get messages.\n */\n\n /**\n * @typedef GetOptsType\n * @type {Object}\n * @property {Date=} ims - \"If modified since\", fetch data only it was was modified since stated date.\n * @property {number=} limit - Maximum number of results to return. Ignored when querying topic description.\n */\n\n /**\n * @typedef GetDataType\n * @type {Object}\n * @property {number=} since - Load messages with seq id equal or greater than this value.\n * @property {number=} before - Load messages with seq id lower than this number.\n * @property {number=} limit - Maximum number of results to return.\n */\n\n /**\n * Request topic metadata\n *\n * @param {string} topic - Name of the topic to query.\n * @param {GetQuery} params - Parameters of the query. Use {@link Tinode.MetaGetBuilder} to generate.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n getMeta(topic, params) {\n const pkt = this.#initPacket('get', topic);\n\n pkt.get = mergeObj(pkt.get, params);\n\n return this.#send(pkt, pkt.get.id);\n }\n\n /**\n * Update topic's metadata: description, subscribtions.\n *\n * @param {string} topic - Topic to update.\n * @param {SetParams} params - topic metadata to update.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n setMeta(topic, params) {\n const pkt = this.#initPacket('set', topic);\n const what = [];\n\n if (params) {\n ['desc', 'sub', 'tags', 'cred', 'ephemeral'].forEach(function(key) {\n if (params.hasOwnProperty(key)) {\n what.push(key);\n pkt.set[key] = params[key];\n }\n });\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n if (what.length == 0) {\n return Promise.reject(new Error(\"Invalid {set} parameters\"));\n }\n\n return this.#send(pkt, pkt.set.id);\n }\n\n /**\n * Range of message IDs to delete.\n *\n * @typedef DelRange\n * @type {Object}\n * @property {number} low - low end of the range, inclusive (closed).\n * @property {number=} hi - high end of the range, exclusive (open).\n */\n /**\n * Delete some or all messages in a topic.\n *\n * @param {string} topic - Topic name to delete messages from.\n * @param {DelRange[]} list - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delMessages(topic, ranges, hard) {\n const pkt = this.#initPacket('del', topic);\n\n pkt.del.what = 'msg';\n pkt.del.delseq = ranges;\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete the topic alltogether. Requires Owner permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {boolean} hard - hard-delete topic.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delTopic(topicName, hard) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'topic';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete subscription. Requires Share permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delSubscription(topicName, user) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'sub';\n pkt.del.user = user;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete credential. Always sent on 'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n"],"names":["AccessMode","constructor","acs","given","decode","want","mode","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","i","length","bit","charAt","toUpperCase","encode","val","_INVALID","res","update","upd","action","val0","parts","split","diff","a1","a2","toString","jsonHelper","setMode","m","updateMode","u","getMode","setGiven","g","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","side","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","flag","includes","Error","CBuffer","compare_","unique_","undefined","a","b","getAt","at","buffer","getLast","put","insert","arguments","Array","isArray","idx","delAt","r","splice","delRange","since","before","reset","forEach","callback","startIdx","beforeIdx","context","call","find","elem","nearest","filter","count","isEmpty","arr","exact","start","end","pivot","found","CommError","message","code","name","PACKAGE_VERSION","PROTOCOL_VERSION","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_SYS","TOPIC_CHAN","TOPIC_GRP","TOPIC_P2P","USER_NEW","LOCAL_SEQID","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","EXPIRE_PROMISES_TIMEOUT","EXPIRE_PROMISES_PERIOD","RECV_TIMEOUT","DEFAULT_MESSAGES_PAGE","DEL_CHAR","jsonParseHelper","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","url","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","initialized","setNetworkProviders","wsProvider","xhrProvider","logger","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","_","prom","catch","XDR_UNSENT","XDR_OPENED","XDR_HEADERS_RECEIVED","XDR_LOADING","XDR_DONE","_lpURL","_poller","_sender","lp_sender","url_","sender","onreadystatechange","evt","readyState","status","open","lp_poller","resolve","poller","promiseCompleted","pkt","JSON","parse","responseText","ctrl","params","sid","send","onOpen","onMessage","onDisconnect","text","abort","err","OPEN","close","conn","onerror","onopen","onclose","onmessage","data","DB_VERSION","DB_NAME","IDBProvider","DB","onError","initDatabase","req","onsuccess","event","db","target","result","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","get","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","src","updUser","uid","pub","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","mapSubscriptions","getAll","addMessage","add","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","limit","openCursor","cursor","value","push","continue","setDatabaseProvider","idbProvider","source","f","hasOwnProperty","tags","_tags","setAccessMode","read","unread","max","dst","getAccessMode","fields","MAX_FORM_ELEMENTS","MAX_PREVIEW_ATTACHMENTS","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","DRAFTY_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","test","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","bin","atob","buf","ArrayBuffer","Uint8Array","charCodeAt","URL","createObjectURL","Blob","type","base64toDataUrl","DECORATORS","props","href","id","act","ref","mime","Drafty","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","init","plainText","content","lines","entityMap","entityIndex","blx","line","spans","entities","tag","concat","spannify","block","sort","toSpanTree","chunks","chunkify","drafty","draftify","extractEntities","ranges","entity","index","unique","tp","offset","len","key","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","Object","assign","quote","header","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","indexOf","appendButton","attachJSON","UNSAFE_toHTML","doc","tree","draftyToTree","htmlFormatter","values","join","treeBottomUp","format","original","formatter","shorten","light","shortenTree","lightEntity","treeToDrafty","forwardedContent","rmMention","node","parent","treeTopDown","lTrim","replyContent","convMNnQQnBR","startsWith","children","attachmentsToEnd","forwarding","toPlainText","isPlainText","toMarkdown","mdFormatter","def","isValid","txt_type","hasAttachments","attachments","hasEntities","styles","sanitizeEntities","copyEntData","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","span","chunk","chld","re_start","re_end","exec","start_offset","lastIndexOf","end_offset","last","spansToTree","flatten","child","addNode","n","substring","att","subspans","inner","keymap","c","keys","newKey","transformer","stack","pop","tail","shortener","allow","lightCopy","trimStart","shift","match","extracted","el","startAt","plain","entries","dc","module","exports","isUrlRelative","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","e","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","window","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","setNetworkProvider","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","withTags","withCred","withDel","withLaterDel","_maxDel","extract","build","getOwnPropertyNames","updated","isP2PType","Const","mergeObj","mergeToCache","normalizeArray","Topic","callbacks","created","touched","Date","private","trusted","_users","_queuedSeqId","_noEarlierMsgs","_recvNotificationTimer","_credentials","_messageVersions","_messages","_attached","_new","_delayedLeaveTimer","onData","onMeta","onPres","onInfo","onMetaDesc","onMetaSub","onSubsUpdated","onTagsUpdated","onCredsUpdated","onDeleteTopic","onAllMessagesReceived","topicType","types","isMeTopicName","isGroupTopicName","isP2PTopicName","isCommTopicName","isNewGroupTopicName","isChannelTopicName","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","desc","_noForwarding","_processMetaDesc","createMessage","noEcho","publish","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_db","_cancelled","_fatal","leave","unsub","_resetSub","_gone","leaveDelayed","delay","getMeta","getMessagesPage","forward","startMetaQuery","_loadMessages","promise","setMeta","_processMetaSub","_processMetaTags","cred","_processMetaCreds","subscriber","am","invite","archive","arch","delMessages","hard","r1","r2","low","hi","tosend","reduce","out","del","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","list","prev","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","_refreshContact","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","recv","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","cb","origSeq","versions","messages","sinceId","beforeId","msgs","unused1","unused2","_isReplacementMsg","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","msgHasMoreMessages","newer","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isArchived","isMeType","isChannelType","isGroupType","isCommType","isMe","head","replace","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","clear","delseq","_routePres","pres","online","isTopicCached","dacs","_routeInfo","info","subs","deleted","_updateCachedUser","creds","_allMessagesReceived","obj","cached","_cachePutUser","_updateReceived","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","updateCount","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","method","contacts","getContact","getCredentials","TopicFnd","_contacts","indexBy","getPrototypeOf","prototype","date","isNaN","isValidDate","d","getTime","rfc3339DateString","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","ignore","prop","cache","newval","simplify","t","trim","toLowerCase","item","pos","ary","DBCache","WebSocket","XMLHttpRequest","IndexedDBProvider","indexedDB","initForNonBrowserApp","chars","btoa","global","input","output","charCode","bc","bs","String","fromCharCode","detectTransport","b64EncodeUnicode","encodeURIComponent","toSolidBytes","p1","jsonBuildHelper","jsonLoggerHelper","getBrowserInfo","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","Tinode","onComplete","floor","_appName","appName","_platform","platform","navigator","_browser","userAgent","_hwos","_humanLanguage","language","_connection","_persist","persist","all","_loggingEnabled","dateString","args","console","log","credential","getVersion","getLibrary","isNullValue","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","searchParams","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","hello","_serverInfo","onConnect","setDeviceToken","dt","sent","_deviceToken","loginBasic","uname","_login","loginToken","requestResetAuthSecret","expires","now","setAuthToken","dft","oobNotification","_trimLongStrings","stringify","xfrom","finally","modeGiven","modeWant","delCurrentUser","func","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_pendingPromises","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_cache","_cacheDelUser","onLogin","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file
diff --git a/umd/tinode.prod.js b/umd/tinode.prod.js
index 1917e3a8..4e3eace8 100644
--- a/umd/tinode.prod.js
+++ b/umd/tinode.prod.js
@@ -1 +1 @@
-!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.tinode=t():e.tinode=t()}(this,(()=>(()=>{"use strict";var e={577:e=>{const t=64,s="application/json",i=["act","height","duration","incoming","mime","name","premime","preref","preview","ref","size","state","url","val","width"],n=[{name:"ST",start:/(?:^|[\W_])(\*)[^\s*]/,end:/[^\s*](\*)(?=$|[\W_])/},{name:"EM",start:/(?:^|\W)(_)[^\s_]/,end:/[^\s_](_)(?=$|\W)/},{name:"DL",start:/(?:^|[\W_])(~)[^\s~]/,end:/[^\s~](~)(?=$|[\W_])/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],r=["QQ"],a=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu}],o={AU:{html_tag:"audio",md_tag:void 0,isVoid:!1},BN:{html_tag:"button",md_tag:void 0,isVoid:!1},BR:{html_tag:"br",md_tag:"\n",isVoid:!0},CO:{html_tag:"tt",md_tag:"`",isVoid:!1},DL:{html_tag:"del",md_tag:"~",isVoid:!1},EM:{html_tag:"i",md_tag:"_",isVoid:!1},EX:{html_tag:"",md_tag:void 0,isVoid:!0},FM:{html_tag:"div",md_tag:void 0,isVoid:!1},HD:{html_tag:"",md_tag:void 0,isVoid:!1},HL:{html_tag:"span",md_tag:void 0,isVoid:!1},HT:{html_tag:"a",md_tag:void 0,isVoid:!1},IM:{html_tag:"img",md_tag:void 0,isVoid:!1},LN:{html_tag:"a",md_tag:void 0,isVoid:!1},MN:{html_tag:"a",md_tag:void 0,isVoid:!1},RW:{html_tag:"div",md_tag:void 0,isVoid:!1},QQ:{html_tag:"div",md_tag:void 0,isVoid:!1},ST:{html_tag:"b",md_tag:"*",isVoid:!1},VC:{html_tag:"div",md_tag:void 0,isVoid:!1},VD:{html_tag:"video",md_tag:void 0,isVoid:!1}};function c(e,t,s){if(!e)return null;try{const s=atob(e),i=s.length,n=new ArrayBuffer(i),r=new Uint8Array(n);for(let e=0;e"",close:e=>""},EM:{open:e=>"",close:e=>""},DL:{open:e=>"",close:e=>""},CO:{open:e=>"",close:e=>""},BR:{open:e=>"
",close:e=>""},HD:{open:e=>"",close:e=>""},HL:{open:e=>'',close:e=>""},LN:{open:e=>'',close:e=>"",props:e=>e?{href:e.url,target:"_blank"}:null},MN:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},HT:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},BN:{open:e=>"",props:e=>e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null},AU:{open:e=>'",props:e=>e?{src:e.ref||c(e.val,e.mime,d.logger),"data-preload":e.ref?"metadata":"auto","data-duration":e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},IM:{open:e=>{const t=h(e._tempPreview,e.mime),s=c(e.val,e.mime,d.logger),i=e.ref||s;return(e.name?'':"")+'
'},close:e=>e.name?"":"",props:e=>e?{src:h(e._tempPreview,e.mime)||e.ref||c(e.val,e.mime,d.logger),title:e.name,alt:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},FM:{open:e=>"",close:e=>""},RW:{open:e=>"",close:e=>""},QQ:{open:e=>"",close:e=>"",props:e=>e?{}:null},VC:{open:e=>"",close:e=>"",props:e=>e?{"data-duration":e.duration,"data-state":e.state}:{}},VD:{open:e=>{const t=h(e._tempPreview,e.mime),s=e.ref||c(e.preview,e.premime||"image/jpeg",d.logger);return'
'},close:e=>"",props:e=>{if(!e)return null;const t=e.preref||c(e.preview,e.premime||"image/jpeg",d.logger);return{src:t,"data-src":e.ref||c(e.val,e.mime,d.logger),"data-width":e.width,"data-height":e.height,"data-preload":e.ref?"metadata":"auto","data-preview":t,"data-duration":0|e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}}}},d=function(){this.txt="",this.fmt=[],this.ent=[]};function u(e,t,s,i){const n=[];if(0==i.length)return[];for(let s in i){const r=i[s];r.at>t&&n.push({txt:e.slice(t,r.at)});const a={tp:r.tp},o=u(e,r.at+1,r.end,r.children);o.length>0?a.children=o:a.txt=r.txt,n.push(a),t=r.end+1}return ts.end?(t.push(e[i]),s=e[i]):e[i].end<=s.end&&s.children.push(e[i]);for(let e in t)t[e].children=p(t[e].children);return t}function g(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:i}=e;if(t=t||"",Array.isArray(i)||(i=[]),!Array.isArray(s)||0==s.length){if(0==i.length)return{text:t};s=[{at:0,len:0,key:0}]}const n=[],a=[];s.forEach((e=>{if(!e||"object"!=typeof e)return;if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,r=0|e.len;if(r<0)return;let o=e.key||0;i.length>0&&("number"!=typeof o||o<0||o>=i.length)||(s<=-1?a.push({start:-1,end:0,key:o}):s+r>t.length||(e.tp?n.push({type:e.tp,start:s,end:s+r}):i.length>0&&"object"==typeof i[o]&&n.push({start:s,end:s+r,key:o})))})),n.sort(((e,t)=>{let s=e.start-t.start;return 0!=s?s:(s=t.end-e.end,0!=s?s:r.indexOf(t.type)-r.indexOf(e.type))})),a.length>0&&n.push(...a),n.forEach((e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")}));let o=m({},t,0,t.length,n);return o=b(o,(function(e){if(Array.isArray(e.children)&&1==e.children.length){const t=e.children[0];if(e.type)t.type||t.children||(e.text=t.text,delete e.children);else{const s=e.parent;(e=t).parent=s}}return e})),o}function f(e,t){return t?(e.children||(e.children=[]),e.text&&(e.children.push({text:e.text,parent:e}),delete e.text),t.parent=e,e.children.push(t),e):e}function m(e,t,s,i,n){if(!n||0==n.length)return s{_(e,t,s)})),t.type){const n=e.txt.length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];const r=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=r,e.ent[r]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:r}):e.fmt.push({at:i,len:n,key:r})}else e.fmt.push({tp:t.type,at:i,len:n})}return e}function b(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;const n=[];for(let e in i.children){let r=i.children[e];r&&(r=b(r,t,s),r&&n.push(r))}return 0==n.length?i.children=null:i.children=n,i}function w(e,t,s,i,n){if(!e)return null;i&&e.type&&i.push(e.type);let r=[];for(let s in e.children){const a=w(e.children[s],t,s,i,n);a&&r.push(a)}return 0==r.length&&(r=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(n,e.type,e.data,r,s,i)}function v(e,t,s){return e?(s&&(t-=s.length),b(e,(function(e){if(t<=-1)return null;if(e.att)return e;if(0==t)e.text=s,t=-1;else if(e.text){const i=e.text.length;i>t?(e.text=e.text.substring(0,t)+s,t=-1):t-=i}return e}))):null}function y(e,t){return b(e,(e=>{const s=P(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e}))}function M(e){if("BR"==e.type)e=null;else if(e.text)e.type||(e.text=e.text.trimStart(),e.text||(e=null));else if(!e.type&&e.children&&e.children.length>0){const t=M(e.children[0]);t?e.children[0]=t:(e.children.shift(),e.type||0!=e.children.length||(e=null))}return e}function S(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const i=[],n=[];for(let r in e.children){const a=e.children[r];if(a.att){if(i.length==t)continue;if(a.data.mime==s)continue;delete a.att,delete a.children,a.text=" ",i.push(a)}else n.push(a)}e.children=n.concat(i)}return e}function T(e,t){let s="",i=[];for(let n in e){const r=e[n];if(!r.txt){const e=T(r.children,s.length+t);r.txt=e.txt,i=i.concat(e.fmt)}r.tp&&i.push({at:s.length+t,len:r.txt.length,tp:r.tp}),s+=r.txt}return{txt:s,fmt:i}}function P(e,s,n){if(e&&Object.entries(e).length>0){n=n||[];const r={};if(i.forEach((i=>{if(e[i]){if(s&&!n.includes(i)&&("string"==typeof e[i]||Array.isArray(e[i]))&&e[i].length>t)return;if("object"==typeof e[i])return;r[i]=e[i]}})),0!=Object.entries(r).length)return r}return null}d.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},d.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],i={},r=[];t.forEach((e=>{let t,o,c=[];if(n.forEach((t=>{c=c.concat(function(e,t,s,i){const n=[];let r=0,a=e.slice(0);for(;a.length>0;){const o=t.exec(a);if(null==o)break;let c=o.index+o[0].lastIndexOf(o[1]);a=a.slice(c+1),c+=r,r=c+1;const h=s?s.exec(a):null;if(null==h)break;let l=h.index+h[0].indexOf(h[1]);a=a.slice(l+1),l+=r,r=l+1,n.push({txt:e.slice(c+1,l),children:[],at:c,end:l,tp:i})}return n}(e,t.start,t.end,t.name))})),0==c.length)o={txt:e};else{c.sort(((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end})),c=p(c);const t=T(u(e,0,e.length,c),0);o={txt:t.txt,fmt:t.fmt}}if(t=function(e){let t,s=[];if(a.forEach((i=>{for(;null!==(t=i.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})})),0==s.length)return s;s.sort(((e,t)=>e.offset-t.offset));let i=-1;return s=s.filter((e=>{const t=e.offset>i;return i=e.offset+e.len,t})),s}(o.txt),t.length>0){const e=[];for(let n in t){const r=t[n];let a=i[r.unique];a||(a=s.length,i[r.unique]=a,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:a})}o.ent=e}r.push(o)}));const o={txt:""};if(r.length>0){o.txt=r[0].txt,o.fmt=(r[0].fmt||[]).concat(r[0].ent||[]);for(let e=1;e(e.at+=s,e))))),t.ent&&(o.fmt=o.fmt.concat(t.ent.map((e=>(e.at+=s,e)))))}0==o.fmt.length&&delete o.fmt,s.length>0&&(o.ent=s)}return o},d.append=function(e,t){if(!e)return t;if(!t)return e;e.txt=e.txt||"";const s=e.txt.length;return"string"==typeof t?e.txt+=t:t.txt&&(e.txt+=t.txt),Array.isArray(t.fmt)&&(e.fmt=e.fmt||[],Array.isArray(t.ent)&&(e.ent=e.ent||[]),t.fmt.forEach((i=>{const n={at:(0|i.at)+s,len:0|i.len};-1==i.at&&(n.at=-1,n.len=0),i.tp?n.tp=i.tp:(n.key=e.ent.length,e.ent.push(t.ent[i.key||0])),e.fmt.push(n)}))),e},d.insertImage=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"IM",data:{mime:s.mime,ref:s.refurl,val:s.bits||s.preview,width:s.width,height:s.height,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e,i.data._tempPreview=void 0,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},d.insertVideo=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"VD",data:{mime:s.mime,ref:s.refurl,val:s.bits,preref:s.preref,preview:s.preview,width:s.width,height:s.height,duration:0|s.duration,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e[0],i.data.preref=e[1],i.data._tempPreview=void 0,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},d.insertAudio=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"AU",data:{mime:s.mime,val:s.bits,duration:0|s.duration,preview:s.preview,name:s.filename,size:0|s.size,ref:s.refurl}};return s.urlPromise&&(i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},d.videoCall=function(e){return{txt:" ",fmt:[{at:0,len:1,key:0}],ent:[{tp:"VC",data:{aonly:e}}]}},d.updateVideoCall=function(e,t){const s=((e||{}).fmt||[])[0];if(!s)return e;let i;if("VC"==s.tp)delete s.tp,s.key=0,i={tp:"VC"},e.ent=[i];else if(i=(e.ent||[])[0|s.key],!i||"VC"!=i.tp)return e;return i.data=i.data||{},Object.assign(i.data,t),e},d.quote=function(e,t,s){const i=d.append(d.appendLineBreak(d.mention(e,t)),s);return i.fmt.push({at:0,len:i.txt.length,tp:"QQ"}),i},d.mention=function(e,t){return{txt:e||"",fmt:[{at:0,len:(e||"").length,key:0}],ent:[{tp:"MN",data:{val:t}}]}},d.appendLink=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:t.txt.length,key:e.ent.length}),e.txt+=t.txt;const s={tp:"LN",data:{url:t.url}};return e.ent.push(s),e},d.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",d.insertImage(e,e.txt.length-1,t)},d.appendAudio=function(e,t){return(e=e||{txt:""}).txt+=" ",d.insertAudio(e,e.txt.length-1,t)},d.attachFile=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});const s={tp:"EX",data:{mime:t.mime,val:t.data,name:t.filename,ref:t.refurl,size:0|t.size}};return t.urlPromise&&(s.data._processing=!0,t.urlPromise.then((e=>{s.data.ref=e,s.data._processing=void 0}),(e=>{s.data._processing=void 0}))),e.ent.push(s),e},d.wrapInto=function(e,t,s,i){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:s||0,len:i||e.txt.length,tp:t}),e},d.wrapAsForm=function(e,t,s){return d.wrapInto(e,"FM",t,s)},d.insertButton=function(e,t,s,i,n,r,a){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length{switch(e.type){case"IM":return["val"];case"VD":return["preview"]}return null})),_({},s,[])):e},d.preview=function(e,t,s){let i=g(e);if(i=S(i,3),i=b(i,(function(e){return"MN"==e.type?e.parent&&e.parent.type||!(e.text||"").startsWith("➦")||(e.text="➦",delete e.children):"QQ"==e.type?(e.text=" ",delete e.children):"BR"==e.type&&(e.text=" ",delete e.children,delete e.type),e})),i=v(i,t,"…"),s){const e={IM:["val"],VD:["preview"]};i=y(i,(t=>e[t.type]))}else i=y(i);return _({},i,[])},d.toPlainText=function(e){return"string"==typeof e?e:e.txt},d.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},d.toMarkdown=function(e){return w(g(e),(function(e,t,s){const i=o[e];let n=s?s.join(""):"";return i&&(i.isVoid?n=i.md_tag||"":i.md_tag&&(n=i.md_tag+n+i.md_tag)),n}),0)},d.isValid=function(e){if(!e)return!1;const{txt:t,fmt:s,ent:i}=e;if(!t&&""!==t&&!s&&!i)return!1;const n=typeof t;return!("string"!=n&&"undefined"!=n&&null!==t||void 0!==s&&!Array.isArray(s)&&null!==s||void 0!==i&&!Array.isArray(i)&&null!==i)},d.hasAttachments=function(e){if(!Array.isArray(e.fmt))return!1;for(let t in e.fmt){const s=e.fmt[t];if(s&&s.at<0){const t=e.ent[0|s.key];return t&&"EX"==t.tp&&t.data}}return!1},d.attachments=function(e,t,s){if(!Array.isArray(e.fmt))return;let i=0;for(let n in e.ent){let r=e.fmt[n];if(r&&r.at<0){const n=e.ent[0|r.key];if(n&&"EX"==n.tp&&n.data&&t.call(s,n.data,i++,"EX"))break}}},d.hasEntities=function(e){return e.ent&&e.ent.length>0},d.entities=function(e,t,s){if(e.ent&&e.ent.length>0)for(let i in e.ent)if(e.ent[i]&&t.call(s,e.ent[i].data,i,e.ent[i].tp))break},d.styles=function(e,t,s){if(e.fmt&&e.fmt.length>0)for(let i in e.fmt){const n=e.fmt[i];if(n&&t.call(s,n.tp,n.at,n.len,n.key,i))break}},d.sanitizeEntities=function(e){if(e&&e.ent&&e.ent.length>0)for(let t in e.ent){const s=e.ent[t];if(s&&s.data){const i=P(s.data);i?e.ent[t].data=i:delete e.ent[t].data}}return e},d.getDownloadUrl=function(e){let t=null;return e.mime!=s&&e.val?t=c(e.val,e.mime,d.logger):"string"==typeof e.ref&&(t=e.ref),t},d.isProcessing=function(e){return!!e._processing},d.getPreviewUrl=function(e){return e.val?c(e.val,e.mime,d.logger):null},d.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},d.getEntityMimeType=function(e){return e.mime||"text/plain"},d.tagName=function(e){return o[e]&&o[e].html_tag},d.attrValue=function(e,t){if(t&&l[e])return l[e].props(t)},d.getContentType=function(){return"text/x-drafty"},e.exports=d}},t={};function s(i){var n=t[i];if(void 0!==n)return n.exports;var r=t[i]={exports:{}};return e[i](r,r.exports,s),r.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{function e(e,t,s){return function(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}(e,t),s}s.r(i),s.d(i,{AccessMode:()=>t,Drafty:()=>Ne(),Tinode:()=>At});class t{constructor(e){e&&(this.given="number"==typeof e.given?e.given:t.decode(e.given),this.want="number"==typeof e.want?e.want:t.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:t.decode(e.mode):this.given&this.want)}static decode(e){if(!e)return null;if("number"==typeof e)return e&t._BITMASK;if("N"===e||"n"===e)return t._NONE;const s={J:t._JOIN,R:t._READ,W:t._WRITE,P:t._PRES,A:t._APPROVE,S:t._SHARE,D:t._DELETE,O:t._OWNER};let i=t._NONE;for(let t=0;t=20&&s.length<=24&&["ts","touched","updated","created","when","deleted","expires"].includes(e)){const e=new Date(s);if(!isNaN(e))return e}else if("acs"===e&&"object"==typeof s)return new t(s);return s}function b(e){return e&&!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}function w(e){return e instanceof Date&&!isNaN(e)&&0!=e.getTime()}function v(e,s,i){if("object"!=typeof s){if(void 0===s)return e;if(s===f)return;return s}if(null===s)return s;if(s instanceof Date&&!isNaN(s))return!e||!(e instanceof Date)||isNaN(e)||e{"_"==t[0]?delete e[t]:e[t]?Array.isArray(e[t])&&0==e[t].length?delete e[t]:e[t]?e[t]instanceof Date?w(e[t])||delete e[t]:"object"==typeof e[t]&&(M(e[t]),0==Object.getOwnPropertyNames(e[t]).length&&delete e[t]):delete e[t]:delete e[t]})),e}function S(e,t){x(e,t),t.add(e)}function T(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function P(e,t,s){x(e,t),t.set(e,s)}function x(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function E(e,t,s){return D(e,A(e,t,"set"),s),s}function k(e,t){return q(e,A(e,t,"get"))}function A(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}function D(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=s}}function R(e,t,s){return C(e,t),N(s,"get"),q(e,s)}function N(e,t){if(void 0===e)throw new TypeError("attempted to "+t+" private static field before its declaration")}function C(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}function q(e,t){return t.get?t.get.call(e):t.value}function U(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let I,O;const j=503,L="Connection failed",W=418,V="Disconnected by client",z=2e3,G=10,B=.3;function F(e,t,s,i){let n=null;return["http","https","ws","wss"].includes(t)&&(n=`${t}://${e}`,"/"!==n.charAt(n.length-1)&&(n+="/"),n+="v"+s+"/channels",["http","https"].includes(t)&&(n+="/lp"),n+="?apikey="+i),n}var K=new WeakMap,H=new WeakMap,Q=new WeakMap,X=new WeakMap,$=new WeakSet,J=new WeakSet,Z=new WeakSet,Y=new WeakSet,ee=new WeakSet;class te{constructor(e,t,s){if(S(this,ee),S(this,Y),S(this,Z),S(this,J),S(this,$),P(this,K,{writable:!0,value:null}),P(this,H,{writable:!0,value:0}),P(this,Q,{writable:!0,value:!1}),P(this,X,{writable:!0,value:null}),T(this,"host",void 0),T(this,"secure",void 0),T(this,"apiKey",void 0),T(this,"version",void 0),T(this,"autoreconnect",void 0),T(this,"initialized",void 0),T(this,"onMessage",void 0),T(this,"onDisconnect",void 0),T(this,"onOpen",void 0),T(this,"onAutoreconnectIteration",void 0),this.host=e.host,this.secure=e.secure,this.apiKey=e.apiKey,this.version=t,this.autoreconnect=s,"lp"===e.transport?(U(this,Y,re).call(this),this.initialized="lp"):"ws"===e.transport&&(U(this,ee,ae).call(this),this.initialized="ws"),!this.initialized)throw R(te,te,oe).call(te,"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.")}static setNetworkProviders(e,t){I=e,O=t}static set logger(e){var t,s,i;s=oe,i=e,C(t=te,te),N(s,"set"),D(t,s,i)}connect(e,t){return Promise.reject(null)}reconnect(e){}disconnect(){}sendText(e){}isConnected(){return!1}transport(){return this.initialized}probe(){this.sendText("1")}backoffReset(){U(this,Z,ne).call(this)}}function se(){clearTimeout(k(this,K));const e=z*(Math.pow(2,k(this,H))*(1+B*Math.random()));E(this,H,k(this,H)>=G?k(this,H):k(this,H)+1),this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),E(this,K,setTimeout((t=>{if(R(te,te,oe).call(te,`Reconnecting, iter=${k(this,H)}, timeout=${e}`),k(this,Q))this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch((e=>{}))}}),e))}function ie(){clearTimeout(k(this,K)),E(this,K,null)}function ne(){E(this,H,0)}function re(){let e=null,t=null,s=null,i=(t,s,n)=>{let r=new O,a=!1;return r.onreadystatechange=o=>{if(4==r.readyState)if(201==r.status){let n=JSON.parse(r.responseText,_);e=t+"&sid="+n.ctrl.params.sid,r=i(e),r.send(null),this.onOpen&&this.onOpen(),s&&(a=!0,s()),this.autoreconnect&&U(this,J,ie).call(this)}else if(r.status>0&&r.status<400)this.onMessage&&this.onMessage(r.responseText),r=i(e),r.send(null);else{if(n&&!a&&(a=!0,n(r.responseText)),this.onMessage&&r.responseText&&this.onMessage(r.responseText),this.onDisconnect){const e=r.status||(k(this,Q)?W:j),t=r.responseText||(k(this,Q)?V:L);this.onDisconnect(new m(t,e),e)}r=null,!k(this,Q)&&this.autoreconnect&&U(this,$,se).call(this)}},r.open("POST",t,!0),r};this.connect=(e,s)=>{if(E(this,Q,!1),t){if(!s)return Promise.resolve();t.onreadystatechange=void 0,t.abort(),t=null}return e&&(this.host=e),new Promise(((e,s)=>{const n=F(this.host,this.secure?"https":"http",this.version,this.apiKey);R(te,te,oe).call(te,"LP connecting to:",n),t=i(n,e,s),t.send(null)})).catch((e=>{R(te,te,oe).call(te,"LP connection failed:",e)}))},this.reconnect=e=>{U(this,J,ie).call(this),this.connect(null,e)},this.disconnect=i=>{E(this,Q,!0),U(this,J,ie).call(this),s&&(s.onreadystatechange=void 0,s.abort(),s=null),t&&(t.onreadystatechange=void 0,t.abort(),t=null),this.onDisconnect&&this.onDisconnect(new m(V,W),W),e=null},this.sendText=t=>{if(s=(e=>{const t=new O;return t.onreadystatechange=e=>{if(4==t.readyState&&t.status>=400)throw new m("LP sender failed",t.status)},t.open("POST",e,!0),t})(e),!s||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(t)},this.isConnected=e=>t&&!0}function ae(){this.connect=(e,t)=>{if(E(this,Q,!1),k(this,X)){if(!t&&k(this,X).readyState==k(this,X).OPEN)return Promise.resolve();k(this,X).close(),E(this,X,null)}return e&&(this.host=e),new Promise(((e,t)=>{const s=F(this.host,this.secure?"wss":"ws",this.version,this.apiKey);R(te,te,oe).call(te,"WS connecting to: ",s);const i=new I(s);i.onerror=e=>{t(e)},i.onopen=t=>{this.autoreconnect&&U(this,J,ie).call(this),this.onOpen&&this.onOpen(),e()},i.onclose=e=>{if(E(this,X,null),this.onDisconnect){const e=k(this,Q)?W:j;this.onDisconnect(new m(k(this,Q)?V:L,e),e)}!k(this,Q)&&this.autoreconnect&&U(this,$,se).call(this)},i.onmessage=e=>{this.onMessage&&this.onMessage(e.data)},E(this,X,i)}))},this.reconnect=e=>{U(this,J,ie).call(this),this.connect(null,e)},this.disconnect=e=>{E(this,Q,!0),U(this,J,ie).call(this),k(this,X)&&(k(this,X).close(),E(this,X,null))},this.sendText=e=>{if(!k(this,X)||k(this,X).readyState!=k(this,X).OPEN)throw new Error("Websocket is not connected");k(this,X).send(e)},this.isConnected=e=>k(this,X)&&k(this,X).readyState==k(this,X).OPEN}var oe={writable:!0,value:e=>{}};function ce(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function he(e,t,s){le(e,t),t.set(e,s)}function le(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function de(e,t,s){return ge(e,t),function(e,t){if(void 0===e)throw new TypeError("attempted to get private static field before its declaration")}(s),me(e,s)}function ue(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function pe(e,t,s){return ge(e,t),s}function ge(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}function fe(e,t){return me(e,be(e,t,"get"))}function me(e,t){return t.get?t.get.call(e):t.value}function _e(e,t,s){return function(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=s}}(e,be(e,t,"set"),s),s}function be(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}te.NETWORK_ERROR=j,te.NETWORK_ERROR_TEXT=L,te.NETWORK_USER=W,te.NETWORK_USER_TEXT=V;const we="tinode-web";let ve;var ye=new WeakMap,Me=new WeakMap,Se=new WeakSet;class Te{constructor(e,t){var s;le(this,s=Se),s.add(this),he(this,ye,{writable:!0,value:e=>{}}),he(this,Me,{writable:!0,value:e=>{}}),ce(this,"db",null),ce(this,"disabled",!1),_e(this,ye,e||fe(this,ye)),_e(this,Me,t||fe(this,Me))}initDatabase(){return new Promise(((e,t)=>{const s=ve.open(we,1);s.onsuccess=t=>{this.db=t.target.result,this.disabled=!1,e(this.db)},s.onerror=e=>{fe(this,Me).call(this,"PCache","failed to initialize",e),t(e.target.error),fe(this,ye).call(this,e.target.error)},s.onupgradeneeded=e=>{this.db=e.target.result,this.db.onerror=e=>{fe(this,Me).call(this,"PCache","failed to create storage",e),fe(this,ye).call(this,e.target.error)},this.db.createObjectStore("topic",{keyPath:"name"}),this.db.createObjectStore("user",{keyPath:"uid"}),this.db.createObjectStore("subscription",{keyPath:["topic","uid"]}),this.db.createObjectStore("message",{keyPath:["topic","seq"]})}}))}deleteDatabase(){return this.db&&(this.db.close(),this.db=null),new Promise(((e,t)=>{const s=ve.deleteDatabase(we);s.onblocked=e=>{this.db&&this.db.close();const s=new Error("blocked");fe(this,Me).call(this,"PCache","deleteDatabase",s),t(s)},s.onsuccess=t=>{this.db=null,this.disabled=!0,e(!0)},s.onerror=e=>{fe(this,Me).call(this,"PCache","deleteDatabase",e.target.error),t(e.target.error)}}))}isReady(){return!!this.db}updTopic(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","updTopic",e.target.error),s(e.target.error)};const n=i.objectStore("topic").get(e.name);n.onsuccess=t=>{i.objectStore("topic").put(pe(Te,Te,Ee).call(Te,n.result,e)),i.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}markTopicAsDeleted(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","markTopicAsDeleted",e.target.error),s(e.target.error)},i.objectStore("topic").get(e).onsuccess=e=>{const t=e.target.result;t._deleted=!0,i.objectStore("topic").put(t),i.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remTopic(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic","subscription","message"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","remTopic",e.target.error),s(e.target.error)},i.objectStore("topic").delete(IDBKeyRange.only(e)),i.objectStore("subscription").delete(IDBKeyRange.bound([e,"-"],[e,"~"])),i.objectStore("message").delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapTopics(e,t){return ue(this,Se,Pe).call(this,"topic",e,t)}deserializeTopic(e,t){pe(Te,Te,xe).call(Te,e,t)}updUser(e,t){if(!(arguments.length<2||void 0===t))return this.isReady()?new Promise(((s,i)=>{const n=this.db.transaction(["user"],"readwrite");n.oncomplete=e=>{s(e.target.result)},n.onerror=e=>{fe(this,Me).call(this,"PCache","updUser",e.target.error),i(e.target.error)},n.objectStore("user").put({uid:e,public:t}),n.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remUser(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["user"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","remUser",e.target.error),s(e.target.error)},i.objectStore("user").delete(IDBKeyRange.only(e)),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapUsers(e,t){return ue(this,Se,Pe).call(this,"user",e,t)}getUser(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["user"]);i.oncomplete=e=>{const s=e.target.result;t({user:s.uid,public:s.public})},i.onerror=e=>{fe(this,Me).call(this,"PCache","getUser",e.target.error),s(e.target.error)},i.objectStore("user").get(e)})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updSubscription(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["subscription"],"readwrite");r.oncomplete=e=>{i(e.target.result)},r.onerror=e=>{fe(this,Me).call(this,"PCache","updSubscription",e.target.error),n(e.target.error)},r.objectStore("subscription").get([e,t]).onsuccess=i=>{r.objectStore("subscription").put(pe(Te,Te,ke).call(Te,i.target.result,e,t,s)),r.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapSubscriptions(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["subscription"]);r.onerror=e=>{fe(this,Me).call(this,"PCache","mapSubscriptions",e.target.error),n(e.target.error)},r.objectStore("subscription").getAll(IDBKeyRange.bound([e,"-"],[e,"~"])).onsuccess=e=>{t&&e.target.result.forEach((e=>{t.call(s,e)})),i(e.target.result)}})):this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}addMessage(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["message"],"readwrite");i.onsuccess=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","addMessage",e.target.error),s(e.target.error)},i.objectStore("message").add(pe(Te,Te,Ae).call(Te,null,e)),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updMessageStatus(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["message"],"readwrite");r.onsuccess=e=>{i(e.target.result)},r.onerror=e=>{fe(this,Me).call(this,"PCache","updMessageStatus",e.target.error),n(e.target.error)};const a=r.objectStore("message").get(IDBKeyRange.only([e,t]));a.onsuccess=i=>{const n=a.result||i.target.result;n&&n._status!=s?(r.objectStore("message").put(pe(Te,Te,Ae).call(Te,n,{topic:e,seq:t,_status:s})),r.commit()):r.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remMessages(e,t,s){return this.isReady()?new Promise(((i,n)=>{t||s||(t=0,s=Number.MAX_SAFE_INTEGER);const r=s>0?IDBKeyRange.bound([e,t],[e,s],!1,!0):IDBKeyRange.only([e,t]),a=this.db.transaction(["message"],"readwrite");a.onsuccess=e=>{i(e.target.result)},a.onerror=e=>{fe(this,Me).call(this,"PCache","remMessages",e.target.error),n(e.target.error)},a.objectStore("message").delete(r),a.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}readMessages(e,t,s,i){return this.isReady()?new Promise(((n,r)=>{const a=(t=t||{}).since>0?t.since:0,o=t.before>0?t.before:Number.MAX_SAFE_INTEGER,c=0|t.limit,h=[],l=IDBKeyRange.bound([e,a],[e,o],!1,!0),d=this.db.transaction(["message"]);d.onerror=e=>{fe(this,Me).call(this,"PCache","readMessages",e.target.error),r(e.target.error)},d.objectStore("message").openCursor(l,"prev").onsuccess=e=>{const t=e.target.result;t?(s&&s.call(i,t.value),h.push(t.value),c<=0||h.length{const r=this.db.transaction([e]);r.onerror=t=>{fe(this,Me).call(this,"PCache","mapObjects",e,t.target.error),n(t.target.error)},r.objectStore(e).getAll().onsuccess=e=>{t&&e.target.result.forEach((e=>{t.call(s,e)})),i(e.target.result)}})):disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}function xe(e,t){de(Te,Te,De).forEach((s=>{t.hasOwnProperty(s)&&(e[s]=t[s])})),Array.isArray(t.tags)&&(e._tags=t.tags),t.acs&&e.setAccessMode(t.acs),e.seq|=0,e.read|=0,e.unread=Math.max(0,e.seq-e.read)}function Ee(e,t){const s=e||{name:t.name};return de(Te,Te,De).forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),Array.isArray(t._tags)&&(s.tags=t._tags),t.acs&&(s.acs=t.getAccessMode().jsonHelper()),s}function ke(e,t,s,i){const n=e||{topic:t,uid:s};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach((e=>{i.hasOwnProperty(e)&&(n[e]=i[e])})),n}function Ae(e,t){const s=e||{};return["topic","seq","ts","_status","from","head","content"].forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),s}var De={writable:!0,value:["created","updated","deleted","read","recv","seq","clear","defacs","creds","public","trusted","private","touched","_deleted"]},Re=s(577),Ne=s.n(Re);let Ce;class qe{constructor(e,t){this._tinode=e,this._version=t,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this.xhr=[]}uploadWithBaseUrl(e,t,s,i,n,r){let a=`/v${this._version}/file/u/`;if(e){let t=e;if(t.endsWith("/")&&(t=t.slice(0,-1)),!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid base URL '${e}'`);a=t+a}const o=this,c=new Ce;this.xhr.push(c),c.open("POST",a,!0),c.setRequestHeader("X-Tinode-APIKey",this._apiKey),this._authToken&&c.setRequestHeader("X-Tinode-Auth",`Token ${this._authToken.token}`);let h=null,l=null;const d=new Promise(((e,t)=>{h=e,l=t}));c.upload.onprogress=e=>{e.lengthComputable&&(i&&i(e.loaded/e.total),this.onProgress&&this.onProgress(e.loaded/e.total))},c.onload=function(){let e;try{e=JSON.parse(this.response,_)}catch(t){o._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(h&&h(e.ctrl.params.url),n&&n(e.ctrl)):this.status>=400?(l&&l(new m(e.ctrl.text,e.ctrl.code)),r&&r(e.ctrl)):o._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},c.onerror=function(e){l&&l(e||new Error("failed")),r&&r(null)},c.onabort=function(e){l&&l(new Error("upload cancelled by user")),r&&r(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._tinode.getNextUniqueId()),s&&e.set("topic",s),c.send(e)}catch(e){l&&l(e),r&&r(null)}return d}upload(e,t,s,i,n){const r=(this._tinode._secure?"https://":"http://")+this._tinode._host;return this.uploadWithBaseUrl(r,e,t,s,i,n)}download(e,t,s,i,n){if(!b(e))return void(n&&n(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(n&&n("Must authenticate first"));const r=this,a=new Ce;this.xhr.push(a),a.open("GET",e,!0),a.setRequestHeader("X-Tinode-APIKey",this._apiKey),a.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),a.responseType="blob",a.onprogress=function(e){i&&i(e.loaded)};let o=null,c=null;const h=new Promise(((e,t)=>{o=e,c=t}));a.onload=function(){if(200==this.status){const e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:s})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),o&&o()}else if(this.status>=400&&c){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,_);c(new m(e.ctrl.text,e.ctrl.code))}catch(e){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),c(e)}},e.readAsText(this.response)}},a.onerror=function(e){c&&c(new Error("failed")),n&&n(e)},a.onabort=function(){c&&c(null)};try{a.send()}catch(e){c&&c(e),n&&n(e)}return h}cancel(){this.xhr.forEach((e=>{e.readyState<4&&e.abort()}))}static setNetworkProvider(e){Ce=e}}function Ue(e,t){!function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.add(e)}function Ie(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}var Oe=new WeakSet,je=new WeakSet;class Le{constructor(e){Ue(this,je),Ue(this,Oe),this.topic=e,this.what={}}withData(e,t,s){return this.what.data={since:e,before:t,limit:s},this}withLaterData(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)}withEarlierData(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)}withDesc(e){return this.what.desc={ims:e},this}withLaterDesc(){return this.withDesc(Ie(this,Oe,We).call(this))}withSub(e,t,s){const i={ims:e,limit:t};return"me"==this.topic.getType()?i.topic=s:i.user=s,this.what.sub=i,this}withOneSub(e,t){return this.withSub(e,void 0,t)}withLaterOneSub(e){return this.withOneSub(this.topic._lastSubsUpdate,e)}withLaterSub(e){return this.withSub(Ie(this,je,Ve).call(this),e)}withTags(){return this.what.tags=!0,this}withCred(){return"me"==this.topic.getType()?this.what.cred=!0:this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds",this.topic.getType()),this}withDel(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this}withLaterDel(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)}extract(e){return this.what[e]}build(){const e=[];let t={};return["data","sub","desc","tags","cred","del"].forEach((s=>{this.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(this.what[s]).length>0&&(t[s]=this.what[s]))})),e.length>0?t.what=e.join(" "):t=void 0,t}}function We(){return this.topic.updated}function Ve(){return this.topic.isP2PType()?Ie(this,Oe,We).call(this):this.topic._lastSubsUpdate}function ze(e,t){Be(e,t),t.add(e)}function Ge(e,t,s){Be(e,t),t.set(e,s)}function Be(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Fe(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function Ke(e,t){return function(e,t){return t.get?t.get.call(e):t.value}(e,Qe(e,t,"get"))}function He(e,t,s){return function(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=s}}(e,Qe(e,t,"set"),s),s}function Qe(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}var Xe=new WeakMap,$e=new WeakMap,Je=new WeakSet,Ze=new WeakSet;class Ye{constructor(e,t){ze(this,Ze),ze(this,Je),Ge(this,Xe,{writable:!0,value:void 0}),Ge(this,$e,{writable:!0,value:!1}),function(e,t,s){(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s}(this,"buffer",[]),He(this,Xe,e||((e,t)=>e===t?0:ee?this.buffer[this.buffer.length-1-e]:void 0}put(){let e;e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;for(let t in e)Fe(this,Ze,tt).call(this,e[t],this.buffer)}delAt(e){e|=0;let t=this.buffer.splice(e,1);if(t&&t.length>0)return t[0]}delRange(e,t){return this.buffer.splice(e,t-e)}length(){return this.buffer.length}reset(){this.buffer=[]}forEach(e,t,s,i){t|=0,s=s||this.buffer.length;for(let n=t;nt?this.buffer[n-1]:void 0,n0)){o=!0;break}n=r-1}return o?{idx:r,exact:!0}:s?{idx:-1}:{idx:a<0?r+1:r}}function tt(e,t){const s=Fe(this,Je,et).call(this,e,t,!1),i=s.exact&&Ke(this,$e)?1:0;return t.splice(s.idx,i,e),t}function st(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class it{constructor(e,s){this._tinode=null,this.name=e,this.created=null,this.updated=null,this.touched=new Date(0),this.acs=new t(null),this.private=null,this.public=null,this.trusted=null,this._users={},this._queuedSeqId=u,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._recvNotificationTimer=null,this._tags=[],this._credentials=[],this._messageVersions={},this._messages=new Ye(((e,t)=>e.seq-t.seq),!0),this._attached=!1,this._lastSubsUpdate=new Date(0),this._new=!0,this._deleted=!1,this._delayedLeaveTimer=null,s&&(this.onData=s.onData,this.onMeta=s.onMeta,this.onPres=s.onPres,this.onInfo=s.onInfo,this.onMetaDesc=s.onMetaDesc,this.onMetaSub=s.onMetaSub,this.onSubsUpdated=s.onSubsUpdated,this.onTagsUpdated=s.onTagsUpdated,this.onCredsUpdated=s.onCredsUpdated,this.onDeleteTopic=s.onDeleteTopic,this.onAllMessagesReceived=s.onAllMessagesReceived)}static topicType(e){return{me:h,fnd:l,grp:d,new:d,nch:d,chn:d,usr:"p2p",sys:"sys"}["string"==typeof e?e.substring(0,3):"xxx"]}static isMeTopicName(e){return it.topicType(e)==h}static isGroupTopicName(e){return it.topicType(e)==d}static isP2PTopicName(e){return"p2p"==it.topicType(e)}static isCommTopicName(e){return it.isP2PTopicName(e)||it.isGroupTopicName(e)}static isNewGroupTopicName(e){return"string"==typeof e&&(e.substring(0,3)==o||e.substring(0,3)==c)}static isChannelTopicName(e){return"string"==typeof e&&("chn"==e.substring(0,3)||e.substring(0,3)==c)}isSubscribed(){return this._attached}subscribe(e,t){return clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=null,this._attached?Promise.resolve(this):this._deleted?Promise.reject(new Error("Conversation deleted")):this._tinode.subscribe(this.name||o,e,t).then((e=>{if(e.code>=300)return e;if(this._attached=!0,this._deleted=!1,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(delete this._new,this.name!=e.topic&&(this._cacheDelSelf(),this.name=e.topic),this._cachePutSelf(),this.created=e.ts,this.updated=e.ts,this.name!=h&&this.name!=l){const e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}t&&t.desc&&(t.desc._noForwarding=!0,this._processMetaDesc(t.desc))}return e}))}createMessage(e,t){return this._tinode.createMessage(this.name,e,t)}publish(e,t){return this.publishMessage(this.createMessage(e,t))}publishMessage(e){if(!this._attached)return Promise.reject(new Error("Cannot publish on inactive topic"));if(this._sending)return Promise.reject(new Error("The message is already being sent"));e._sending=!0,e._failed=!1;let t=null;return Ne().hasEntities(e.content)&&(t=[],Ne().entities(e.content,(e=>{e&&e.ref&&t.push(e.ref)})),0==t.length&&(t=null)),this._tinode.publishMessage(e,t).then((t=>(e._sending=!1,e.ts=t.ts,this.swapMessageId(e,t.params.seq),this._maybeUpdateMessageVersionsCache(e),this._routeData(e),t))).catch((t=>{this._tinode.logger("WARNING: Message rejected by the server",t),e._sending=!1,e._failed=!0,this.onData&&this.onData()}))}publishDraft(e,t){const s=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=s,e.ts=new Date,e.from=this._tinode.getCurrentUserID(),e.noecho=!0,this._messages.put(e),this._tinode._db.addMessage(e),this.onData&&this.onData(e)),(t||Promise.resolve()).then((t=>e._cancelled?{code:300,text:"cancelled"}:this.publishMessage(e))).catch((t=>{throw this._tinode.logger("WARNING: Message draft rejected",t),e._sending=!1,e._failed=!0,e._fatal=t instanceof m&&t.code>=400&&t.code<500,this.onData&&this.onData(),t}))}leave(e){return this._attached||e?this._tinode.leave(this.name,e).then((t=>(this._resetSub(),e&&this._gone(),t))):Promise.reject(new Error("Cannot leave inactive topic"))}leaveDelayed(e,t){clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=setTimeout((t=>{this._delayedLeaveTimer=null,this.leave(e)}),t)}getMeta(e){return this._tinode.getMeta(this.name,e)}getMessagesPage(e,t){let s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);return this._loadMessages(this._tinode._db,s.extract("data")).then((i=>{if(i==e)return Promise.resolve({topic:this.name,code:200,params:{count:i}});e-=i,s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);let n=this.getMeta(s.build());return t||(n=n.then((e=>{e&&e.params&&!e.params.count&&(this._noEarlierMsgs=!0)}))),n}))}setMeta(e){return e.tags&&(e.tags=function(e){let t=[];if(Array.isArray(e)){for(let s=0,i=e.length;s1&&t.push(i))}t.sort().filter((function(e,t,s){return!t||e!=s[t-1]}))}return 0==t.length&&t.push(f),t}(e.tags)),this._tinode.setMeta(this.name,e).then((t=>(t&&t.code>=300||(e.sub&&(e.sub.topic=this.name,t.params&&t.params.acs&&(e.sub.acs=t.params.acs,e.sub.updated=t.ts),e.sub.user||(e.sub.user=this._tinode.getCurrentUserID(),e.desc||(e.desc={})),e.sub._noForwarding=!0,this._processMetaSub([e.sub])),e.desc&&(t.params&&t.params.acs&&(e.desc.acs=t.params.acs,e.desc.updated=t.ts),this._processMetaDesc(e.desc)),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds([e.cred],!0)),t)))}updateMode(e,t){const s=e?this.subscriber(e):null,i=s?s.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:i}})}invite(e,t){return this.setMeta({sub:{user:e,mode:t}})}archive(e){return this.private&&!this.private.arch==!e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||f}}})}delMessages(e,t){if(!this._attached)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort(((e,t)=>e.low=t.hi)));let s,i=e.reduce(((e,t)=>(t.low0?this._tinode.delMessages(this.name,i,t):Promise.resolve({params:{del:0}}),s.then((t=>(t.params.del>this._maxDel&&(this._maxDel=t.params.del),e.forEach((e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low)})),this.onData&&this.onData(),t)))}delMessagesAll(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)}delMessagesList(e,t){e.sort(((e,t)=>e-t));let s=e.reduce(((e,t)=>{if(0==e.length)e.push({low:t});else{let s=e[e.length-1];!s.hi&&t!=s.low+1||t>s.hi?e.push({low:t}):s.hi=s.hi?Math.max(s.hi,t+1):t+1}return e}),[]);return this.delMessages(s,t)}delMessagesEdits(e,t){const s=[e];return this.messageVersions(e,(e=>s.push(e.seq))),this.delMessagesList(s,t)}delTopic(e){return this._deleted?(this._gone(),Promise.resolve(null)):this._tinode.delTopic(this.name,e).then((e=>(this._deleted=!0,this._resetSub(),this._gone(),e)))}delSubscription(e){return this._attached?this._tinode.delSubscription(this.name,e).then((t=>(delete this._users[e],this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users)),t))):Promise.reject(new Error("Cannot delete subscription in inactive topic"))}note(e,t){if(!this._attached)return;const s=this._users[this._tinode.getCurrentUserID()];let i=!1;s?(!s[e]||s[e]0&&this.note("read",e)}noteKeyPress(){this._attached?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")}noteRecording(e){this._attached?this._tinode.noteKeyPress(this.name,e?"kpa":"kpv"):this._tinode.logger("INFO: Cannot send notification in inactive topic")}videoCall(e,t,s){if(this._attached||["ringing","hang-up"].includes(e))return this._tinode.videoCall(this.name,t,e,s)}_updateReadRecv(e,t,s){let i,n=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":i=this.recv,this.recv=Math.max(this.recv,t),n=i!=this.recv;break;case"read":i=this.read,this.read=Math.max(this.read,t),n=i!=this.read;break;case"msg":i=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched{if(this._isReplacementMsg(e))return;const r=this.latestMsgVersion(e.seq)||e;r._origTs||(r._origTs=r.ts,r._origSeq=r.seq,r.ts=e.ts,r.seq=e.seq),t.push({data:r,idx:n})}),e,r,{}),t.forEach(((e,s)=>{n.call(i,e.data,s>0?t[s-1].data:void 0,s=0)return this._messages.getAt(t)}latestMessage(){return this._messages.getLast()}latestMsgVersion(e){const t=this._messageVersions[e];return t?t.getLast():null}maxMsgSeq(){return this._maxSeq}maxClearId(){return this._maxDel}messageCount(){return this._messages.length()}queuedMessages(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,u,void 0,t)}msgReceiptCount(e,t){let s=0;if(t>0){const i=this._tinode.getCurrentUserID();for(let n in this._users){const r=this._users[n];r.user!==i&&r[e]>=t&&s++}}return s}msgReadCount(e){return this.msgReceiptCount("read",e)}msgRecvCount(e){return this.msgReceiptCount("recv",e)}msgHasMoreMessages(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs}isNewMessage(e){return this._maxSeq<=e}flushMessage(e){const t=this._messages.find({seq:e});if(delete this._messageVersions[e],t>=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)}flushMessageRange(e,t){this._tinode._db.remMessages(this.name,e,t);for(let s=e;s=0?this._messages.delRange(s,this._messages.find({seq:t},!0)):[]}swapMessageId(e,t){const s=this._messages.find(e),i=this._messages.length();0<=s&&s=0){const s=this._messages.getAt(t),i=this.msgStatus(s);if(10==i||30==i||40==i)return this._tinode._db.remMessages(this.name,e),s._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1}getType(){return it.topicType(this.name)}getAccessMode(){return this.acs}setAccessMode(e){return this.acs=new t(e)}getDefaultAccess(){return this.defacs}startMetaQuery(){return new Le(this)}isArchived(){return this.private&&!!this.private.arch}isMeType(){return it.isMeTopicName(this.name)}isChannelType(){return it.isChannelTopicName(this.name)}isGroupType(){return it.isGroupTopicName(this.name)}isP2PType(){return it.isP2PTopicName(this.name)}isCommType(){return it.isCommTopicName(this.name)}msgStatus(e,t){let s=0;return this._tinode.isMe(e.from)?e._sending?s=20:e._fatal||e._cancelled?s=40:e._failed?s=30:e.seq>=u?s=10:this.msgReadCount(e.seq)>0?s=70:this.msgRecvCount(e.seq)>0?s=60:e.seq>0&&(s=50):s=80,t&&e._status!=s&&(e._status=s,this._tinode._db.updMessageStatus(this.name,e.seq,s)),s}_isReplacementMsg(e){return e.head&&e.head.replace}_maybeUpdateMessageVersionsCache(e){if(!this._isReplacementMsg(e))return void(this._messageVersions[e.seq]&&(this._messageVersions[e.seq].filter((t=>t.from==e.from)),this._messageVersions[e.seq].isEmpty()&&delete this._messageVersions[e.seq]));const t=parseInt(e.head.replace.split(":")[1]);if(t>e.seq)return;const s=this.findMessage(t);if(s&&s.from!=e.from)return;const i=this._messageVersions[t]||new Ye(((e,t)=>e.seq-t.seq),!0);i.put(e),this._messageVersions[t]=i}_routeData(e){e.content&&(!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq,this.msgStatus(e,!0),clearTimeout(this._recvNotificationTimer),this._recvNotificationTimer=setTimeout((e=>{this._recvNotificationTimer=null,this.noteRecv(this._maxSeq)}),100)),(e.seq0&&this._processMetaSub(e.sub),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds(e.cred),this.onMeta&&this.onMeta(e)}_routePres(e){let s,i;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":s=this._users[e.src],s?s.online="on"==e.what:this._tinode.logger("WARNING: Presence update for an unknown user",this.name,e.src);break;case"term":this._resetSub();break;case"upd":e.src&&!this._tinode.isTopicCached(e.src)&&this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":if(i=e.src||this._tinode.getCurrentUserID(),s=this._users[i],s)s.acs.updateAll(e.dacs),this._processMetaSub([{user:i,updated:new Date,acs:s.acs}]);else{const n=(new t).updateAll(e.dacs);n&&n.mode!=t._NONE&&(s=this._cacheGetUser(i),s?s.acs=n:(s={user:i,acs:n},this.getMeta(this.startMetaQuery().withOneSub(void 0,i).build())),s.updated=new Date,this._processMetaSub([s]))}break;default:this._tinode.logger("INFO: Ignored presence update",e.what)}this.onPres&&this.onPres(e)}_routeInfo(e){switch(e.what){case"recv":case"read":const t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv0&&this.onData&&this.onData()}_allMessagesReceived(e){this.onAllMessagesReceived&&this.onAllMessagesReceived(e)}_resetSub(){this._attached=!1}_gone(){this._messages.reset(),this._tinode._db.remMessages(this.name),this._users={},this.acs=new t(null),this.private=null,this.public=null,this.trusted=null,this._maxSeq=0,this._minSeq=0,this._attached=!1;const e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:h,src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()}_updateCachedUser(e,t){let s=this._cacheGetUser(e);return s=v(s||{},t),this._cachePutUser(e,s),y(this._users,e,s)}_getQueuedSeqId(){return this._queuedSeqId++}_loadMessages(e,t){const{since:s,before:i,limit:n}=t||{};return e.readMessages(this.name,{since:s,before:i,limit:n||24}).then((e=>(e.forEach((e=>{e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq{e.online&&(e.online=!1,e.seen=Object.assign(e.seen||{},{when:new Date}),this._refreshContact("off",e))})),this.onMetaDesc&&this.onMetaDesc(this)}_processMetaSub(e){let t=0;if(e.forEach((e=>{const s=e.topic;if(s==l||s==h)return;e.online=!!e.online;let i=null;if(e.deleted)i=e,this._tinode.cacheRemTopic(s),this._tinode._db.remTopic(s);else{void 0!==e.seq&&(e.seq=0|e.seq,e.recv=0|e.recv,e.read=0|e.read,e.unread=e.seq-e.read);const t=this._tinode.getTopic(s);t._new&&delete t._new,i=v(t,e),this._tinode._db.updTopic(i),it.isP2PTopicName(s)&&(this._cachePutUser(s,i),this._tinode._db.updUser(s,i.public)),!e._noForwarding&&t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(i)})),this.onSubsUpdated&&t>0){const s=[];e.forEach((e=>{s.push(e.topic)})),this.onSubsUpdated(s,t)}}_processMetaCreds(e,t){1==e.length&&e[0]==f&&(e=[]),t?e.forEach((e=>{if(e.val){let t=this._credentials.findIndex((t=>t.meth==e.meth&&t.val==e.val));t<0?(e.done||(t=this._credentials.findIndex((t=>t.meth==e.meth&&!t.done)),t>=0&&this._credentials.splice(t,1)),this._credentials.push(e)):this._credentials[t].done=e.done}else if(e.resp){const t=this._credentials.findIndex((t=>t.meth==e.meth&&!t.done));t>=0&&(this._credentials[t].done=!0)}})):this._credentials=e,this.onCredsUpdated&&this.onCredsUpdated(this._credentials)}_routePres(e){if("term"==e.what)return void this._resetSub();if("upd"==e.what&&e.src==h)return void this.getMeta(this.startMetaQuery().withDesc().build());const s=this._tinode.cacheGetTopic(e.src);if(s){switch(e.what){case"on":s.online=!0;break;case"off":s.online&&(s.online=!1,s.seen=Object.assign(s.seen||{},{when:new Date}));break;case"msg":s._updateReceived(e.seq,e.act);break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":s.acs?s.acs.updateAll(e.dacs):s.acs=(new t).updateAll(e.dacs),s.touched=new Date;break;case"ua":s.seen={when:new Date,ua:e.ua};break;case"recv":e.seq=0|e.seq,s.recv=s.recv?Math.max(s.recv,e.seq):e.seq;break;case"read":e.seq=0|e.seq,s.read=s.read?Math.max(s.read,e.seq):e.seq,s.recv=s.recv?Math.max(s.read,s.recv):s.recv,s.unread=s.seq-s.read;break;case"gone":s._deleted?this._tinode._db.remTopic(e.src):(s._deleted=!0,s._attached=!1,this._tinode._db.markTopicAsDeleted(e.src));break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",e.what)}this._refreshContact(e.what,s)}else if("acs"==e.what){const s=new t(e.dacs);if(!s||s.mode==t._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(s.mode==t._NONE)return void this._tinode.logger("WARNING: Removing non-existent subscription",e.src,e.dacs);{this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build());const t=this._tinode.getTopic(e.src);t.topic=e.src,t.online=!1,t.acs=s,this._tinode._db.updTopic(t)}}else"tags"==e.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(e)}_refreshContact(e,t){this.onContactUpdate&&this.onContactUpdate(e,t)}publish(){return Promise.reject(new Error("Publishing to 'me' is not supported"))}delCredential(e,t){return this._attached?this._tinode.delCredential(e,t).then((s=>{const i=this._credentials.findIndex((s=>s.meth==e&&s.val==t));return i>-1&&this._credentials.splice(i,1),this.onCredsUpdated&&this.onCredsUpdated(this._credentials),s})):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))}contacts(e,t,s){this._tinode.mapTopics(((i,n)=>{!i.isCommType()||t&&!t(i)||e.call(s,i,n)}))}getContact(e){return this._tinode.cacheGetTopic(e)}getAccessMode(e){if(e){const t=this._tinode.cacheGetTopic(e);return t?t.acs:null}return this.acs}isArchived(e){const t=this._tinode.cacheGetTopic(e);return t&&t.private&&!!t.private.arch}getCredentials(){return this._credentials}}class rt extends it{constructor(e){super(l,e),st(this,"_contacts",{})}_processMetaSub(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let s in e){let i=e[s];const n=i.topic?i.topic:i.user;i=y(this._contacts,n,i),t++,this.onMetaSub&&this.onMetaSub(i)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))}publish(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))}setMeta(e){return Object.getPrototypeOf(rt.prototype).setMeta.call(this,e).then((e=>{Object.keys(this._contacts).length>0&&(this._contacts={},this.onSubsUpdated&&this.onSubsUpdated([]))}))}contacts(e,t){const s=e||this.onMetaSub;if(s)for(let e in this._contacts)s.call(t,this._contacts[e],e,this._contacts)}}function at(e,t){!function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.add(e)}function ot(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function ct(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let ht,lt,dt;function ut(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function pt(e,s){if(s instanceof Date)s=function(e){if(!w(e))return;const t=function(e,t){return"0".repeat((t=t||2)-(""+e).length)+e},s=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+(s?"."+t(s,3):"")+"Z"}(s);else if(s instanceof t)s=s.jsonHelper();else if(null==s||!1===s||Array.isArray(s)&&0==s.length||"object"==typeof s&&0==Object.keys(s).length)return;return s}function gt(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":pt(0,t)}"undefined"!=typeof WebSocket&&(ht=WebSocket),"undefined"!=typeof XMLHttpRequest&&(lt=XMLHttpRequest),"undefined"!=typeof indexedDB&&(dt=indexedDB),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(s.g.btoa=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s="";for(let i,n=0,r=0,a=e;t.charAt(0|r)||(a="=",r%1);s+=a.charAt(63&n>>8-r%1*8)){if(i=t.charCodeAt(r+=3/4),i>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");n=n<<8|i}return s}),"undefined"==typeof atob&&(s.g.atob=function(){let t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").replace(/=+$/,""),s="";if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let i,n=0,r=0,a=0;i=t.charAt(a++);~i&&(r=n%4?64*r+i:i,n++%4)?s+=String.fromCharCode(255&r>>(-2*n&6)):0)i=e.indexOf(i);return s}),"undefined"==typeof window&&(s.g.window={WebSocket:ht,XMLHttpRequest:lt,indexedDB:dt,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}}),te.setNetworkProviders(ht,lt),qe.setNetworkProvider(lt),Te.setDatabaseProvider(dt)}();var ft=new WeakSet,mt=new WeakSet,_t=new WeakSet,bt=new WeakSet,wt=new WeakSet,vt=new WeakSet,yt=new WeakSet,Mt=new WeakSet,St=new WeakSet,Tt=new WeakSet,Pt=new WeakSet,xt=new WeakSet,Et=new WeakSet,kt=new WeakSet;class At{constructor(e,t){if(at(this,kt),at(this,Et),at(this,xt),at(this,Pt),at(this,Tt),at(this,St),at(this,Mt),at(this,yt),at(this,vt),at(this,wt),at(this,bt),at(this,_t),at(this,mt),at(this,ft),ot(this,"_host",void 0),ot(this,"_secure",void 0),ot(this,"_appName",void 0),ot(this,"_apiKey",void 0),ot(this,"_browser",""),ot(this,"_platform",void 0),ot(this,"_hwos","undefined"),ot(this,"_humanLanguage","xx"),ot(this,"_loggingEnabled",!1),ot(this,"_trimLongStrings",!1),ot(this,"_myUID",null),ot(this,"_authenticated",!1),ot(this,"_login",null),ot(this,"_authToken",null),ot(this,"_inPacketCount",0),ot(this,"_messageId",Math.floor(65535*Math.random()+65535)),ot(this,"_serverInfo",null),ot(this,"_deviceToken",null),ot(this,"_pendingPromises",{}),ot(this,"_expirePromises",null),ot(this,"_connection",null),ot(this,"_persist",!1),ot(this,"_db",null),ot(this,"_cache",{}),ot(this,"onWebsocketOpen",void 0),ot(this,"onConnect",void 0),ot(this,"onDisconnect",void 0),ot(this,"onLogin",void 0),ot(this,"onCtrlMessage",void 0),ot(this,"onDataMessage",void 0),ot(this,"onPresMessage",void 0),ot(this,"onMessage",void 0),ot(this,"onRawMessage",void 0),ot(this,"onNetworkProbe",void 0),ot(this,"onAutoreconnectIteration",void 0),this._host=e.host,this._secure=e.secure,this._appName=e.appName||"Undefined",this._apiKey=e.apiKey,this._platform=e.platform||"web","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";let s,i="";/reactnative/i.test(t)&&(i="ReactNative; ");let n=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(n){const t=["edg","chrome","safari","mobile","version"];let i,r=e.substr(n.index+n[0].length).split(" "),a=[];for(let e=0;es[1].toLowerCase().startsWith(e)))]),"Version"==s[1]&&(i=s[2]))}a.sort(((e,t)=>e[2]-t[2])),a.length>0?(a[0][0].toLowerCase().startsWith("edg")?a[0][0]="Edge":"OPR"==a[0][0]?a[0][0]="Opera":"Safari"==a[0][0]&&i&&(a[0][1]=i),s=a[0][0]+"/"+a[0][1]):s=n[1]}else/firefox/i.test(e)?(n=/Firefox\/([.\d]+)/g.exec(e),s=n?"Firefox/"+n[1]:"Firefox/?"):(n=/([\w.]+)\/([.\d]+)/.exec(e),n?s=n[1]+"/"+n[2]:(n=e.split(" "),s=n[0]));if(n=s.split("/"),n.length>1){const e=n[1].split("."),t=e[1]?"."+e[1].substr(0,2):"";s=`${n[0]}/${e[0]}${t}`}return i+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),te.logger=this.logger,Ne().logger=this.logger,"lp"!=e.transport&&"ws"!=e.transport&&(e.transport=function(){if("object"==typeof window){if(window.WebSocket)return"ws";if(window.XMLHttpRequest)return"lp"}return null}()),this._connection=new te(e,"0",!0),this._connection.onMessage=e=>{ct(this,bt,Ct).call(this,e)},this._connection.onOpen=e=>ct(this,wt,qt).call(this),this._connection.onDisconnect=(e,t)=>ct(this,vt,Ut).call(this,e,t),this._connection.onAutoreconnectIteration=(e,t)=>{this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e,t)},this._persist=e.persist,this._db=new Te((e=>{this.logger("DB",e)}),this.logger),this._persist){const e=[];this._db.initDatabase().then((t=>this._db.mapTopics((t=>{let s=ct(this,Tt,Lt).call(this,"topic",t.name);s||(s=t.name==h?new nt:t.name==l?new rt:new it(t.name),this._db.deserializeTopic(s,t),ct(this,Et,zt).call(this,s),s._cachePutSelf(),delete s._new,e.push(s._loadMessages(this._db)))})))).then((e=>this._db.mapUsers((e=>{ct(this,St,jt).call(this,"user",e.uid,v({},e.public))})))).then((t=>Promise.all(e))).then((e=>{t&&t(),this.logger("Persistent cache initialized.")})).catch((e=>{t&&t(e),this.logger("Failed to initialize persistent cache:",e)}))}else this._db.deleteDatabase().then((e=>{t&&t()}))}logger(e){if(this._loggingEnabled){const n=new Date,r=("0"+n.getUTCHours()).slice(-2)+":"+("0"+n.getUTCMinutes()).slice(-2)+":"+("0"+n.getUTCSeconds()).slice(-2)+"."+("00"+n.getUTCMilliseconds()).slice(-3);for(var t=arguments.length,s=new Array(t>1?t-1:0),i=1;i0&&(r.extra={attachments:n.attachments.filter((e=>b(e)))})),ct(this,_t,Nt).call(this,r,r.acc.id)}createAccount(e,t,s,i){let n=this.account("new",e,t,s,i);return s&&(n=n.then((e=>ct(this,kt,Gt).call(this,e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",ut(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",ut(t+":"+s),!1,i)}hello(){const e=ct(this,Mt,Ot).call(this,"hi");return ct(this,_t,Nt).call(this,e,e.hi.id).then((e=>(this._connection.backoffReset(),e.params&&(this._serverInfo=e.params),this.onConnect&&this.onConnect(),e))).catch((e=>{this._connection.reconnect(!0),this.onDisconnect&&this.onDisconnect(e)}))}setDeviceToken(e){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(ct(this,_t,Nt).call(this,{hi:{dev:e||At.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=ct(this,Mt,Ot).call(this,"login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,ct(this,_t,Nt).call(this,i,i.login.id).then((e=>ct(this,kt,Gt).call(this,e)))}loginBasic(e,t,s){return this.login("basic",ut(e+":"+t),s).then((t=>(this._login=e,t)))}loginToken(e,t){return this.login("token",e,t)}requestResetAuthSecret(e,t,s){return this.login("reset",ut(e+":"+t+":"+s))}getAuthToken(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)}setAuthToken(e){this._authToken=e}subscribe(e,t,s){const i=ct(this,Mt,Ot).call(this,"sub",e);if(e||(e=o),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;At.isNewGroupTopicName(e)?i.sub.set.desc=t:At.isP2PTopicName(e)&&t.defacs&&(i.sub.set.desc={defacs:t.defacs})}Array.isArray(s.attachments)&&s.attachments.length>0&&(i.extra={attachments:s.attachments.filter((e=>b(e)))}),s.tags&&(i.sub.set.tags=s.tags)}return ct(this,_t,Nt).call(this,i,i.sub.id)}leave(e,t){const s=ct(this,Mt,Ot).call(this,"leave",e);return s.leave.unsub=t,ct(this,_t,Nt).call(this,s,s.leave.id)}createMessage(e,t,s){const i=ct(this,Mt,Ot).call(this,"pub",e);let n="string"==typeof t?Ne().parse(t):t;return n&&!Ne().isPlainText(n)&&(i.pub.head={mime:Ne().getContentType()},t=n),i.pub.noecho=s,i.pub.content=t,i.pub}publish(e,t,s){return this.publishMessage(this.createMessage(e,t,s))}publishMessage(e,t){(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0;const s={pub:e};return t&&(s.extra={attachments:t.filter((e=>b(e)))}),ct(this,_t,Nt).call(this,s,e.id)}oobNotification(e){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(e,gt):e)),e.what){case"msg":if(!e.seq||e.seq<1||!e.topic)break;if(!this.isConnected())break;const s=ct(this,Tt,Lt).call(this,"topic",e.topic);if(!s)break;if(s.isSubscribed())break;s.maxMsgSeq(){this.logger("Failed to get the name of a new sender",e)})),s.subscribe(null).then((e=>s.getMeta(new Le(s).withLaterData(24).withLaterDel(24).build()))).then((e=>{s.leaveDelayed(!1,1e3)})).catch((e=>{this.logger("On push data fetch failed",e)})).finally((e=>{this.getMeTopic()._refreshContact("msg",s)})));break;case"read":this.getMeTopic()._routePres({what:"read",seq:e.seq});break;case"sub":if(!this.isMe(e.xfrom))break;const i={given:e.modeGiven,want:e.modeWant},n=new t(i),r=n.mode&&n.mode!=t._NONE?{what:"acs",src:e.topic,dacs:i}:{what:"gone",src:e.topic};this.getMeTopic()._routePres(r);break;default:this.logger("Unknown push type ignored",e.what)}}getMeta(e,t){const s=ct(this,Mt,Ot).call(this,"get",e);return s.get=v(s.get,t),ct(this,_t,Nt).call(this,s,s.get.id)}setMeta(e,t){const s=ct(this,Mt,Ot).call(this,"set",e),i=[];return t&&(["desc","sub","tags","cred","ephemeral"].forEach((function(e){t.hasOwnProperty(e)&&(i.push(e),s.set[e]=t[e])})),Array.isArray(t.attachments)&&t.attachments.length>0&&(s.extra={attachments:t.attachments.filter((e=>b(e)))})),0==i.length?Promise.reject(new Error("Invalid {set} parameters")):ct(this,_t,Nt).call(this,s,s.set.id)}delMessages(e,t,s){const i=ct(this,Mt,Ot).call(this,"del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,ct(this,_t,Nt).call(this,i,i.del.id)}delTopic(e,t){const s=ct(this,Mt,Ot).call(this,"del",e);return s.del.what="topic",s.del.hard=t,ct(this,_t,Nt).call(this,s,s.del.id)}delSubscription(e,t){const s=ct(this,Mt,Ot).call(this,"del",e);return s.del.what="sub",s.del.user=t,ct(this,_t,Nt).call(this,s,s.del.id)}delCredential(e,t){const s=ct(this,Mt,Ot).call(this,"del",h);return s.del.what="cred",s.del.cred={meth:e,val:t},ct(this,_t,Nt).call(this,s,s.del.id)}delCurrentUser(e){const t=ct(this,Mt,Ot).call(this,"del",null);return t.del.what="user",t.del.hard=e,ct(this,_t,Nt).call(this,t,t.del.id).then((e=>{this._myUID=null}))}note(e,t,s){if(s<=0||s>=u)throw new Error(`Invalid message id ${s}`);const i=ct(this,Mt,Ot).call(this,"note",e);i.note.what=t,i.note.seq=s,ct(this,_t,Nt).call(this,i)}noteKeyPress(e,t){const s=ct(this,Mt,Ot).call(this,"note",e);s.note.what=t||"kp",ct(this,_t,Nt).call(this,s)}videoCall(e,t,s,i){const n=ct(this,Mt,Ot).call(this,"note",e);n.note.seq=t,n.note.what="call",n.note.event=s,n.note.payload=i,ct(this,_t,Nt).call(this,n,n.note.id)}getTopic(e){let t=ct(this,Tt,Lt).call(this,"topic",e);return!t&&e&&(t=e==h?new nt:e==l?new rt:new it(e),ct(this,Et,zt).call(this,t),t._cachePutSelf()),t}cacheGetTopic(e){return ct(this,Tt,Lt).call(this,"topic",e)}cacheRemTopic(e){ct(this,Pt,Wt).call(this,"topic",e)}mapTopics(e,t){ct(this,xt,Vt).call(this,"topic",e,t)}isTopicCached(e){return!!ct(this,Tt,Lt).call(this,"topic",e)}newGroupTopicName(e){return(e?c:o)+this.getNextUniqueId()}getMeTopic(){return this.getTopic(h)}getFndTopic(){return this.getTopic(l)}getLargeFileHelper(){return new qe(this,"0")}getCurrentUserID(){return this._myUID}isMe(e){return this._myUID===e}getCurrentLogin(){return this._login}getServerInfo(){return this._serverInfo}report(e,t){return this.publish("sys",Ne().attachJSON(null,{action:e,target:t}))}getServerParam(e,t){return this._serverInfo&&this._serverInfo[e]||t}enableLogging(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t}setHumanLanguage(e){e&&(this._humanLanguage=e)}isTopicOnline(e){const t=ct(this,Tt,Lt).call(this,"topic",e);return t&&t.online}getTopicAccessMode(e){const t=ct(this,Tt,Lt).call(this,"topic",e);return t?t.acs:null}wantAkn(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0}}function Dt(e){let t=null;return e&&(t=new Promise(((t,s)=>{this._pendingPromises[e]={resolve:t,reject:s,ts:new Date}}))),t}function Rt(e,t,s,i){const n=this._pendingPromises[e];n&&(delete this._pendingPromises[e],t>=200&&t<400?n.resolve&&n.resolve(s):n.reject&&n.reject(new m(i,t)))}function Nt(e,t){let s;t&&(s=ct(this,ft,Dt).call(this,t)),e=M(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,gt):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;ct(this,mt,Rt).call(this,t,te.NETWORK_ERROR,null,e.message)}return s}function Ct(e){if(!e)return;if(this._inPacketCount++,this.onRawMessage&&this.onRawMessage(e),"0"===e)return void(this.onNetworkProbe&&this.onNetworkProbe());let t=JSON.parse(e,_);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,gt):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&ct(this,mt,Rt).call(this,t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout((e=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=ct(this,Tt,Lt).call(this,"topic",t.ctrl.topic);e&&(e._resetSub(),t.ctrl.params&&t.ctrl.params.unsub&&e._gone())}else if(t.ctrl.code<300&&t.ctrl.params)if("data"==t.ctrl.params.what){const e=ct(this,Tt,Lt).call(this,"topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=ct(this,Tt,Lt).call(this,"topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((e=>{if(t.meta){const e=ct(this,Tt,Lt).call(this,"topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&ct(this,mt,Rt).call(this,t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=ct(this,Tt,Lt).call(this,"topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=ct(this,Tt,Lt).call(this,"topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=ct(this,Tt,Lt).call(this,"topic",t.info.topic);e&&e._routeInfo(t.info),this.onInfoMessage&&this.onInfoMessage(t.info)}else this.logger("ERROR: Unknown packet received.")}),0)):(this.logger("in: "+e),this.logger("ERROR: failed to parse data"))}function qt(){this._expirePromises||(this._expirePromises=setInterval((e=>{const t=new m("timeout",504),s=new Date((new Date).getTime()-p);for(let e in this._pendingPromises){let i=this._pendingPromises[e];i&&i.ts{e._resetSub()}));for(let t in this._pendingPromises){const s=this._pendingPromises[t];s&&s.reject&&s.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}function It(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+a}function Ot(e,t){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:r,ua:ct(this,yt,It).call(this),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:t,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:t,desc:{},sub:{},tags:[],ephemeral:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw new Error(`Unknown packet type requested: ${e}`)}}function jt(e,t,s){this._cache[e+":"+t]=s}function Lt(e,t){return this._cache[e+":"+t]}function Wt(e,t){delete this._cache[e+":"+t]}function Vt(e,t,s){const i=e?e+":":void 0;for(let e in this._cache)if((!i||0==e.indexOf(i))&&t.call(s,this._cache[e],e))break}function zt(e){e._tinode=this,e._cacheGetUser=e=>{const t=ct(this,Tt,Lt).call(this,"user",e);if(t)return{user:e,public:v({},t)}},e._cachePutUser=(e,t)=>{ct(this,St,jt).call(this,"user",e,v({},t.public))},e._cacheDelUser=e=>{ct(this,Pt,Wt).call(this,"user",e)},e._cachePutSelf=t=>{ct(this,St,jt).call(this,"topic",e.name,e)},e._cacheDelSelf=t=>{ct(this,Pt,Wt).call(this,"topic",e.name)}}function Gt(e){return e.params&&e.params.user?(this._myUID=e.params.user,this._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?this._authToken={token:e.params.token,expires:e.params.expires}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text),e):e}At.MESSAGE_STATUS_NONE=0,At.MESSAGE_STATUS_QUEUED=10,At.MESSAGE_STATUS_SENDING=20,At.MESSAGE_STATUS_FAILED=30,At.MESSAGE_STATUS_FATAL=40,At.MESSAGE_STATUS_SENT=50,At.MESSAGE_STATUS_RECEIVED=60,At.MESSAGE_STATUS_READ=70,At.MESSAGE_STATUS_TO_ME=80,At.DEL_CHAR=f,At.MAX_MESSAGE_SIZE="maxMessageSize",At.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",At.MAX_TAG_COUNT="maxTagCount",At.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",At.REQ_CRED_VALIDATORS="reqCred"})(),i})()));
\ No newline at end of file
+!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.tinode=t():e.tinode=t()}(this,(()=>(()=>{"use strict";var e={577:e=>{const t=64,s="application/json",i=["act","height","duration","incoming","mime","name","premime","preref","preview","ref","size","state","url","val","width"],n=[{name:"ST",start:/(?:^|[\W_])(\*)[^\s*]/,end:/[^\s*](\*)(?=$|[\W_])/},{name:"EM",start:/(?:^|\W)(_)[^\s_]/,end:/[^\s_](_)(?=$|\W)/},{name:"DL",start:/(?:^|[\W_])(~)[^\s~]/,end:/[^\s~](~)(?=$|[\W_])/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],r=["QQ"],a=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu}],o={AU:{html_tag:"audio",md_tag:void 0,isVoid:!1},BN:{html_tag:"button",md_tag:void 0,isVoid:!1},BR:{html_tag:"br",md_tag:"\n",isVoid:!0},CO:{html_tag:"tt",md_tag:"`",isVoid:!1},DL:{html_tag:"del",md_tag:"~",isVoid:!1},EM:{html_tag:"i",md_tag:"_",isVoid:!1},EX:{html_tag:"",md_tag:void 0,isVoid:!0},FM:{html_tag:"div",md_tag:void 0,isVoid:!1},HD:{html_tag:"",md_tag:void 0,isVoid:!1},HL:{html_tag:"span",md_tag:void 0,isVoid:!1},HT:{html_tag:"a",md_tag:void 0,isVoid:!1},IM:{html_tag:"img",md_tag:void 0,isVoid:!1},LN:{html_tag:"a",md_tag:void 0,isVoid:!1},MN:{html_tag:"a",md_tag:void 0,isVoid:!1},RW:{html_tag:"div",md_tag:void 0,isVoid:!1},QQ:{html_tag:"div",md_tag:void 0,isVoid:!1},ST:{html_tag:"b",md_tag:"*",isVoid:!1},VC:{html_tag:"div",md_tag:void 0,isVoid:!1},VD:{html_tag:"video",md_tag:void 0,isVoid:!1}};function c(e,t,s){if(!e)return null;try{const s=atob(e),i=s.length,n=new ArrayBuffer(i),r=new Uint8Array(n);for(let e=0;e"",close:e=>""},EM:{open:e=>"",close:e=>""},DL:{open:e=>"",close:e=>""},CO:{open:e=>"",close:e=>""},BR:{open:e=>"
",close:e=>""},HD:{open:e=>"",close:e=>""},HL:{open:e=>'',close:e=>""},LN:{open:e=>'',close:e=>"",props:e=>e?{href:e.url,target:"_blank"}:null},MN:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},HT:{open:e=>'',close:e=>"",props:e=>e?{id:e.val}:null},BN:{open:e=>"",props:e=>e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null},AU:{open:e=>'",props:e=>e?{src:e.ref||c(e.val,e.mime,d.logger),"data-preload":e.ref?"metadata":"auto","data-duration":e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},IM:{open:e=>{const t=h(e._tempPreview,e.mime),s=c(e.val,e.mime,d.logger),i=e.ref||s;return(e.name?'':"")+'
'},close:e=>e.name?"":"",props:e=>e?{src:h(e._tempPreview,e.mime)||e.ref||c(e.val,e.mime,d.logger),title:e.name,alt:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},FM:{open:e=>"",close:e=>""},RW:{open:e=>"",close:e=>""},QQ:{open:e=>"",close:e=>"",props:e=>e?{}:null},VC:{open:e=>"",close:e=>"",props:e=>e?{"data-duration":e.duration,"data-state":e.state}:{}},VD:{open:e=>{const t=h(e._tempPreview,e.mime),s=e.ref||c(e.preview,e.premime||"image/jpeg",d.logger);return'
'},close:e=>"",props:e=>{if(!e)return null;const t=e.preref||c(e.preview,e.premime||"image/jpeg",d.logger);return{src:t,"data-src":e.ref||c(e.val,e.mime,d.logger),"data-width":e.width,"data-height":e.height,"data-preload":e.ref?"metadata":"auto","data-preview":t,"data-duration":0|e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}}}},d=function(){this.txt="",this.fmt=[],this.ent=[]};function u(e,t,s,i){const n=[];if(0==i.length)return[];for(let s in i){const r=i[s];r.at>t&&n.push({txt:e.slice(t,r.at)});const a={tp:r.tp},o=u(e,r.at+1,r.end,r.children);o.length>0?a.children=o:a.txt=r.txt,n.push(a),t=r.end+1}return ts.end?(t.push(e[i]),s=e[i]):e[i].end<=s.end&&s.children.push(e[i]);for(let e in t)t[e].children=p(t[e].children);return t}function g(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:i}=e;if(t=t||"",Array.isArray(i)||(i=[]),!Array.isArray(s)||0==s.length){if(0==i.length)return{text:t};s=[{at:0,len:0,key:0}]}const n=[],a=[];s.forEach((e=>{if(!e||"object"!=typeof e)return;if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,r=0|e.len;if(r<0)return;let o=e.key||0;i.length>0&&("number"!=typeof o||o<0||o>=i.length)||(s<=-1?a.push({start:-1,end:0,key:o}):s+r>t.length||(e.tp?n.push({type:e.tp,start:s,end:s+r}):i.length>0&&"object"==typeof i[o]&&n.push({start:s,end:s+r,key:o})))})),n.sort(((e,t)=>{let s=e.start-t.start;return 0!=s?s:(s=t.end-e.end,0!=s?s:r.indexOf(t.type)-r.indexOf(e.type))})),a.length>0&&n.push(...a),n.forEach((e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")}));let o=m({},t,0,t.length,n);return o=b(o,(function(e){if(Array.isArray(e.children)&&1==e.children.length){const t=e.children[0];if(e.type)t.type||t.children||(e.text=t.text,delete e.children);else{const s=e.parent;(e=t).parent=s}}return e})),o}function f(e,t){return t?(e.children||(e.children=[]),e.text&&(e.children.push({text:e.text,parent:e}),delete e.text),t.parent=e,e.children.push(t),e):e}function m(e,t,s,i,n){if(!n||0==n.length)return s{_(e,t,s)})),t.type){const n=e.txt.length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];const r=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=r,e.ent[r]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:r}):e.fmt.push({at:i,len:n,key:r})}else e.fmt.push({tp:t.type,at:i,len:n})}return e}function b(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;const n=[];for(let e in i.children){let r=i.children[e];r&&(r=b(r,t,s),r&&n.push(r))}return 0==n.length?i.children=null:i.children=n,i}function w(e,t,s,i,n){if(!e)return null;i&&e.type&&i.push(e.type);let r=[];for(let s in e.children){const a=w(e.children[s],t,s,i,n);a&&r.push(a)}return 0==r.length&&(r=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(n,e.type,e.data,r,s,i)}function v(e,t,s){return e?(s&&(t-=s.length),b(e,(function(e){if(t<=-1)return null;if(e.att)return e;if(0==t)e.text=s,t=-1;else if(e.text){const i=e.text.length;i>t?(e.text=e.text.substring(0,t)+s,t=-1):t-=i}return e}))):null}function y(e,t){return b(e,(e=>{const s=P(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e}))}function M(e){if("BR"==e.type)e=null;else if(e.text)e.type||(e.text=e.text.trimStart(),e.text||(e=null));else if(!e.type&&e.children&&e.children.length>0){const t=M(e.children[0]);t?e.children[0]=t:(e.children.shift(),e.type||0!=e.children.length||(e=null))}return e}function S(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const i=[],n=[];for(let r in e.children){const a=e.children[r];if(a.att){if(i.length==t)continue;if(a.data.mime==s)continue;delete a.att,delete a.children,a.text=" ",i.push(a)}else n.push(a)}e.children=n.concat(i)}return e}function T(e,t){let s="",i=[];for(let n in e){const r=e[n];if(!r.txt){const e=T(r.children,s.length+t);r.txt=e.txt,i=i.concat(e.fmt)}r.tp&&i.push({at:s.length+t,len:r.txt.length,tp:r.tp}),s+=r.txt}return{txt:s,fmt:i}}function P(e,s,n){if(e&&Object.entries(e).length>0){n=n||[];const r={};if(i.forEach((i=>{if(e[i]){if(s&&!n.includes(i)&&("string"==typeof e[i]||Array.isArray(e[i]))&&e[i].length>t)return;if("object"==typeof e[i])return;r[i]=e[i]}})),0!=Object.entries(r).length)return r}return null}d.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},d.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],i={},r=[];t.forEach((e=>{let t,o,c=[];if(n.forEach((t=>{c=c.concat(function(e,t,s,i){const n=[];let r=0,a=e.slice(0);for(;a.length>0;){const o=t.exec(a);if(null==o)break;let c=o.index+o[0].lastIndexOf(o[1]);a=a.slice(c+1),c+=r,r=c+1;const h=s?s.exec(a):null;if(null==h)break;let l=h.index+h[0].indexOf(h[1]);a=a.slice(l+1),l+=r,r=l+1,n.push({txt:e.slice(c+1,l),children:[],at:c,end:l,tp:i})}return n}(e,t.start,t.end,t.name))})),0==c.length)o={txt:e};else{c.sort(((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end})),c=p(c);const t=T(u(e,0,e.length,c),0);o={txt:t.txt,fmt:t.fmt}}if(t=function(e){let t,s=[];if(a.forEach((i=>{for(;null!==(t=i.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})})),0==s.length)return s;s.sort(((e,t)=>e.offset-t.offset));let i=-1;return s=s.filter((e=>{const t=e.offset>i;return i=e.offset+e.len,t})),s}(o.txt),t.length>0){const e=[];for(let n in t){const r=t[n];let a=i[r.unique];a||(a=s.length,i[r.unique]=a,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:a})}o.ent=e}r.push(o)}));const o={txt:""};if(r.length>0){o.txt=r[0].txt,o.fmt=(r[0].fmt||[]).concat(r[0].ent||[]);for(let e=1;e(e.at+=s,e))))),t.ent&&(o.fmt=o.fmt.concat(t.ent.map((e=>(e.at+=s,e)))))}0==o.fmt.length&&delete o.fmt,s.length>0&&(o.ent=s)}return o},d.append=function(e,t){if(!e)return t;if(!t)return e;e.txt=e.txt||"";const s=e.txt.length;return"string"==typeof t?e.txt+=t:t.txt&&(e.txt+=t.txt),Array.isArray(t.fmt)&&(e.fmt=e.fmt||[],Array.isArray(t.ent)&&(e.ent=e.ent||[]),t.fmt.forEach((i=>{const n={at:(0|i.at)+s,len:0|i.len};-1==i.at&&(n.at=-1,n.len=0),i.tp?n.tp=i.tp:(n.key=e.ent.length,e.ent.push(t.ent[i.key||0])),e.fmt.push(n)}))),e},d.insertImage=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"IM",data:{mime:s.mime,ref:s.refurl,val:s.bits||s.preview,width:s.width,height:s.height,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e,i.data._tempPreview=void 0,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},d.insertVideo=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"VD",data:{mime:s.mime,ref:s.refurl,val:s.bits,preref:s.preref,preview:s.preview,width:s.width,height:s.height,duration:0|s.duration,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e[0],i.data.preref=e[1],i.data._tempPreview=void 0,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},d.insertAudio=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"AU",data:{mime:s.mime,val:s.bits,duration:0|s.duration,preview:s.preview,name:s.filename,size:0|s.size,ref:s.refurl}};return s.urlPromise&&(i.data._processing=!0,s.urlPromise.then((e=>{i.data.ref=e,i.data._processing=void 0}),(e=>{i.data._processing=void 0}))),e.ent.push(i),e},d.videoCall=function(e){return{txt:" ",fmt:[{at:0,len:1,key:0}],ent:[{tp:"VC",data:{aonly:e}}]}},d.updateVideoCall=function(e,t){const s=((e||{}).fmt||[])[0];if(!s)return e;let i;if("VC"==s.tp)delete s.tp,s.key=0,i={tp:"VC"},e.ent=[i];else if(i=(e.ent||[])[0|s.key],!i||"VC"!=i.tp)return e;return i.data=i.data||{},Object.assign(i.data,t),e},d.quote=function(e,t,s){const i=d.append(d.appendLineBreak(d.mention(e,t)),s);return i.fmt.push({at:0,len:i.txt.length,tp:"QQ"}),i},d.mention=function(e,t){return{txt:e||"",fmt:[{at:0,len:(e||"").length,key:0}],ent:[{tp:"MN",data:{val:t}}]}},d.appendLink=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:t.txt.length,key:e.ent.length}),e.txt+=t.txt;const s={tp:"LN",data:{url:t.url}};return e.ent.push(s),e},d.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",d.insertImage(e,e.txt.length-1,t)},d.appendAudio=function(e,t){return(e=e||{txt:""}).txt+=" ",d.insertAudio(e,e.txt.length-1,t)},d.attachFile=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});const s={tp:"EX",data:{mime:t.mime,val:t.data,name:t.filename,ref:t.refurl,size:0|t.size}};return t.urlPromise&&(s.data._processing=!0,t.urlPromise.then((e=>{s.data.ref=e,s.data._processing=void 0}),(e=>{s.data._processing=void 0}))),e.ent.push(s),e},d.wrapInto=function(e,t,s,i){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:s||0,len:i||e.txt.length,tp:t}),e},d.wrapAsForm=function(e,t,s){return d.wrapInto(e,"FM",t,s)},d.insertButton=function(e,t,s,i,n,r,a){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length{switch(e.type){case"IM":return["val"];case"VD":return["preview"]}return null})),_({},s,[])):e},d.preview=function(e,t,s){let i=g(e);if(i=S(i,3),i=b(i,(function(e){return"MN"==e.type?e.parent&&e.parent.type||!(e.text||"").startsWith("➦")||(e.text="➦",delete e.children):"QQ"==e.type?(e.text=" ",delete e.children):"BR"==e.type&&(e.text=" ",delete e.children,delete e.type),e})),i=v(i,t,"…"),s){const e={IM:["val"],VD:["preview"]};i=y(i,(t=>e[t.type]))}else i=y(i);return _({},i,[])},d.toPlainText=function(e){return"string"==typeof e?e:e.txt},d.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},d.toMarkdown=function(e){return w(g(e),(function(e,t,s){const i=o[e];let n=s?s.join(""):"";return i&&(i.isVoid?n=i.md_tag||"":i.md_tag&&(n=i.md_tag+n+i.md_tag)),n}),0)},d.isValid=function(e){if(!e)return!1;const{txt:t,fmt:s,ent:i}=e;if(!t&&""!==t&&!s&&!i)return!1;const n=typeof t;return!("string"!=n&&"undefined"!=n&&null!==t||void 0!==s&&!Array.isArray(s)&&null!==s||void 0!==i&&!Array.isArray(i)&&null!==i)},d.hasAttachments=function(e){if(!Array.isArray(e.fmt))return!1;for(let t in e.fmt){const s=e.fmt[t];if(s&&s.at<0){const t=e.ent[0|s.key];return t&&"EX"==t.tp&&t.data}}return!1},d.attachments=function(e,t,s){if(!Array.isArray(e.fmt))return;let i=0;for(let n in e.ent){let r=e.fmt[n];if(r&&r.at<0){const n=e.ent[0|r.key];if(n&&"EX"==n.tp&&n.data&&t.call(s,n.data,i++,"EX"))break}}},d.hasEntities=function(e){return e.ent&&e.ent.length>0},d.entities=function(e,t,s){if(e.ent&&e.ent.length>0)for(let i in e.ent)if(e.ent[i]&&t.call(s,e.ent[i].data,i,e.ent[i].tp))break},d.styles=function(e,t,s){if(e.fmt&&e.fmt.length>0)for(let i in e.fmt){const n=e.fmt[i];if(n&&t.call(s,n.tp,n.at,n.len,n.key,i))break}},d.sanitizeEntities=function(e){if(e&&e.ent&&e.ent.length>0)for(let t in e.ent){const s=e.ent[t];if(s&&s.data){const i=P(s.data);i?e.ent[t].data=i:delete e.ent[t].data}}return e},d.getDownloadUrl=function(e){let t=null;return e.mime!=s&&e.val?t=c(e.val,e.mime,d.logger):"string"==typeof e.ref&&(t=e.ref),t},d.isProcessing=function(e){return!!e._processing},d.getPreviewUrl=function(e){return e.val?c(e.val,e.mime,d.logger):null},d.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},d.getEntityMimeType=function(e){return e.mime||"text/plain"},d.tagName=function(e){return o[e]&&o[e].html_tag},d.attrValue=function(e,t){if(t&&l[e])return l[e].props(t)},d.getContentType=function(){return"text/x-drafty"},e.exports=d}},t={};function s(i){var n=t[i];if(void 0!==n)return n.exports;var r=t[i]={exports:{}};return e[i](r,r.exports,s),r.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{function e(e,t,s){return function(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}(e,t),s}s.r(i),s.d(i,{AccessMode:()=>t,Drafty:()=>Ne(),Tinode:()=>At});class t{constructor(e){e&&(this.given="number"==typeof e.given?e.given:t.decode(e.given),this.want="number"==typeof e.want?e.want:t.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:t.decode(e.mode):this.given&this.want)}static decode(e){if(!e)return null;if("number"==typeof e)return e&t._BITMASK;if("N"===e||"n"===e)return t._NONE;const s={J:t._JOIN,R:t._READ,W:t._WRITE,P:t._PRES,A:t._APPROVE,S:t._SHARE,D:t._DELETE,O:t._OWNER};let i=t._NONE;for(let t=0;t=20&&s.length<=24&&["ts","touched","updated","created","when","deleted","expires"].includes(e)){const e=new Date(s);if(!isNaN(e))return e}else if("acs"===e&&"object"==typeof s)return new t(s);return s}function b(e){return e&&!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}function w(e){return e instanceof Date&&!isNaN(e)&&0!=e.getTime()}function v(e,s,i){if("object"!=typeof s){if(void 0===s)return e;if(s===f)return;return s}if(null===s)return s;if(s instanceof Date&&!isNaN(s))return!e||!(e instanceof Date)||isNaN(e)||e{"_"==t[0]?delete e[t]:e[t]?Array.isArray(e[t])&&0==e[t].length?delete e[t]:e[t]?e[t]instanceof Date?w(e[t])||delete e[t]:"object"==typeof e[t]&&(M(e[t]),0==Object.getOwnPropertyNames(e[t]).length&&delete e[t]):delete e[t]:delete e[t]})),e}function S(e,t){x(e,t),t.add(e)}function T(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function P(e,t,s){x(e,t),t.set(e,s)}function x(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function E(e,t,s){return D(e,A(e,t,"set"),s),s}function k(e,t){return q(e,A(e,t,"get"))}function A(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}function D(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=s}}function R(e,t,s){return C(e,t),N(s,"get"),q(e,s)}function N(e,t){if(void 0===e)throw new TypeError("attempted to "+t+" private static field before its declaration")}function C(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}function q(e,t){return t.get?t.get.call(e):t.value}function U(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let I,O;const j=503,L="Connection failed",W=418,V="Disconnected by client",z=2e3,G=10,B=.3;function F(e,t,s,i){let n=null;return["http","https","ws","wss"].includes(t)&&(n=`${t}://${e}`,"/"!==n.charAt(n.length-1)&&(n+="/"),n+="v"+s+"/channels",["http","https"].includes(t)&&(n+="/lp"),n+="?apikey="+i),n}var K=new WeakMap,H=new WeakMap,Q=new WeakMap,X=new WeakMap,$=new WeakSet,J=new WeakSet,Z=new WeakSet,Y=new WeakSet,ee=new WeakSet;class te{constructor(e,t,s){if(S(this,ee),S(this,Y),S(this,Z),S(this,J),S(this,$),P(this,K,{writable:!0,value:null}),P(this,H,{writable:!0,value:0}),P(this,Q,{writable:!0,value:!1}),P(this,X,{writable:!0,value:null}),T(this,"host",void 0),T(this,"secure",void 0),T(this,"apiKey",void 0),T(this,"version",void 0),T(this,"autoreconnect",void 0),T(this,"initialized",void 0),T(this,"onMessage",void 0),T(this,"onDisconnect",void 0),T(this,"onOpen",void 0),T(this,"onAutoreconnectIteration",void 0),this.host=e.host,this.secure=e.secure,this.apiKey=e.apiKey,this.version=t,this.autoreconnect=s,"lp"===e.transport?(U(this,Y,re).call(this),this.initialized="lp"):"ws"===e.transport&&(U(this,ee,ae).call(this),this.initialized="ws"),!this.initialized)throw R(te,te,oe).call(te,"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.")}static setNetworkProviders(e,t){I=e,O=t}static set logger(e){var t,s,i;s=oe,i=e,C(t=te,te),N(s,"set"),D(t,s,i)}connect(e,t){return Promise.reject(null)}reconnect(e){}disconnect(){}sendText(e){}isConnected(){return!1}transport(){return this.initialized}probe(){this.sendText("1")}backoffReset(){U(this,Z,ne).call(this)}}function se(){clearTimeout(k(this,K));const e=z*(Math.pow(2,k(this,H))*(1+B*Math.random()));E(this,H,k(this,H)>=G?k(this,H):k(this,H)+1),this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),E(this,K,setTimeout((t=>{if(R(te,te,oe).call(te,`Reconnecting, iter=${k(this,H)}, timeout=${e}`),k(this,Q))this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch((e=>{}))}}),e))}function ie(){clearTimeout(k(this,K)),E(this,K,null)}function ne(){E(this,H,0)}function re(){let e=null,t=null,s=null,i=(t,s,n)=>{let r=new O,a=!1;return r.onreadystatechange=o=>{if(4==r.readyState)if(201==r.status){let n=JSON.parse(r.responseText,_);e=t+"&sid="+n.ctrl.params.sid,r=i(e),r.send(null),this.onOpen&&this.onOpen(),s&&(a=!0,s()),this.autoreconnect&&U(this,J,ie).call(this)}else if(r.status>0&&r.status<400)this.onMessage&&this.onMessage(r.responseText),r=i(e),r.send(null);else{if(n&&!a&&(a=!0,n(r.responseText)),this.onMessage&&r.responseText&&this.onMessage(r.responseText),this.onDisconnect){const e=r.status||(k(this,Q)?W:j),t=r.responseText||(k(this,Q)?V:L);this.onDisconnect(new m(t,e),e)}r=null,!k(this,Q)&&this.autoreconnect&&U(this,$,se).call(this)}},r.open("POST",t,!0),r};this.connect=(e,s)=>{if(E(this,Q,!1),t){if(!s)return Promise.resolve();t.onreadystatechange=void 0,t.abort(),t=null}return e&&(this.host=e),new Promise(((e,s)=>{const n=F(this.host,this.secure?"https":"http",this.version,this.apiKey);R(te,te,oe).call(te,"LP connecting to:",n),t=i(n,e,s),t.send(null)})).catch((e=>{R(te,te,oe).call(te,"LP connection failed:",e)}))},this.reconnect=e=>{U(this,J,ie).call(this),this.connect(null,e)},this.disconnect=i=>{E(this,Q,!0),U(this,J,ie).call(this),s&&(s.onreadystatechange=void 0,s.abort(),s=null),t&&(t.onreadystatechange=void 0,t.abort(),t=null),this.onDisconnect&&this.onDisconnect(new m(V,W),W),e=null},this.sendText=t=>{if(s=(e=>{const t=new O;return t.onreadystatechange=e=>{if(4==t.readyState&&t.status>=400)throw new m("LP sender failed",t.status)},t.open("POST",e,!0),t})(e),!s||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(t)},this.isConnected=e=>t&&!0}function ae(){this.connect=(e,t)=>{if(E(this,Q,!1),k(this,X)){if(!t&&k(this,X).readyState==k(this,X).OPEN)return Promise.resolve();k(this,X).close(),E(this,X,null)}return e&&(this.host=e),new Promise(((e,t)=>{const s=F(this.host,this.secure?"wss":"ws",this.version,this.apiKey);R(te,te,oe).call(te,"WS connecting to: ",s);const i=new I(s);i.onerror=e=>{t(e)},i.onopen=t=>{this.autoreconnect&&U(this,J,ie).call(this),this.onOpen&&this.onOpen(),e()},i.onclose=e=>{if(E(this,X,null),this.onDisconnect){const e=k(this,Q)?W:j;this.onDisconnect(new m(k(this,Q)?V:L,e),e)}!k(this,Q)&&this.autoreconnect&&U(this,$,se).call(this)},i.onmessage=e=>{this.onMessage&&this.onMessage(e.data)},E(this,X,i)}))},this.reconnect=e=>{U(this,J,ie).call(this),this.connect(null,e)},this.disconnect=e=>{E(this,Q,!0),U(this,J,ie).call(this),k(this,X)&&(k(this,X).close(),E(this,X,null))},this.sendText=e=>{if(!k(this,X)||k(this,X).readyState!=k(this,X).OPEN)throw new Error("Websocket is not connected");k(this,X).send(e)},this.isConnected=e=>k(this,X)&&k(this,X).readyState==k(this,X).OPEN}var oe={writable:!0,value:e=>{}};function ce(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function he(e,t,s){le(e,t),t.set(e,s)}function le(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function de(e,t,s){return ge(e,t),function(e,t){if(void 0===e)throw new TypeError("attempted to get private static field before its declaration")}(s),me(e,s)}function ue(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function pe(e,t,s){return ge(e,t),s}function ge(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}function fe(e,t){return me(e,be(e,t,"get"))}function me(e,t){return t.get?t.get.call(e):t.value}function _e(e,t,s){return function(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=s}}(e,be(e,t,"set"),s),s}function be(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}te.NETWORK_ERROR=j,te.NETWORK_ERROR_TEXT=L,te.NETWORK_USER=W,te.NETWORK_USER_TEXT=V;const we="tinode-web";let ve;var ye=new WeakMap,Me=new WeakMap,Se=new WeakSet;class Te{constructor(e,t){var s;le(this,s=Se),s.add(this),he(this,ye,{writable:!0,value:e=>{}}),he(this,Me,{writable:!0,value:e=>{}}),ce(this,"db",null),ce(this,"disabled",!1),_e(this,ye,e||fe(this,ye)),_e(this,Me,t||fe(this,Me))}initDatabase(){return new Promise(((e,t)=>{const s=ve.open(we,1);s.onsuccess=t=>{this.db=t.target.result,this.disabled=!1,e(this.db)},s.onerror=e=>{fe(this,Me).call(this,"PCache","failed to initialize",e),t(e.target.error),fe(this,ye).call(this,e.target.error)},s.onupgradeneeded=e=>{this.db=e.target.result,this.db.onerror=e=>{fe(this,Me).call(this,"PCache","failed to create storage",e),fe(this,ye).call(this,e.target.error)},this.db.createObjectStore("topic",{keyPath:"name"}),this.db.createObjectStore("user",{keyPath:"uid"}),this.db.createObjectStore("subscription",{keyPath:["topic","uid"]}),this.db.createObjectStore("message",{keyPath:["topic","seq"]})}}))}deleteDatabase(){return this.db&&(this.db.close(),this.db=null),new Promise(((e,t)=>{const s=ve.deleteDatabase(we);s.onblocked=e=>{this.db&&this.db.close();const s=new Error("blocked");fe(this,Me).call(this,"PCache","deleteDatabase",s),t(s)},s.onsuccess=t=>{this.db=null,this.disabled=!0,e(!0)},s.onerror=e=>{fe(this,Me).call(this,"PCache","deleteDatabase",e.target.error),t(e.target.error)}}))}isReady(){return!!this.db}updTopic(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","updTopic",e.target.error),s(e.target.error)};const n=i.objectStore("topic").get(e.name);n.onsuccess=t=>{i.objectStore("topic").put(pe(Te,Te,Ee).call(Te,n.result,e)),i.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}markTopicAsDeleted(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","markTopicAsDeleted",e.target.error),s(e.target.error)},i.objectStore("topic").get(e).onsuccess=e=>{const t=e.target.result;t._deleted=!0,i.objectStore("topic").put(t),i.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remTopic(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["topic","subscription","message"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","remTopic",e.target.error),s(e.target.error)},i.objectStore("topic").delete(IDBKeyRange.only(e)),i.objectStore("subscription").delete(IDBKeyRange.bound([e,"-"],[e,"~"])),i.objectStore("message").delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapTopics(e,t){return ue(this,Se,Pe).call(this,"topic",e,t)}deserializeTopic(e,t){pe(Te,Te,xe).call(Te,e,t)}updUser(e,t){if(!(arguments.length<2||void 0===t))return this.isReady()?new Promise(((s,i)=>{const n=this.db.transaction(["user"],"readwrite");n.oncomplete=e=>{s(e.target.result)},n.onerror=e=>{fe(this,Me).call(this,"PCache","updUser",e.target.error),i(e.target.error)},n.objectStore("user").put({uid:e,public:t}),n.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remUser(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["user"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","remUser",e.target.error),s(e.target.error)},i.objectStore("user").delete(IDBKeyRange.only(e)),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapUsers(e,t){return ue(this,Se,Pe).call(this,"user",e,t)}getUser(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["user"]);i.oncomplete=e=>{const s=e.target.result;t({user:s.uid,public:s.public})},i.onerror=e=>{fe(this,Me).call(this,"PCache","getUser",e.target.error),s(e.target.error)},i.objectStore("user").get(e)})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updSubscription(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["subscription"],"readwrite");r.oncomplete=e=>{i(e.target.result)},r.onerror=e=>{fe(this,Me).call(this,"PCache","updSubscription",e.target.error),n(e.target.error)},r.objectStore("subscription").get([e,t]).onsuccess=i=>{r.objectStore("subscription").put(pe(Te,Te,ke).call(Te,i.target.result,e,t,s)),r.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapSubscriptions(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["subscription"]);r.onerror=e=>{fe(this,Me).call(this,"PCache","mapSubscriptions",e.target.error),n(e.target.error)},r.objectStore("subscription").getAll(IDBKeyRange.bound([e,"-"],[e,"~"])).onsuccess=e=>{t&&e.target.result.forEach((e=>{t.call(s,e)})),i(e.target.result)}})):this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}addMessage(e){return this.isReady()?new Promise(((t,s)=>{const i=this.db.transaction(["message"],"readwrite");i.onsuccess=e=>{t(e.target.result)},i.onerror=e=>{fe(this,Me).call(this,"PCache","addMessage",e.target.error),s(e.target.error)},i.objectStore("message").add(pe(Te,Te,Ae).call(Te,null,e)),i.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updMessageStatus(e,t,s){return this.isReady()?new Promise(((i,n)=>{const r=this.db.transaction(["message"],"readwrite");r.onsuccess=e=>{i(e.target.result)},r.onerror=e=>{fe(this,Me).call(this,"PCache","updMessageStatus",e.target.error),n(e.target.error)};const a=r.objectStore("message").get(IDBKeyRange.only([e,t]));a.onsuccess=i=>{const n=a.result||i.target.result;n&&n._status!=s?(r.objectStore("message").put(pe(Te,Te,Ae).call(Te,n,{topic:e,seq:t,_status:s})),r.commit()):r.commit()}})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remMessages(e,t,s){return this.isReady()?new Promise(((i,n)=>{t||s||(t=0,s=Number.MAX_SAFE_INTEGER);const r=s>0?IDBKeyRange.bound([e,t],[e,s],!1,!0):IDBKeyRange.only([e,t]),a=this.db.transaction(["message"],"readwrite");a.onsuccess=e=>{i(e.target.result)},a.onerror=e=>{fe(this,Me).call(this,"PCache","remMessages",e.target.error),n(e.target.error)},a.objectStore("message").delete(r),a.commit()})):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}readMessages(e,t,s,i){return this.isReady()?new Promise(((n,r)=>{const a=(t=t||{}).since>0?t.since:0,o=t.before>0?t.before:Number.MAX_SAFE_INTEGER,c=0|t.limit,h=[],l=IDBKeyRange.bound([e,a],[e,o],!1,!0),d=this.db.transaction(["message"]);d.onerror=e=>{fe(this,Me).call(this,"PCache","readMessages",e.target.error),r(e.target.error)},d.objectStore("message").openCursor(l,"prev").onsuccess=e=>{const t=e.target.result;t?(s&&s.call(i,t.value),h.push(t.value),c<=0||h.length{const r=this.db.transaction([e]);r.onerror=t=>{fe(this,Me).call(this,"PCache","mapObjects",e,t.target.error),n(t.target.error)},r.objectStore(e).getAll().onsuccess=e=>{t&&e.target.result.forEach((e=>{t.call(s,e)})),i(e.target.result)}})):disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}function xe(e,t){de(Te,Te,De).forEach((s=>{t.hasOwnProperty(s)&&(e[s]=t[s])})),Array.isArray(t.tags)&&(e._tags=t.tags),t.acs&&e.setAccessMode(t.acs),e.seq|=0,e.read|=0,e.unread=Math.max(0,e.seq-e.read)}function Ee(e,t){const s=e||{name:t.name};return de(Te,Te,De).forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),Array.isArray(t._tags)&&(s.tags=t._tags),t.acs&&(s.acs=t.getAccessMode().jsonHelper()),s}function ke(e,t,s,i){const n=e||{topic:t,uid:s};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach((e=>{i.hasOwnProperty(e)&&(n[e]=i[e])})),n}function Ae(e,t){const s=e||{};return["topic","seq","ts","_status","from","head","content"].forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),s}var De={writable:!0,value:["created","updated","deleted","read","recv","seq","clear","defacs","creds","public","trusted","private","touched","_deleted"]},Re=s(577),Ne=s.n(Re);let Ce;class qe{constructor(e,t){this._tinode=e,this._version=t,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this.xhr=[]}uploadWithBaseUrl(e,t,s,i,n,r){let a=`/v${this._version}/file/u/`;if(e){let t=e;if(t.endsWith("/")&&(t=t.slice(0,-1)),!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid base URL '${e}'`);a=t+a}const o=this,c=new Ce;this.xhr.push(c),c.open("POST",a,!0),c.setRequestHeader("X-Tinode-APIKey",this._apiKey),this._authToken&&c.setRequestHeader("X-Tinode-Auth",`Token ${this._authToken.token}`);let h=null,l=null;const d=new Promise(((e,t)=>{h=e,l=t}));c.upload.onprogress=e=>{e.lengthComputable&&(i&&i(e.loaded/e.total),this.onProgress&&this.onProgress(e.loaded/e.total))},c.onload=function(){let e;try{e=JSON.parse(this.response,_)}catch(t){o._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(h&&h(e.ctrl.params.url),n&&n(e.ctrl)):this.status>=400?(l&&l(new m(e.ctrl.text,e.ctrl.code)),r&&r(e.ctrl)):o._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},c.onerror=function(e){l&&l(e||new Error("failed")),r&&r(null)},c.onabort=function(e){l&&l(new Error("upload cancelled by user")),r&&r(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._tinode.getNextUniqueId()),s&&e.set("topic",s),c.send(e)}catch(e){l&&l(e),r&&r(null)}return d}upload(e,t,s,i,n){const r=(this._tinode._secure?"https://":"http://")+this._tinode._host;return this.uploadWithBaseUrl(r,e,t,s,i,n)}download(e,t,s,i,n){if(!b(e))return void(n&&n(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(n&&n("Must authenticate first"));const r=this,a=new Ce;this.xhr.push(a),a.open("GET",e,!0),a.setRequestHeader("X-Tinode-APIKey",this._apiKey),a.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),a.responseType="blob",a.onprogress=function(e){i&&i(e.loaded)};let o=null,c=null;const h=new Promise(((e,t)=>{o=e,c=t}));a.onload=function(){if(200==this.status){const e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:s})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),o&&o()}else if(this.status>=400&&c){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,_);c(new m(e.ctrl.text,e.ctrl.code))}catch(e){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),c(e)}},e.readAsText(this.response)}},a.onerror=function(e){c&&c(new Error("failed")),n&&n(e)},a.onabort=function(){c&&c(null)};try{a.send()}catch(e){c&&c(e),n&&n(e)}return h}cancel(){this.xhr.forEach((e=>{e.readyState<4&&e.abort()}))}static setNetworkProvider(e){Ce=e}}function Ue(e,t){!function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.add(e)}function Ie(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}var Oe=new WeakSet,je=new WeakSet;class Le{constructor(e){Ue(this,je),Ue(this,Oe),this.topic=e,this.what={}}withData(e,t,s){return this.what.data={since:e,before:t,limit:s},this}withLaterData(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)}withEarlierData(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)}withDesc(e){return this.what.desc={ims:e},this}withLaterDesc(){return this.withDesc(Ie(this,Oe,We).call(this))}withSub(e,t,s){const i={ims:e,limit:t};return"me"==this.topic.getType()?i.topic=s:i.user=s,this.what.sub=i,this}withOneSub(e,t){return this.withSub(e,void 0,t)}withLaterOneSub(e){return this.withOneSub(this.topic._lastSubsUpdate,e)}withLaterSub(e){return this.withSub(Ie(this,je,Ve).call(this),e)}withTags(){return this.what.tags=!0,this}withCred(){return"me"==this.topic.getType()?this.what.cred=!0:this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds",this.topic.getType()),this}withDel(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this}withLaterDel(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)}extract(e){return this.what[e]}build(){const e=[];let t={};return["data","sub","desc","tags","cred","del"].forEach((s=>{this.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(this.what[s]).length>0&&(t[s]=this.what[s]))})),e.length>0?t.what=e.join(" "):t=void 0,t}}function We(){return this.topic.updated}function Ve(){return this.topic.isP2PType()?Ie(this,Oe,We).call(this):this.topic._lastSubsUpdate}function ze(e,t){Be(e,t),t.add(e)}function Ge(e,t,s){Be(e,t),t.set(e,s)}function Be(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Fe(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function Ke(e,t){return function(e,t){return t.get?t.get.call(e):t.value}(e,Qe(e,t,"get"))}function He(e,t,s){return function(e,t,s){if(t.set)t.set.call(e,s);else{if(!t.writable)throw new TypeError("attempted to set read only private field");t.value=s}}(e,Qe(e,t,"set"),s),s}function Qe(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}var Xe=new WeakMap,$e=new WeakMap,Je=new WeakSet,Ze=new WeakSet;class Ye{constructor(e,t){ze(this,Ze),ze(this,Je),Ge(this,Xe,{writable:!0,value:void 0}),Ge(this,$e,{writable:!0,value:!1}),function(e,t,s){(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s}(this,"buffer",[]),He(this,Xe,e||((e,t)=>e===t?0:ee?this.buffer[this.buffer.length-1-e]:void 0}put(){let e;e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;for(let t in e)Fe(this,Ze,tt).call(this,e[t],this.buffer)}delAt(e){e|=0;let t=this.buffer.splice(e,1);if(t&&t.length>0)return t[0]}delRange(e,t){return this.buffer.splice(e,t-e)}length(){return this.buffer.length}reset(){this.buffer=[]}forEach(e,t,s,i){t|=0,s=s||this.buffer.length;for(let n=t;nt?this.buffer[n-1]:void 0,n0)){o=!0;break}n=r-1}return o?{idx:r,exact:!0}:s?{idx:-1}:{idx:a<0?r+1:r}}function tt(e,t){const s=Fe(this,Je,et).call(this,e,t,!1),i=s.exact&&Ke(this,$e)?1:0;return t.splice(s.idx,i,e),t}function st(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}class it{constructor(e,s){this._tinode=null,this.name=e,this.created=null,this.updated=null,this.touched=new Date(0),this.acs=new t(null),this.private=null,this.public=null,this.trusted=null,this._users={},this._queuedSeqId=u,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._recvNotificationTimer=null,this._tags=[],this._credentials=[],this._messageVersions={},this._messages=new Ye(((e,t)=>e.seq-t.seq),!0),this._attached=!1,this._lastSubsUpdate=new Date(0),this._new=!0,this._deleted=!1,this._delayedLeaveTimer=null,s&&(this.onData=s.onData,this.onMeta=s.onMeta,this.onPres=s.onPres,this.onInfo=s.onInfo,this.onMetaDesc=s.onMetaDesc,this.onMetaSub=s.onMetaSub,this.onSubsUpdated=s.onSubsUpdated,this.onTagsUpdated=s.onTagsUpdated,this.onCredsUpdated=s.onCredsUpdated,this.onDeleteTopic=s.onDeleteTopic,this.onAllMessagesReceived=s.onAllMessagesReceived)}static topicType(e){return{me:h,fnd:l,grp:d,new:d,nch:d,chn:d,usr:"p2p",sys:"sys"}["string"==typeof e?e.substring(0,3):"xxx"]}static isMeTopicName(e){return it.topicType(e)==h}static isGroupTopicName(e){return it.topicType(e)==d}static isP2PTopicName(e){return"p2p"==it.topicType(e)}static isCommTopicName(e){return it.isP2PTopicName(e)||it.isGroupTopicName(e)}static isNewGroupTopicName(e){return"string"==typeof e&&(e.substring(0,3)==o||e.substring(0,3)==c)}static isChannelTopicName(e){return"string"==typeof e&&("chn"==e.substring(0,3)||e.substring(0,3)==c)}isSubscribed(){return this._attached}subscribe(e,t){return clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=null,this._attached?Promise.resolve(this):this._deleted?Promise.reject(new Error("Conversation deleted")):this._tinode.subscribe(this.name||o,e,t).then((e=>{if(e.code>=300)return e;if(this._attached=!0,this._deleted=!1,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(delete this._new,this.name!=e.topic&&(this._cacheDelSelf(),this.name=e.topic),this._cachePutSelf(),this.created=e.ts,this.updated=e.ts,this.name!=h&&this.name!=l){const e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}t&&t.desc&&(t.desc._noForwarding=!0,this._processMetaDesc(t.desc))}return e}))}createMessage(e,t){return this._tinode.createMessage(this.name,e,t)}publish(e,t){return this.publishMessage(this.createMessage(e,t))}publishMessage(e){if(!this._attached)return Promise.reject(new Error("Cannot publish on inactive topic"));if(this._sending)return Promise.reject(new Error("The message is already being sent"));e._sending=!0,e._failed=!1;let t=null;return Ne().hasEntities(e.content)&&(t=[],Ne().entities(e.content,(e=>{e&&(e.ref&&t.push(e.ref),e.preref&&t.push(e.preref))})),0==t.length&&(t=null)),this._tinode.publishMessage(e,t).then((t=>(e._sending=!1,e.ts=t.ts,this.swapMessageId(e,t.params.seq),this._maybeUpdateMessageVersionsCache(e),this._routeData(e),t))).catch((t=>{this._tinode.logger("WARNING: Message rejected by the server",t),e._sending=!1,e._failed=!0,this.onData&&this.onData()}))}publishDraft(e,t){const s=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=s,e.ts=new Date,e.from=this._tinode.getCurrentUserID(),e.noecho=!0,this._messages.put(e),this._tinode._db.addMessage(e),this.onData&&this.onData(e)),(t||Promise.resolve()).then((t=>e._cancelled?{code:300,text:"cancelled"}:this.publishMessage(e))).catch((t=>{throw this._tinode.logger("WARNING: Message draft rejected",t),e._sending=!1,e._failed=!0,e._fatal=t instanceof m&&t.code>=400&&t.code<500,this.onData&&this.onData(),t}))}leave(e){return this._attached||e?this._tinode.leave(this.name,e).then((t=>(this._resetSub(),e&&this._gone(),t))):Promise.reject(new Error("Cannot leave inactive topic"))}leaveDelayed(e,t){clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=setTimeout((t=>{this._delayedLeaveTimer=null,this.leave(e)}),t)}getMeta(e){return this._tinode.getMeta(this.name,e)}getMessagesPage(e,t){let s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);return this._loadMessages(this._tinode._db,s.extract("data")).then((i=>{if(i==e)return Promise.resolve({topic:this.name,code:200,params:{count:i}});e-=i,s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);let n=this.getMeta(s.build());return t||(n=n.then((e=>{e&&e.params&&!e.params.count&&(this._noEarlierMsgs=!0)}))),n}))}setMeta(e){return e.tags&&(e.tags=function(e){let t=[];if(Array.isArray(e)){for(let s=0,i=e.length;s1&&t.push(i))}t.sort().filter((function(e,t,s){return!t||e!=s[t-1]}))}return 0==t.length&&t.push(f),t}(e.tags)),this._tinode.setMeta(this.name,e).then((t=>(t&&t.code>=300||(e.sub&&(e.sub.topic=this.name,t.params&&t.params.acs&&(e.sub.acs=t.params.acs,e.sub.updated=t.ts),e.sub.user||(e.sub.user=this._tinode.getCurrentUserID(),e.desc||(e.desc={})),e.sub._noForwarding=!0,this._processMetaSub([e.sub])),e.desc&&(t.params&&t.params.acs&&(e.desc.acs=t.params.acs,e.desc.updated=t.ts),this._processMetaDesc(e.desc)),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds([e.cred],!0)),t)))}updateMode(e,t){const s=e?this.subscriber(e):null,i=s?s.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:i}})}invite(e,t){return this.setMeta({sub:{user:e,mode:t}})}archive(e){return this.private&&!this.private.arch==!e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||f}}})}delMessages(e,t){if(!this._attached)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort(((e,t)=>e.low=t.hi)));let s,i=e.reduce(((e,t)=>(t.low0?this._tinode.delMessages(this.name,i,t):Promise.resolve({params:{del:0}}),s.then((t=>(t.params.del>this._maxDel&&(this._maxDel=t.params.del),e.forEach((e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low)})),this.onData&&this.onData(),t)))}delMessagesAll(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)}delMessagesList(e,t){e.sort(((e,t)=>e-t));let s=e.reduce(((e,t)=>{if(0==e.length)e.push({low:t});else{let s=e[e.length-1];!s.hi&&t!=s.low+1||t>s.hi?e.push({low:t}):s.hi=s.hi?Math.max(s.hi,t+1):t+1}return e}),[]);return this.delMessages(s,t)}delMessagesEdits(e,t){const s=[e];return this.messageVersions(e,(e=>s.push(e.seq))),this.delMessagesList(s,t)}delTopic(e){return this._deleted?(this._gone(),Promise.resolve(null)):this._tinode.delTopic(this.name,e).then((e=>(this._deleted=!0,this._resetSub(),this._gone(),e)))}delSubscription(e){return this._attached?this._tinode.delSubscription(this.name,e).then((t=>(delete this._users[e],this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users)),t))):Promise.reject(new Error("Cannot delete subscription in inactive topic"))}note(e,t){if(!this._attached)return;const s=this._users[this._tinode.getCurrentUserID()];let i=!1;s?(!s[e]||s[e]0&&this.note("read",e)}noteKeyPress(){this._attached?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")}noteRecording(e){this._attached?this._tinode.noteKeyPress(this.name,e?"kpa":"kpv"):this._tinode.logger("INFO: Cannot send notification in inactive topic")}videoCall(e,t,s){if(this._attached||["ringing","hang-up"].includes(e))return this._tinode.videoCall(this.name,t,e,s)}_updateReadRecv(e,t,s){let i,n=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":i=this.recv,this.recv=Math.max(this.recv,t),n=i!=this.recv;break;case"read":i=this.read,this.read=Math.max(this.read,t),n=i!=this.read;break;case"msg":i=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched{if(this._isReplacementMsg(e))return;const r=this.latestMsgVersion(e.seq)||e;r._origTs||(r._origTs=r.ts,r._origSeq=r.seq,r.ts=e.ts,r.seq=e.seq),t.push({data:r,idx:n})}),e,r,{}),t.forEach(((e,s)=>{n.call(i,e.data,s>0?t[s-1].data:void 0,s=0)return this._messages.getAt(t)}latestMessage(){return this._messages.getLast()}latestMsgVersion(e){const t=this._messageVersions[e];return t?t.getLast():null}maxMsgSeq(){return this._maxSeq}maxClearId(){return this._maxDel}messageCount(){return this._messages.length()}queuedMessages(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,u,void 0,t)}msgReceiptCount(e,t){let s=0;if(t>0){const i=this._tinode.getCurrentUserID();for(let n in this._users){const r=this._users[n];r.user!==i&&r[e]>=t&&s++}}return s}msgReadCount(e){return this.msgReceiptCount("read",e)}msgRecvCount(e){return this.msgReceiptCount("recv",e)}msgHasMoreMessages(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs}isNewMessage(e){return this._maxSeq<=e}flushMessage(e){const t=this._messages.find({seq:e});if(delete this._messageVersions[e],t>=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)}flushMessageRange(e,t){this._tinode._db.remMessages(this.name,e,t);for(let s=e;s=0?this._messages.delRange(s,this._messages.find({seq:t},!0)):[]}swapMessageId(e,t){const s=this._messages.find(e),i=this._messages.length();0<=s&&s=0){const s=this._messages.getAt(t),i=this.msgStatus(s);if(10==i||30==i||40==i)return this._tinode._db.remMessages(this.name,e),s._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1}getType(){return it.topicType(this.name)}getAccessMode(){return this.acs}setAccessMode(e){return this.acs=new t(e)}getDefaultAccess(){return this.defacs}startMetaQuery(){return new Le(this)}isArchived(){return this.private&&!!this.private.arch}isMeType(){return it.isMeTopicName(this.name)}isChannelType(){return it.isChannelTopicName(this.name)}isGroupType(){return it.isGroupTopicName(this.name)}isP2PType(){return it.isP2PTopicName(this.name)}isCommType(){return it.isCommTopicName(this.name)}msgStatus(e,t){let s=0;return this._tinode.isMe(e.from)?e._sending?s=20:e._fatal||e._cancelled?s=40:e._failed?s=30:e.seq>=u?s=10:this.msgReadCount(e.seq)>0?s=70:this.msgRecvCount(e.seq)>0?s=60:e.seq>0&&(s=50):s=80,t&&e._status!=s&&(e._status=s,this._tinode._db.updMessageStatus(this.name,e.seq,s)),s}_isReplacementMsg(e){return e.head&&e.head.replace}_maybeUpdateMessageVersionsCache(e){if(!this._isReplacementMsg(e))return void(this._messageVersions[e.seq]&&(this._messageVersions[e.seq].filter((t=>t.from==e.from)),this._messageVersions[e.seq].isEmpty()&&delete this._messageVersions[e.seq]));const t=parseInt(e.head.replace.split(":")[1]);if(t>e.seq)return;const s=this.findMessage(t);if(s&&s.from!=e.from)return;const i=this._messageVersions[t]||new Ye(((e,t)=>e.seq-t.seq),!0);i.put(e),this._messageVersions[t]=i}_routeData(e){e.content&&(!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq,this.msgStatus(e,!0),clearTimeout(this._recvNotificationTimer),this._recvNotificationTimer=setTimeout((e=>{this._recvNotificationTimer=null,this.noteRecv(this._maxSeq)}),100)),(e.seq0&&this._processMetaSub(e.sub),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds(e.cred),this.onMeta&&this.onMeta(e)}_routePres(e){let s,i;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":s=this._users[e.src],s?s.online="on"==e.what:this._tinode.logger("WARNING: Presence update for an unknown user",this.name,e.src);break;case"term":this._resetSub();break;case"upd":e.src&&!this._tinode.isTopicCached(e.src)&&this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":if(i=e.src||this._tinode.getCurrentUserID(),s=this._users[i],s)s.acs.updateAll(e.dacs),this._processMetaSub([{user:i,updated:new Date,acs:s.acs}]);else{const n=(new t).updateAll(e.dacs);n&&n.mode!=t._NONE&&(s=this._cacheGetUser(i),s?s.acs=n:(s={user:i,acs:n},this.getMeta(this.startMetaQuery().withOneSub(void 0,i).build())),s.updated=new Date,this._processMetaSub([s]))}break;default:this._tinode.logger("INFO: Ignored presence update",e.what)}this.onPres&&this.onPres(e)}_routeInfo(e){switch(e.what){case"recv":case"read":const t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv0&&this.onData&&this.onData()}_allMessagesReceived(e){this.onAllMessagesReceived&&this.onAllMessagesReceived(e)}_resetSub(){this._attached=!1}_gone(){this._messages.reset(),this._tinode._db.remMessages(this.name),this._users={},this.acs=new t(null),this.private=null,this.public=null,this.trusted=null,this._maxSeq=0,this._minSeq=0,this._attached=!1;const e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:h,src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()}_updateCachedUser(e,t){let s=this._cacheGetUser(e);return s=v(s||{},t),this._cachePutUser(e,s),y(this._users,e,s)}_getQueuedSeqId(){return this._queuedSeqId++}_loadMessages(e,t){const{since:s,before:i,limit:n}=t||{};return e.readMessages(this.name,{since:s,before:i,limit:n||24}).then((e=>(e.forEach((e=>{e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq{e.online&&(e.online=!1,e.seen=Object.assign(e.seen||{},{when:new Date}),this._refreshContact("off",e))})),this.onMetaDesc&&this.onMetaDesc(this)}_processMetaSub(e){let t=0;if(e.forEach((e=>{const s=e.topic;if(s==l||s==h)return;e.online=!!e.online;let i=null;if(e.deleted)i=e,this._tinode.cacheRemTopic(s),this._tinode._db.remTopic(s);else{void 0!==e.seq&&(e.seq=0|e.seq,e.recv=0|e.recv,e.read=0|e.read,e.unread=e.seq-e.read);const t=this._tinode.getTopic(s);t._new&&delete t._new,i=v(t,e),this._tinode._db.updTopic(i),it.isP2PTopicName(s)&&(this._cachePutUser(s,i),this._tinode._db.updUser(s,i.public)),!e._noForwarding&&t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(i)})),this.onSubsUpdated&&t>0){const s=[];e.forEach((e=>{s.push(e.topic)})),this.onSubsUpdated(s,t)}}_processMetaCreds(e,t){1==e.length&&e[0]==f&&(e=[]),t?e.forEach((e=>{if(e.val){let t=this._credentials.findIndex((t=>t.meth==e.meth&&t.val==e.val));t<0?(e.done||(t=this._credentials.findIndex((t=>t.meth==e.meth&&!t.done)),t>=0&&this._credentials.splice(t,1)),this._credentials.push(e)):this._credentials[t].done=e.done}else if(e.resp){const t=this._credentials.findIndex((t=>t.meth==e.meth&&!t.done));t>=0&&(this._credentials[t].done=!0)}})):this._credentials=e,this.onCredsUpdated&&this.onCredsUpdated(this._credentials)}_routePres(e){if("term"==e.what)return void this._resetSub();if("upd"==e.what&&e.src==h)return void this.getMeta(this.startMetaQuery().withDesc().build());const s=this._tinode.cacheGetTopic(e.src);if(s){switch(e.what){case"on":s.online=!0;break;case"off":s.online&&(s.online=!1,s.seen=Object.assign(s.seen||{},{when:new Date}));break;case"msg":s._updateReceived(e.seq,e.act);break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":s.acs?s.acs.updateAll(e.dacs):s.acs=(new t).updateAll(e.dacs),s.touched=new Date;break;case"ua":s.seen={when:new Date,ua:e.ua};break;case"recv":e.seq=0|e.seq,s.recv=s.recv?Math.max(s.recv,e.seq):e.seq;break;case"read":e.seq=0|e.seq,s.read=s.read?Math.max(s.read,e.seq):e.seq,s.recv=s.recv?Math.max(s.read,s.recv):s.recv,s.unread=s.seq-s.read;break;case"gone":s._deleted?this._tinode._db.remTopic(e.src):(s._deleted=!0,s._attached=!1,this._tinode._db.markTopicAsDeleted(e.src));break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",e.what)}this._refreshContact(e.what,s)}else if("acs"==e.what){const s=new t(e.dacs);if(!s||s.mode==t._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(s.mode==t._NONE)return void this._tinode.logger("WARNING: Removing non-existent subscription",e.src,e.dacs);{this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build());const t=this._tinode.getTopic(e.src);t.topic=e.src,t.online=!1,t.acs=s,this._tinode._db.updTopic(t)}}else"tags"==e.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(e)}_refreshContact(e,t){this.onContactUpdate&&this.onContactUpdate(e,t)}publish(){return Promise.reject(new Error("Publishing to 'me' is not supported"))}delCredential(e,t){return this._attached?this._tinode.delCredential(e,t).then((s=>{const i=this._credentials.findIndex((s=>s.meth==e&&s.val==t));return i>-1&&this._credentials.splice(i,1),this.onCredsUpdated&&this.onCredsUpdated(this._credentials),s})):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))}contacts(e,t,s){this._tinode.mapTopics(((i,n)=>{!i.isCommType()||t&&!t(i)||e.call(s,i,n)}))}getContact(e){return this._tinode.cacheGetTopic(e)}getAccessMode(e){if(e){const t=this._tinode.cacheGetTopic(e);return t?t.acs:null}return this.acs}isArchived(e){const t=this._tinode.cacheGetTopic(e);return t&&t.private&&!!t.private.arch}getCredentials(){return this._credentials}}class rt extends it{constructor(e){super(l,e),st(this,"_contacts",{})}_processMetaSub(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let s in e){let i=e[s];const n=i.topic?i.topic:i.user;i=y(this._contacts,n,i),t++,this.onMetaSub&&this.onMetaSub(i)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))}publish(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))}setMeta(e){return Object.getPrototypeOf(rt.prototype).setMeta.call(this,e).then((e=>{Object.keys(this._contacts).length>0&&(this._contacts={},this.onSubsUpdated&&this.onSubsUpdated([]))}))}contacts(e,t){const s=e||this.onMetaSub;if(s)for(let e in this._contacts)s.call(t,this._contacts[e],e,this._contacts)}}function at(e,t){!function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}(e,t),t.add(e)}function ot(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function ct(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let ht,lt,dt;function ut(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function pt(e,s){if(s instanceof Date)s=function(e){if(!w(e))return;const t=function(e,t){return"0".repeat((t=t||2)-(""+e).length)+e},s=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+(s?"."+t(s,3):"")+"Z"}(s);else if(s instanceof t)s=s.jsonHelper();else if(null==s||!1===s||Array.isArray(s)&&0==s.length||"object"==typeof s&&0==Object.keys(s).length)return;return s}function gt(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":pt(0,t)}"undefined"!=typeof WebSocket&&(ht=WebSocket),"undefined"!=typeof XMLHttpRequest&&(lt=XMLHttpRequest),"undefined"!=typeof indexedDB&&(dt=indexedDB),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(s.g.btoa=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s="";for(let i,n=0,r=0,a=e;t.charAt(0|r)||(a="=",r%1);s+=a.charAt(63&n>>8-r%1*8)){if(i=t.charCodeAt(r+=3/4),i>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");n=n<<8|i}return s}),"undefined"==typeof atob&&(s.g.atob=function(){let t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").replace(/=+$/,""),s="";if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let i,n=0,r=0,a=0;i=t.charAt(a++);~i&&(r=n%4?64*r+i:i,n++%4)?s+=String.fromCharCode(255&r>>(-2*n&6)):0)i=e.indexOf(i);return s}),"undefined"==typeof window&&(s.g.window={WebSocket:ht,XMLHttpRequest:lt,indexedDB:dt,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}}),te.setNetworkProviders(ht,lt),qe.setNetworkProvider(lt),Te.setDatabaseProvider(dt)}();var ft=new WeakSet,mt=new WeakSet,_t=new WeakSet,bt=new WeakSet,wt=new WeakSet,vt=new WeakSet,yt=new WeakSet,Mt=new WeakSet,St=new WeakSet,Tt=new WeakSet,Pt=new WeakSet,xt=new WeakSet,Et=new WeakSet,kt=new WeakSet;class At{constructor(e,t){if(at(this,kt),at(this,Et),at(this,xt),at(this,Pt),at(this,Tt),at(this,St),at(this,Mt),at(this,yt),at(this,vt),at(this,wt),at(this,bt),at(this,_t),at(this,mt),at(this,ft),ot(this,"_host",void 0),ot(this,"_secure",void 0),ot(this,"_appName",void 0),ot(this,"_apiKey",void 0),ot(this,"_browser",""),ot(this,"_platform",void 0),ot(this,"_hwos","undefined"),ot(this,"_humanLanguage","xx"),ot(this,"_loggingEnabled",!1),ot(this,"_trimLongStrings",!1),ot(this,"_myUID",null),ot(this,"_authenticated",!1),ot(this,"_login",null),ot(this,"_authToken",null),ot(this,"_inPacketCount",0),ot(this,"_messageId",Math.floor(65535*Math.random()+65535)),ot(this,"_serverInfo",null),ot(this,"_deviceToken",null),ot(this,"_pendingPromises",{}),ot(this,"_expirePromises",null),ot(this,"_connection",null),ot(this,"_persist",!1),ot(this,"_db",null),ot(this,"_cache",{}),ot(this,"onWebsocketOpen",void 0),ot(this,"onConnect",void 0),ot(this,"onDisconnect",void 0),ot(this,"onLogin",void 0),ot(this,"onCtrlMessage",void 0),ot(this,"onDataMessage",void 0),ot(this,"onPresMessage",void 0),ot(this,"onMessage",void 0),ot(this,"onRawMessage",void 0),ot(this,"onNetworkProbe",void 0),ot(this,"onAutoreconnectIteration",void 0),this._host=e.host,this._secure=e.secure,this._appName=e.appName||"Undefined",this._apiKey=e.apiKey,this._platform=e.platform||"web","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";let s,i="";/reactnative/i.test(t)&&(i="ReactNative; ");let n=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(n){const t=["edg","chrome","safari","mobile","version"];let i,r=e.substr(n.index+n[0].length).split(" "),a=[];for(let e=0;es[1].toLowerCase().startsWith(e)))]),"Version"==s[1]&&(i=s[2]))}a.sort(((e,t)=>e[2]-t[2])),a.length>0?(a[0][0].toLowerCase().startsWith("edg")?a[0][0]="Edge":"OPR"==a[0][0]?a[0][0]="Opera":"Safari"==a[0][0]&&i&&(a[0][1]=i),s=a[0][0]+"/"+a[0][1]):s=n[1]}else/firefox/i.test(e)?(n=/Firefox\/([.\d]+)/g.exec(e),s=n?"Firefox/"+n[1]:"Firefox/?"):(n=/([\w.]+)\/([.\d]+)/.exec(e),n?s=n[1]+"/"+n[2]:(n=e.split(" "),s=n[0]));if(n=s.split("/"),n.length>1){const e=n[1].split("."),t=e[1]?"."+e[1].substr(0,2):"";s=`${n[0]}/${e[0]}${t}`}return i+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),te.logger=this.logger,Ne().logger=this.logger,"lp"!=e.transport&&"ws"!=e.transport&&(e.transport=function(){if("object"==typeof window){if(window.WebSocket)return"ws";if(window.XMLHttpRequest)return"lp"}return null}()),this._connection=new te(e,"0",!0),this._connection.onMessage=e=>{ct(this,bt,Ct).call(this,e)},this._connection.onOpen=e=>ct(this,wt,qt).call(this),this._connection.onDisconnect=(e,t)=>ct(this,vt,Ut).call(this,e,t),this._connection.onAutoreconnectIteration=(e,t)=>{this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e,t)},this._persist=e.persist,this._db=new Te((e=>{this.logger("DB",e)}),this.logger),this._persist){const e=[];this._db.initDatabase().then((t=>this._db.mapTopics((t=>{let s=ct(this,Tt,Lt).call(this,"topic",t.name);s||(s=t.name==h?new nt:t.name==l?new rt:new it(t.name),this._db.deserializeTopic(s,t),ct(this,Et,zt).call(this,s),s._cachePutSelf(),delete s._new,e.push(s._loadMessages(this._db)))})))).then((e=>this._db.mapUsers((e=>{ct(this,St,jt).call(this,"user",e.uid,v({},e.public))})))).then((t=>Promise.all(e))).then((e=>{t&&t(),this.logger("Persistent cache initialized.")})).catch((e=>{t&&t(e),this.logger("Failed to initialize persistent cache:",e)}))}else this._db.deleteDatabase().then((e=>{t&&t()}))}logger(e){if(this._loggingEnabled){const n=new Date,r=("0"+n.getUTCHours()).slice(-2)+":"+("0"+n.getUTCMinutes()).slice(-2)+":"+("0"+n.getUTCSeconds()).slice(-2)+"."+("00"+n.getUTCMilliseconds()).slice(-3);for(var t=arguments.length,s=new Array(t>1?t-1:0),i=1;i0&&(r.extra={attachments:n.attachments.filter((e=>b(e)))})),ct(this,_t,Nt).call(this,r,r.acc.id)}createAccount(e,t,s,i){let n=this.account("new",e,t,s,i);return s&&(n=n.then((e=>ct(this,kt,Gt).call(this,e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",ut(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",ut(t+":"+s),!1,i)}hello(){const e=ct(this,Mt,Ot).call(this,"hi");return ct(this,_t,Nt).call(this,e,e.hi.id).then((e=>(this._connection.backoffReset(),e.params&&(this._serverInfo=e.params),this.onConnect&&this.onConnect(),e))).catch((e=>{this._connection.reconnect(!0),this.onDisconnect&&this.onDisconnect(e)}))}setDeviceToken(e){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(ct(this,_t,Nt).call(this,{hi:{dev:e||At.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=ct(this,Mt,Ot).call(this,"login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,ct(this,_t,Nt).call(this,i,i.login.id).then((e=>ct(this,kt,Gt).call(this,e)))}loginBasic(e,t,s){return this.login("basic",ut(e+":"+t),s).then((t=>(this._login=e,t)))}loginToken(e,t){return this.login("token",e,t)}requestResetAuthSecret(e,t,s){return this.login("reset",ut(e+":"+t+":"+s))}getAuthToken(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)}setAuthToken(e){this._authToken=e}subscribe(e,t,s){const i=ct(this,Mt,Ot).call(this,"sub",e);if(e||(e=o),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;At.isNewGroupTopicName(e)?i.sub.set.desc=t:At.isP2PTopicName(e)&&t.defacs&&(i.sub.set.desc={defacs:t.defacs})}Array.isArray(s.attachments)&&s.attachments.length>0&&(i.extra={attachments:s.attachments.filter((e=>b(e)))}),s.tags&&(i.sub.set.tags=s.tags)}return ct(this,_t,Nt).call(this,i,i.sub.id)}leave(e,t){const s=ct(this,Mt,Ot).call(this,"leave",e);return s.leave.unsub=t,ct(this,_t,Nt).call(this,s,s.leave.id)}createMessage(e,t,s){const i=ct(this,Mt,Ot).call(this,"pub",e);let n="string"==typeof t?Ne().parse(t):t;return n&&!Ne().isPlainText(n)&&(i.pub.head={mime:Ne().getContentType()},t=n),i.pub.noecho=s,i.pub.content=t,i.pub}publish(e,t,s){return this.publishMessage(this.createMessage(e,t,s))}publishMessage(e,t){(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0;const s={pub:e};return t&&(s.extra={attachments:t.filter((e=>b(e)))}),ct(this,_t,Nt).call(this,s,e.id)}oobNotification(e){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(e,gt):e)),e.what){case"msg":if(!e.seq||e.seq<1||!e.topic)break;if(!this.isConnected())break;const s=ct(this,Tt,Lt).call(this,"topic",e.topic);if(!s)break;if(s.isSubscribed())break;s.maxMsgSeq(){this.logger("Failed to get the name of a new sender",e)})),s.subscribe(null).then((e=>s.getMeta(new Le(s).withLaterData(24).withLaterDel(24).build()))).then((e=>{s.leaveDelayed(!1,1e3)})).catch((e=>{this.logger("On push data fetch failed",e)})).finally((e=>{this.getMeTopic()._refreshContact("msg",s)})));break;case"read":this.getMeTopic()._routePres({what:"read",seq:e.seq});break;case"sub":if(!this.isMe(e.xfrom))break;const i={given:e.modeGiven,want:e.modeWant},n=new t(i),r=n.mode&&n.mode!=t._NONE?{what:"acs",src:e.topic,dacs:i}:{what:"gone",src:e.topic};this.getMeTopic()._routePres(r);break;default:this.logger("Unknown push type ignored",e.what)}}getMeta(e,t){const s=ct(this,Mt,Ot).call(this,"get",e);return s.get=v(s.get,t),ct(this,_t,Nt).call(this,s,s.get.id)}setMeta(e,t){const s=ct(this,Mt,Ot).call(this,"set",e),i=[];return t&&(["desc","sub","tags","cred","ephemeral"].forEach((function(e){t.hasOwnProperty(e)&&(i.push(e),s.set[e]=t[e])})),Array.isArray(t.attachments)&&t.attachments.length>0&&(s.extra={attachments:t.attachments.filter((e=>b(e)))})),0==i.length?Promise.reject(new Error("Invalid {set} parameters")):ct(this,_t,Nt).call(this,s,s.set.id)}delMessages(e,t,s){const i=ct(this,Mt,Ot).call(this,"del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,ct(this,_t,Nt).call(this,i,i.del.id)}delTopic(e,t){const s=ct(this,Mt,Ot).call(this,"del",e);return s.del.what="topic",s.del.hard=t,ct(this,_t,Nt).call(this,s,s.del.id)}delSubscription(e,t){const s=ct(this,Mt,Ot).call(this,"del",e);return s.del.what="sub",s.del.user=t,ct(this,_t,Nt).call(this,s,s.del.id)}delCredential(e,t){const s=ct(this,Mt,Ot).call(this,"del",h);return s.del.what="cred",s.del.cred={meth:e,val:t},ct(this,_t,Nt).call(this,s,s.del.id)}delCurrentUser(e){const t=ct(this,Mt,Ot).call(this,"del",null);return t.del.what="user",t.del.hard=e,ct(this,_t,Nt).call(this,t,t.del.id).then((e=>{this._myUID=null}))}note(e,t,s){if(s<=0||s>=u)throw new Error(`Invalid message id ${s}`);const i=ct(this,Mt,Ot).call(this,"note",e);i.note.what=t,i.note.seq=s,ct(this,_t,Nt).call(this,i)}noteKeyPress(e,t){const s=ct(this,Mt,Ot).call(this,"note",e);s.note.what=t||"kp",ct(this,_t,Nt).call(this,s)}videoCall(e,t,s,i){const n=ct(this,Mt,Ot).call(this,"note",e);n.note.seq=t,n.note.what="call",n.note.event=s,n.note.payload=i,ct(this,_t,Nt).call(this,n,n.note.id)}getTopic(e){let t=ct(this,Tt,Lt).call(this,"topic",e);return!t&&e&&(t=e==h?new nt:e==l?new rt:new it(e),ct(this,Et,zt).call(this,t),t._cachePutSelf()),t}cacheGetTopic(e){return ct(this,Tt,Lt).call(this,"topic",e)}cacheRemTopic(e){ct(this,Pt,Wt).call(this,"topic",e)}mapTopics(e,t){ct(this,xt,Vt).call(this,"topic",e,t)}isTopicCached(e){return!!ct(this,Tt,Lt).call(this,"topic",e)}newGroupTopicName(e){return(e?c:o)+this.getNextUniqueId()}getMeTopic(){return this.getTopic(h)}getFndTopic(){return this.getTopic(l)}getLargeFileHelper(){return new qe(this,"0")}getCurrentUserID(){return this._myUID}isMe(e){return this._myUID===e}getCurrentLogin(){return this._login}getServerInfo(){return this._serverInfo}report(e,t){return this.publish("sys",Ne().attachJSON(null,{action:e,target:t}))}getServerParam(e,t){return this._serverInfo&&this._serverInfo[e]||t}enableLogging(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t}setHumanLanguage(e){e&&(this._humanLanguage=e)}isTopicOnline(e){const t=ct(this,Tt,Lt).call(this,"topic",e);return t&&t.online}getTopicAccessMode(e){const t=ct(this,Tt,Lt).call(this,"topic",e);return t?t.acs:null}wantAkn(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0}}function Dt(e){let t=null;return e&&(t=new Promise(((t,s)=>{this._pendingPromises[e]={resolve:t,reject:s,ts:new Date}}))),t}function Rt(e,t,s,i){const n=this._pendingPromises[e];n&&(delete this._pendingPromises[e],t>=200&&t<400?n.resolve&&n.resolve(s):n.reject&&n.reject(new m(i,t)))}function Nt(e,t){let s;t&&(s=ct(this,ft,Dt).call(this,t)),e=M(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,gt):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;ct(this,mt,Rt).call(this,t,te.NETWORK_ERROR,null,e.message)}return s}function Ct(e){if(!e)return;if(this._inPacketCount++,this.onRawMessage&&this.onRawMessage(e),"0"===e)return void(this.onNetworkProbe&&this.onNetworkProbe());let t=JSON.parse(e,_);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,gt):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&ct(this,mt,Rt).call(this,t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout((e=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=ct(this,Tt,Lt).call(this,"topic",t.ctrl.topic);e&&(e._resetSub(),t.ctrl.params&&t.ctrl.params.unsub&&e._gone())}else if(t.ctrl.code<300&&t.ctrl.params)if("data"==t.ctrl.params.what){const e=ct(this,Tt,Lt).call(this,"topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=ct(this,Tt,Lt).call(this,"topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((e=>{if(t.meta){const e=ct(this,Tt,Lt).call(this,"topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&ct(this,mt,Rt).call(this,t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=ct(this,Tt,Lt).call(this,"topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=ct(this,Tt,Lt).call(this,"topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=ct(this,Tt,Lt).call(this,"topic",t.info.topic);e&&e._routeInfo(t.info),this.onInfoMessage&&this.onInfoMessage(t.info)}else this.logger("ERROR: Unknown packet received.")}),0)):(this.logger("in: "+e),this.logger("ERROR: failed to parse data"))}function qt(){this._expirePromises||(this._expirePromises=setInterval((e=>{const t=new m("timeout",504),s=new Date((new Date).getTime()-p);for(let e in this._pendingPromises){let i=this._pendingPromises[e];i&&i.ts{e._resetSub()}));for(let t in this._pendingPromises){const s=this._pendingPromises[t];s&&s.reject&&s.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}function It(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+a}function Ot(e,t){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:r,ua:ct(this,yt,It).call(this),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:t,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:t,desc:{},sub:{},tags:[],ephemeral:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw new Error(`Unknown packet type requested: ${e}`)}}function jt(e,t,s){this._cache[e+":"+t]=s}function Lt(e,t){return this._cache[e+":"+t]}function Wt(e,t){delete this._cache[e+":"+t]}function Vt(e,t,s){const i=e?e+":":void 0;for(let e in this._cache)if((!i||0==e.indexOf(i))&&t.call(s,this._cache[e],e))break}function zt(e){e._tinode=this,e._cacheGetUser=e=>{const t=ct(this,Tt,Lt).call(this,"user",e);if(t)return{user:e,public:v({},t)}},e._cachePutUser=(e,t)=>{ct(this,St,jt).call(this,"user",e,v({},t.public))},e._cacheDelUser=e=>{ct(this,Pt,Wt).call(this,"user",e)},e._cachePutSelf=t=>{ct(this,St,jt).call(this,"topic",e.name,e)},e._cacheDelSelf=t=>{ct(this,Pt,Wt).call(this,"topic",e.name)}}function Gt(e){return e.params&&e.params.user?(this._myUID=e.params.user,this._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?this._authToken={token:e.params.token,expires:e.params.expires}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text),e):e}At.MESSAGE_STATUS_NONE=0,At.MESSAGE_STATUS_QUEUED=10,At.MESSAGE_STATUS_SENDING=20,At.MESSAGE_STATUS_FAILED=30,At.MESSAGE_STATUS_FATAL=40,At.MESSAGE_STATUS_SENT=50,At.MESSAGE_STATUS_RECEIVED=60,At.MESSAGE_STATUS_READ=70,At.MESSAGE_STATUS_TO_ME=80,At.DEL_CHAR=f,At.MAX_MESSAGE_SIZE="maxMessageSize",At.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",At.MAX_TAG_COUNT="maxTagCount",At.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",At.REQ_CRED_VALIDATORS="reqCred"})(),i})()));
\ No newline at end of file
diff --git a/umd/tinode.prod.js.map b/umd/tinode.prod.js.map
index f7102b5d..020728ea 100644
--- a/umd/tinode.prod.js.map
+++ b/umd/tinode.prod.js.map
@@ -1 +1 @@
-{"version":3,"file":"tinode.prod.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,GAClB,CATD,CASGK,MAAM,I,kCCmDT,MAEMC,EAAwB,GACxBC,EAAiB,mBAEjBC,EAAqB,CAAC,MAAO,SAAU,WAAY,WAAY,OAAQ,OAAQ,UAAW,SAAU,UACxG,MAAO,OAAQ,QAAS,MAAO,MAAO,SAKlCC,EAAgB,CAEpB,CACEC,KAAM,KACNC,MAAO,wBACPC,IAAK,yBAGP,CACEF,KAAM,KACNC,MAAO,oBACPC,IAAK,qBAGP,CACEF,KAAM,KACNC,MAAO,uBACPC,IAAK,wBAGP,CACEF,KAAM,KACNC,MAAO,kBACPC,IAAK,oBAKHC,EAAa,CAAC,MAGdC,EAAe,CAEnB,CACEJ,KAAM,KACNK,SAAU,MACVC,KAAM,SAASC,GAKb,MAHK,gBAAgBC,KAAKD,KACxBA,EAAM,UAAYA,GAEb,C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mB,iBAC1B5H,GAAO6H,qBAAuB,qBAC9B7H,GAAO8H,cAAgB,cACvB9H,GAAO+H,qBAAuB,oBAC9B/H,GAAOgI,oBAAsB,S","sources":["webpack://tinode/webpack/universalModuleDefinition","webpack://tinode/./src/drafty.js","webpack://tinode/webpack/bootstrap","webpack://tinode/webpack/runtime/compat get default export","webpack://tinode/webpack/runtime/define property getters","webpack://tinode/webpack/runtime/global","webpack://tinode/webpack/runtime/hasOwnProperty shorthand","webpack://tinode/webpack/runtime/make namespace object","webpack://tinode/./src/access-mode.js","webpack://tinode/./version.js","webpack://tinode/./src/config.js","webpack://tinode/./src/comm-error.js","webpack://tinode/./src/utils.js","webpack://tinode/./src/connection.js","webpack://tinode/./src/db.js","webpack://tinode/./src/large-file.js","webpack://tinode/./src/meta-builder.js","webpack://tinode/./src/cbuffer.js","webpack://tinode/./src/topic.js","webpack://tinode/./src/tinode.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"tinode\"] = factory();\n\telse\n\t\troot[\"tinode\"] = factory();\n})(this, () => {\nreturn ","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * Supports conversion of user keyboard input to formatted text:
\n * \n * - *abc* → abc
\n * - _abc_ → abc
\n * - ~abc~ →
abc \n * - `abc` → abc
\n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * \n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '
';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '',\n close: _ => ''\n },\n // Row: logic grouping of elements\n RW: {\n open: _ => '',\n close: _ => ''\n },\n // Quoted block.\n QQ: {\n open: _ => '',\n close: _ => '',\n props: (data) => {\n return data ? {} : null;\n },\n },\n // Video call\n VC: {\n open: _ => '',\n close: _ => '',\n props: data => {\n if (!data) return {};\n return {\n 'data-duration': data.duration,\n 'data-state': data.state,\n };\n }\n },\n // Video.\n VD: {\n open: data => {\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = data.ref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * @typedef Drafty.ImageDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the image, e.g. \"image/png\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded image content. Could be null/undefined.\n * @param {string} preview - base64-encoded thumbnail of the image.\n * @param {integer} width - width of the image.\n * @param {integer} height - height of the image.\n * @param {string} filename - file name suggestion for downloading the image.\n * @param {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.VideoDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @param {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @param {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @param {integer} width - width of the video.\n * @param {integer} height - height of the video.\n * @param {integer} duration - duration of the video.\n * @param {string} filename - file name suggestion for downloading the video.\n * @param {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @param {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.AudioDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded audio content. Could be null/undefined.\n * @param {integer} duration - duration of the record in milliseconds.\n * @param {string} preview - base64 encoded short array of amplitude values 0..100.\n * @param {string} filename - file name suggestion for downloading the audio.\n * @param {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * @typedef Drafty.AttachmentDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @param {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @param {string} filename - file name suggestion for downloading the attachment.\n * @param {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @param {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @file Access control model.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\n/**\n * Helper class for handling access mode.\n *\n * @class AccessMode\n * @memberof Tinode\n *\n * @param {AccessMode|Object=} acs - AccessMode to copy or access mode object received from the server.\n */\nexport default class AccessMode {\n constructor(acs) {\n if (acs) {\n this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);\n this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);\n this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :\n (this.given & this.want);\n }\n }\n\n static #checkFlag(val, side, flag) {\n side = side || 'mode';\n if (['given', 'want', 'mode'].includes(side)) {\n return ((val[side] & flag) != 0);\n }\n throw new Error(`Invalid AccessMode component '${side}'`);\n }\n /**\n * Parse string into an access mode value.\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {string | Number} mode - either a String representation of the access mode to parse or a set of bits to assign.\n * @returns {number} - Access mode as a numeric value.\n */\n static decode(str) {\n if (!str) {\n return null;\n } else if (typeof str == 'number') {\n return str & AccessMode._BITMASK;\n } else if (str === 'N' || str === 'n') {\n return AccessMode._NONE;\n }\n\n const bitmask = {\n 'J': AccessMode._JOIN,\n 'R': AccessMode._READ,\n 'W': AccessMode._WRITE,\n 'P': AccessMode._PRES,\n 'A': AccessMode._APPROVE,\n 'S': AccessMode._SHARE,\n 'D': AccessMode._DELETE,\n 'O': AccessMode._OWNER\n };\n\n let m0 = AccessMode._NONE;\n\n for (let i = 0; i < str.length; i++) {\n const bit = bitmask[str.charAt(i).toUpperCase()];\n if (!bit) {\n // Unrecognized bit, skip.\n continue;\n }\n m0 |= bit;\n }\n return m0;\n }\n /**\n * Convert numeric representation of the access mode into a string.\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to convert to a string.\n * @returns {string} - Access mode as a string.\n */\n static encode(val) {\n if (val === null || val === AccessMode._INVALID) {\n return null;\n } else if (val === AccessMode._NONE) {\n return 'N';\n }\n\n const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];\n let res = '';\n for (let i = 0; i < bitmask.length; i++) {\n if ((val & (1 << i)) != 0) {\n res = res + bitmask[i];\n }\n }\n return res;\n }\n /**\n * Update numeric representation of access mode with the new value. The value\n * is one of the following:\n * - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","export const PACKAGE_VERSION = \"0.21.0\";\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter(function(item, pos, ary) {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst DB_VERSION = 1;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = (event) => {\n resolve(event.target.result);\n };\n trx.onerror = (event) => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {Object} query - parameters of the message range to retrieve.\n * @param {number=} query.since - the least message ID to retrieve (inclusive).\n * @param {number=} query.before - the greatest message ID to retrieve (exclusive).\n * @param {number=} query.limit - the maximum number of messages to retrieve.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n const result = [];\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n const trx = this.db.transaction(['message']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev').onsuccess = (event) => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Private methods.\n\n // Serializable topic fields.\n static #topic_fields = ['created', 'updated', 'deleted', 'read', 'recv', 'seq', 'clear', 'defacs',\n 'creds', 'public', 'trusted', 'private', 'touched', '_deleted'\n ];\n\n // Copy data from src to Topic object.\n static #deserializeTopic(topic, src) {\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n topic[f] = src[f];\n }\n });\n if (Array.isArray(src.tags)) {\n topic._tags = src.tags;\n }\n if (src.acs) {\n topic.setAccessMode(src.acs);\n }\n topic.seq |= 0;\n topic.read |= 0;\n topic.unread = Math.max(0, topic.seq - topic.read);\n }\n\n // Copy values from 'src' to 'dst'. Allocate dst if it's null or undefined.\n static #serializeTopic(dst, src) {\n const res = dst || {\n name: src.name\n };\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n res[f] = src[f];\n }\n });\n if (Array.isArray(src._tags)) {\n res.tags = src._tags;\n }\n if (src.acs) {\n res.acs = src.getAccessMode().jsonHelper();\n }\n return res;\n }\n\n static #serializeSubscription(dst, topicName, uid, sub) {\n const fields = ['updated', 'mode', 'read', 'recv', 'clear', 'lastSeen', 'userAgent'];\n const res = dst || {\n topic: topicName,\n uid: uid\n };\n\n fields.forEach((f) => {\n if (sub.hasOwnProperty(f)) {\n res[f] = sub[f];\n }\n });\n\n return res;\n }\n\n static #serializeMessage(dst, msg) {\n // Serializable fields.\n const fields = ['topic', 'seq', 'ts', '_status', 'from', 'head', 'content'];\n const res = dst || {};\n fields.forEach((f) => {\n if (msg.hasOwnProperty(f)) {\n res[f] = msg[f];\n }\n });\n return res;\n }\n\n /**\n * To use DB in a non browser context, supply indexedDB provider.\n * @static\n * @memberof DB\n * @param idbProvider indexedDB provider, e.g. for node require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Add new element(s) to the buffer. Variadic: takes one or more arguments. If an array is passed as a single\n * argument, its elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive).\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive).\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = startIdx | 0;\n beforeIdx = beforeIdx || this.buffer.length;\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n mergeObj,\n mergeToCache,\n normalizeArray\n} from './utils.js';\n\nexport class Topic {\n /**\n * @callback Tinode.Topic.onData\n * @param {Data} data - Data packet\n */\n /**\n * Topic is a class representing a logical communication channel.\n * @class Topic\n * @memberof Tinode\n *\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {Tinode.Topic.onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic is subscribed.\n * @memberof Tinode.Topic#\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data && data.ref) {\n attachments.push(data.ref);\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {boolean} forward if true, request newer messages.\n */\n getMessagesPage(limit, forward) {\n let query = forward ?\n this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n\n // First try fetching from DB, then from the server.\n return this._loadMessages(this._tinode._db, query.extract('data'))\n .then((count) => {\n if (count == limit) {\n // Got enough messages from local cache.\n return Promise.resolve({\n topic: this.name,\n code: 200,\n params: {\n count: count\n }\n });\n }\n\n // Reduce the count of requested messages.\n limit -= count;\n // Update query with new values loaded from DB.\n query = forward ? this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n let promise = this.getMeta(query.build());\n if (!forward) {\n promise = promise.then(ctrl => {\n if (ctrl && ctrl.params && !ctrl.params.count) {\n this._noEarlierMsgs = true;\n }\n });\n }\n return promise;\n });\n }\n /**\n * Update topic metadata.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n if (params.tags) {\n params.tags = normalizeArray(params.tags);\n }\n // Send Set message, handle async response.\n return this._tinode.setMeta(this.name, params)\n .then(ctrl => {\n if (ctrl && ctrl.code >= 300) {\n // Not modified\n return ctrl;\n }\n\n if (params.sub) {\n params.sub.topic = this.name;\n if (ctrl.params && ctrl.params.acs) {\n params.sub.acs = ctrl.params.acs;\n params.sub.updated = ctrl.ts;\n }\n if (!params.sub.user) {\n // This is a subscription update of the current user.\n // Assign user ID otherwise the update will be ignored by _processMetaSub.\n params.sub.user = this._tinode.getCurrentUserID();\n if (!params.desc) {\n // Force update to topic's asc.\n params.desc = {};\n }\n }\n params.sub._noForwarding = true;\n this._processMetaSub([params.sub]);\n }\n\n if (params.desc) {\n if (ctrl.params && ctrl.params.acs) {\n params.desc.acs = ctrl.params.acs;\n params.desc.updated = ctrl.ts;\n }\n this._processMetaDesc(params.desc);\n }\n\n if (params.tags) {\n this._processMetaTags(params.tags);\n }\n if (params.cred) {\n this._processMetaCreds([params.cred], true);\n }\n\n return ctrl;\n });\n }\n /**\n * Update access mode of the current user or of another topic subsriber.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - UID of the user to update or null to update current user.\n * @param {string} update - the update value, full or delta.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n updateMode(uid, update) {\n const user = uid ? this.subscriber(uid) : null;\n const am = user ?\n user.acs.updateGiven(update).getGiven() :\n this.getAccessMode().updateWant(update).getWant();\n\n return this.setMeta({\n sub: {\n user: uid,\n mode: am\n }\n });\n }\n /**\n * Create new topic subscription. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to invite\n * @param {string=} mode - Access mode. null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.DelRange[]} ranges - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessages(ranges, hard) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete messages in inactive topic\"));\n }\n\n // Sort ranges in accending order by low, the descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n let tosend = ranges.reduce((out, r) => {\n if (r.low < Const.LOCAL_SEQID) {\n if (!r.hi || r.hi < Const.LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: this._maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n\n // Send {del} message, return promise\n let result;\n if (tosend.length > 0) {\n result = this._tinode.delMessages(this.name, tosend, hard);\n } else {\n result = Promise.resolve({\n params: {\n del: 0\n }\n });\n }\n // Update local cache.\n return result.then(ctrl => {\n if (ctrl.params.del > this._maxDel) {\n this._maxDel = ctrl.params.del;\n }\n\n ranges.forEach((r) => {\n if (r.hi) {\n this.flushMessageRange(r.low, r.hi);\n } else {\n this.flushMessage(r.low);\n }\n });\n\n if (this.onData) {\n // Calling with no parameters to indicate the messages were deleted.\n this.onData();\n }\n return ctrl;\n });\n }\n /**\n * Delete all messages. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesAll(hardDel) {\n if (!this._maxSeq || this._maxSeq <= 0) {\n // There are no messages to delete.\n return Promise.resolve();\n }\n return this.delMessages([{\n low: 1,\n hi: this._maxSeq + 1,\n _all: true\n }], hardDel);\n }\n\n /**\n * Delete multiple messages defined by their IDs. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {Array.} list - list of seq IDs to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesList(list, hardDel) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n let ranges = list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n // Send {del} message, return promise\n return this.delMessages(ranges, hardDel);\n }\n\n /**\n * Delete original message and edited variants. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delMessagesEdits(seq, hardDel) {\n const list = [seq];\n this.messageVersions(seq, msg => list.push(msg.seq));\n // Send {del} message, return promise\n return this.delMessagesList(list, hardDel);\n }\n\n /**\n * Delete topic. Requires Owner permission. Wrapper for {@link Tinode#delTopic}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hard - had-delete topic.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delTopic(hard) {\n if (this._deleted) {\n // The topic is already deleted at the server, just remove from DB.\n this._gone();\n return Promise.resolve(null);\n }\n\n return this._tinode.delTopic(this.name, hard).then(ctrl => {\n this._deleted = true;\n this._resetSub();\n this._gone();\n return ctrl;\n });\n }\n /**\n * Delete subscription. Requires Share permission. Wrapper for {@link Tinode#delSubscription}.\n * @memberof Tinode.Topic#\n *\n * @param {string} user - ID of the user to remove subscription for.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delSubscription(user) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete subscription in inactive topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delSubscription(this.name, user).then(ctrl => {\n // Remove the object from the subscription cache;\n delete this._users[user];\n // Notify listeners\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n return ctrl;\n });\n }\n /**\n * Send a read/recv notification.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what notification to send: recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.} a copy of tags\n */\n tags() {\n // Return a copy.\n return this._tags.slice(0);\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (this._isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by seq.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} newer - if true, check for newer messages only.\n */\n msgHasMoreMessages(newer) {\n return newer ? this.seq > this._maxSeq :\n // _minSeq could be more than 1, but earlier messages could have been deleted.\n (this._minSeq > 1 && !this._noEarlierMsgs);\n }\n /**\n * Check if the given seq Id is id of the most recent message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to check\n */\n isNewMessage(seqId) {\n return this._maxSeq <= seqId;\n }\n /**\n * Remove one message from local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to remove from cache.\n * @returns {Message} removed message or undefined if such message was not found.\n */\n flushMessage(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n delete this._messageVersions[seqId];\n if (idx >= 0) {\n this._tinode._db.remMessages(this.name, seqId);\n return this._messages.delAt(idx);\n }\n return undefined;\n }\n /**\n * Remove a range of messages from the local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} fromId seq ID of the first message to remove (inclusive).\n * @param {number} untilId seqID of the last message to remove (exclusive).\n *\n * @returns {Message[]} array of removed messages (could be empty).\n */\n flushMessageRange(fromId, untilId) {\n // Remove range from persistent cache.\n this._tinode._db.remMessages(this.name, fromId, untilId);\n\n // Remove all versions keyed by IDs in the range.\n for (let i = fromId; i < untilId; i++) {\n delete this._messageVersions[i];\n }\n\n // start, end: find insertion points (nearest == true).\n const since = this._messages.find({\n seq: fromId\n }, true);\n return since >= 0 ? this._messages.delRange(since, this._messages.find({\n seq: untilId\n }, true)) : [];\n }\n /**\n * Update message's seqId.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub message object.\n * @param {number} newSeqId new seq id for pub.\n */\n swapMessageId(pub, newSeqId) {\n const idx = this._messages.find(pub);\n const numMessages = this._messages.length();\n if (0 <= idx && idx < numMessages) {\n // Remove message with the old seq ID.\n this._messages.delAt(idx);\n this._tinode._db.remMessages(this.name, pub.seq);\n // Add message with the new seq ID.\n pub.seq = newSeqId;\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n }\n }\n /**\n * Attempt to stop message from being sent.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to stop sending and remove from cache.\n *\n * @returns {boolean} true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n _isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!this._isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags.length == 1 && tags[0] == Const.DEL_CHAR) {\n tags = [];\n }\n this._tags = tags;\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n const topic = this;\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(function(range) {\n if (!range.hi) {\n count++;\n topic.flushMessage(range.low);\n } else {\n for (let i = range.low; i < range.hi; i++) {\n count++;\n topic.flushMessage(i);\n }\n }\n });\n }\n\n if (count > 0) {\n // this._updateDeletedRanges();\n\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, params) {\n const {\n since,\n before,\n limit\n } = params || {};\n return db.readMessages(this.name, {\n since: since,\n before: before,\n limit: limit || Const.DEFAULT_MESSAGES_PAGE\n })\n .then(msgs => {\n msgs.forEach((data) => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n return msgs.length;\n });\n }\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n\n/**\n * @class TopicFnd - special case of {@link Tinode.Topic} for searching for\n * contacts and group topics.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n Topic,\n TopicMe,\n TopicFnd\n} from './topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format /\n this._appName = config.appName || \"Undefined\";\n\n // API Key.\n this._apiKey = config.apiKey;\n\n // Name and version of the browser.\n this._platform = config.platform || 'web';\n // Underlying OS.\n if (typeof navigator != 'undefined') {\n this._browser = getBrowserInfo(navigator.userAgent, navigator.product);\n this._hwos = navigator.platform;\n // This is the default language. It could be changed by client.\n this._humanLanguage = navigator.language || 'en-US';\n }\n\n Connection.logger = this.logger;\n Drafty.logger = this.logger;\n\n // WebSocket or long polling network connection.\n if (config.transport != 'lp' && config.transport != 'ws') {\n config.transport = detectTransport();\n }\n this._connection = new Connection(config, Const.PROTOCOL_VERSION, /* autoreconnect */ true);\n this._connection.onMessage = (data) => {\n // Call the main message dispatcher.\n this.#dispatchMessage(data);\n }\n\n // Ready to start sending.\n this._connection.onOpen = _ => this.#connectionOpen();\n this._connection.onDisconnect = (err, code) => this.#disconnected(err, code);\n\n // Wrapper for the reconnect iterator callback.\n this._connection.onAutoreconnectIteration = (timeout, promise) => {\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout, promise);\n }\n }\n\n this._persist = config.persist;\n // Initialize object regardless. It simplifies the code.\n this._db = new DBCache(err => {\n this.logger('DB', err);\n }, this.logger);\n\n if (this._persist) {\n // Create the persistent cache.\n // Store promises to be resolved when messages load into memory.\n const prom = [];\n this._db.initDatabase().then(_ => {\n // First load topics into memory.\n return this._db.mapTopics((data) => {\n let topic = this.#cacheGet('topic', data.name);\n if (topic) {\n return;\n }\n if (data.name == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (data.name == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(data.name);\n }\n this._db.deserializeTopic(topic, data);\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Topic loaded from DB is not new.\n delete topic._new;\n // Request to load messages and save the promise.\n prom.push(topic._loadMessages(this._db));\n });\n }).then(_ => {\n // Then load users.\n return this._db.mapUsers((data) => {\n this.#cachePut('user', data.uid, mergeObj({}, data.public));\n });\n }).then(_ => {\n // Now wait for all messages to finish loading.\n return Promise.all(prom);\n }).then(_ => {\n if (onComplete) {\n onComplete();\n }\n this.logger(\"Persistent cache initialized.\");\n }).catch(err => {\n if (onComplete) {\n onComplete(err);\n }\n this.logger(\"Failed to initialize persistent cache:\", err);\n });\n } else {\n this._db.deleteDatabase().then(_ => {\n if (onComplete) {\n onComplete();\n }\n });\n }\n }\n\n // Private methods.\n\n // Console logger. Babel somehow fails to parse '...rest' parameter.\n logger(str, ...args) {\n if (this._loggingEnabled) {\n const d = new Date();\n const dateString = ('0' + d.getUTCHours()).slice(-2) + ':' +\n ('0' + d.getUTCMinutes()).slice(-2) + ':' +\n ('0' + d.getUTCSeconds()).slice(-2) + '.' +\n ('00' + d.getUTCMilliseconds()).slice(-3);\n\n console.log('[' + dateString + ']', str, args.join(' '));\n }\n }\n\n // Generator of default promises for sent packets.\n #makePromise(id) {\n let promise = null;\n if (id) {\n promise = new Promise((resolve, reject) => {\n // Stored callbacks will be called when the response packet with this Id arrives\n this._pendingPromises[id] = {\n 'resolve': resolve,\n 'reject': reject,\n 'ts': new Date()\n };\n });\n }\n return promise;\n };\n\n // Resolve or reject a pending promise.\n // Unresolved promises are stored in _pendingPromises.\n #execPromise(id, code, onOK, errorText) {\n const callbacks = this._pendingPromises[id];\n if (callbacks) {\n delete this._pendingPromises[id];\n if (code >= 200 && code < 400) {\n if (callbacks.resolve) {\n callbacks.resolve(onOK);\n }\n } else if (callbacks.reject) {\n callbacks.reject(new CommError(errorText, code));\n }\n }\n }\n\n // Send a packet. If packet id is provided return a promise.\n #send(pkt, id) {\n let promise;\n if (id) {\n promise = this.#makePromise(id);\n }\n pkt = simplify(pkt);\n let msg = JSON.stringify(pkt);\n this.logger(\"out: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : msg));\n try {\n this._connection.sendText(msg);\n } catch (err) {\n // If sendText throws, wrap the error in a promise or rethrow.\n if (id) {\n this.#execPromise(id, Connection.NETWORK_ERROR, null, err.message);\n } else {\n throw err;\n }\n }\n return promise;\n }\n\n // The main message dispatcher.\n #dispatchMessage(data) {\n // Skip empty response. This happens when LP times out.\n if (!data)\n return;\n\n this._inPacketCount++;\n\n // Send raw message to listener\n if (this.onRawMessage) {\n this.onRawMessage(data);\n }\n\n if (data === '0') {\n // Server response to a network probe.\n if (this.onNetworkProbe) {\n this.onNetworkProbe();\n }\n // No processing is necessary.\n return;\n }\n\n let pkt = JSON.parse(data, jsonParseHelper);\n if (!pkt) {\n this.logger(\"in: \" + data);\n this.logger(\"ERROR: failed to parse data\");\n } else {\n this.logger(\"in: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : data));\n\n // Send complete packet to listener\n if (this.onMessage) {\n this.onMessage(pkt);\n }\n\n if (pkt.ctrl) {\n // Handling {ctrl} message\n if (this.onCtrlMessage) {\n this.onCtrlMessage(pkt.ctrl);\n }\n\n // Resolve or reject a pending promise, if any\n if (pkt.ctrl.id) {\n this.#execPromise(pkt.ctrl.id, pkt.ctrl.code, pkt.ctrl, pkt.ctrl.text);\n }\n setTimeout(_ => {\n if (pkt.ctrl.code == 205 && pkt.ctrl.text == 'evicted') {\n // User evicted from topic.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._resetSub();\n if (pkt.ctrl.params && pkt.ctrl.params.unsub) {\n topic._gone();\n }\n }\n } else if (pkt.ctrl.code < 300 && pkt.ctrl.params) {\n if (pkt.ctrl.params.what == 'data') {\n // code=208, all messages received: \"params\":{\"count\":11,\"what\":\"data\"},\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._allMessagesReceived(pkt.ctrl.params.count);\n }\n } else if (pkt.ctrl.params.what == 'sub') {\n // code=204, the topic has no (refreshed) subscriptions.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n // Trigger topic.onSubsUpdated.\n topic._processMetaSub([]);\n }\n }\n }\n }, 0);\n } else {\n setTimeout(_ => {\n if (pkt.meta) {\n // Handling a {meta} message.\n // Preferred API: Route meta to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.meta.topic);\n if (topic) {\n topic._routeMeta(pkt.meta);\n }\n\n if (pkt.meta.id) {\n this.#execPromise(pkt.meta.id, 200, pkt.meta, 'META');\n }\n\n // Secondary API: callback\n if (this.onMetaMessage) {\n this.onMetaMessage(pkt.meta);\n }\n } else if (pkt.data) {\n // Handling {data} message\n // Preferred API: Route data to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.data.topic);\n if (topic) {\n topic._routeData(pkt.data);\n }\n\n // Secondary API: Call callback\n if (this.onDataMessage) {\n this.onDataMessage(pkt.data);\n }\n } else if (pkt.pres) {\n // Handling {pres} message\n // Preferred API: Route presence to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.pres.topic);\n if (topic) {\n topic._routePres(pkt.pres);\n }\n\n // Secondary API - callback\n if (this.onPresMessage) {\n this.onPresMessage(pkt.pres);\n }\n } else if (pkt.info) {\n // {info} message - read/received notifications and key presses\n // Preferred API: Route {info}} to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.info.topic);\n if (topic) {\n topic._routeInfo(pkt.info);\n }\n\n // Secondary API - callback\n if (this.onInfoMessage) {\n this.onInfoMessage(pkt.info);\n }\n } else {\n this.logger(\"ERROR: Unknown packet received.\");\n }\n }, 0);\n }\n }\n }\n\n // Connection open, ready to start sending.\n #connectionOpen() {\n if (!this._expirePromises) {\n // Reject promises which have not been resolved for too long.\n this._expirePromises = setInterval(_ => {\n const err = new CommError(\"timeout\", 504);\n const expires = new Date(new Date().getTime() - Const.EXPIRE_PROMISES_TIMEOUT);\n for (let id in this._pendingPromises) {\n let callbacks = this._pendingPromises[id];\n if (callbacks && callbacks.ts < expires) {\n this.logger(\"Promise expired\", id);\n delete this._pendingPromises[id];\n if (callbacks.reject) {\n callbacks.reject(err);\n }\n }\n }\n }, Const.EXPIRE_PROMISES_PERIOD);\n }\n this.hello();\n }\n\n #disconnected(err, code) {\n this._inPacketCount = 0;\n this._serverInfo = null;\n this._authenticated = false;\n\n if (this._expirePromises) {\n clearInterval(this._expirePromises);\n this._expirePromises = null;\n }\n\n // Mark all topics as unsubscribed\n this.#cacheMap('topic', (topic, key) => {\n topic._resetSub();\n });\n\n // Reject all pending promises\n for (let key in this._pendingPromises) {\n const callbacks = this._pendingPromises[key];\n if (callbacks && callbacks.reject) {\n callbacks.reject(err);\n }\n }\n this._pendingPromises = {};\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n }\n\n // Get User Agent string\n #getUserAgent() {\n return this._appName + ' (' + (this._browser ? this._browser + '; ' : '') + this._hwos + '); ' + Const.LIBRARY;\n }\n\n // Generator of packets stubs\n #initPacket(type, topic) {\n switch (type) {\n case 'hi':\n return {\n 'hi': {\n 'id': this.getNextUniqueId(),\n 'ver': Const.VERSION,\n 'ua': this.#getUserAgent(),\n 'dev': this._deviceToken,\n 'lang': this._humanLanguage,\n 'platf': this._platform\n }\n };\n\n case 'acc':\n return {\n 'acc': {\n 'id': this.getNextUniqueId(),\n 'user': null,\n 'scheme': null,\n 'secret': null,\n 'tmpscheme': null,\n 'tmpsecret': null,\n 'login': false,\n 'tags': null,\n 'desc': {},\n 'cred': {}\n }\n };\n\n case 'login':\n return {\n 'login': {\n 'id': this.getNextUniqueId(),\n 'scheme': null,\n 'secret': null\n }\n };\n\n case 'sub':\n return {\n 'sub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'set': {},\n 'get': {}\n }\n };\n\n case 'leave':\n return {\n 'leave': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'unsub': false\n }\n };\n\n case 'pub':\n return {\n 'pub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'noecho': false,\n 'head': null,\n 'content': {}\n }\n };\n\n case 'get':\n return {\n 'get': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'desc': {},\n 'sub': {},\n 'data': {}\n }\n };\n\n case 'set':\n return {\n 'set': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'desc': {},\n 'sub': {},\n 'tags': [],\n 'ephemeral': {}\n }\n };\n\n case 'del':\n return {\n 'del': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'delseq': null,\n 'user': null,\n 'hard': false\n }\n };\n\n case 'note':\n return {\n 'note': {\n // no id by design (except calls).\n 'topic': topic,\n 'what': null, // one of \"recv\", \"read\", \"kp\", \"call\"\n 'seq': undefined // the server-side message id acknowledged as received or read.\n }\n };\n\n default:\n throw new Error(`Unknown packet type requested: ${type}`);\n }\n }\n\n // Cache management\n #cachePut(type, name, obj) {\n this._cache[type + ':' + name] = obj;\n }\n #cacheGet(type, name) {\n return this._cache[type + ':' + name];\n }\n #cacheDel(type, name) {\n delete this._cache[type + ':' + name];\n }\n\n // Enumerate all items in cache, call func for each item.\n // Enumeration stops if func returns true.\n #cacheMap(type, func, context) {\n const key = type ? type + ':' : undefined;\n for (let idx in this._cache) {\n if (!key || idx.indexOf(key) == 0) {\n if (func.call(context, this._cache[idx], idx)) {\n break;\n }\n }\n }\n }\n\n // Make limited cache management available to topic.\n // Caching user.public only. Everything else is per-topic.\n #attachCacheToTopic(topic) {\n topic._tinode = this;\n\n topic._cacheGetUser = (uid) => {\n const pub = this.#cacheGet('user', uid);\n if (pub) {\n return {\n user: uid,\n public: mergeObj({}, pub)\n };\n }\n return undefined;\n };\n topic._cachePutUser = (uid, user) => {\n this.#cachePut('user', uid, mergeObj({}, user.public));\n };\n topic._cacheDelUser = (uid) => {\n this.#cacheDel('user', uid);\n };\n topic._cachePutSelf = _ => {\n this.#cachePut('topic', topic.name, topic);\n };\n topic._cacheDelSelf = _ => {\n this.#cacheDel('topic', topic.name);\n };\n }\n\n // On successful login save server-provided data.\n #loginSuccessful(ctrl) {\n if (!ctrl.params || !ctrl.params.user) {\n return ctrl;\n }\n // This is a response to a successful login,\n // extract UID and security token, save it in Tinode module\n this._myUID = ctrl.params.user;\n this._authenticated = (ctrl && ctrl.code >= 200 && ctrl.code < 300);\n if (ctrl.params && ctrl.params.token && ctrl.params.expires) {\n this._authToken = {\n token: ctrl.params.token,\n expires: ctrl.params.expires\n };\n } else {\n this._authToken = null;\n }\n\n if (this.onLogin) {\n this.onLogin(ctrl.code, ctrl.text);\n }\n\n return ctrl;\n }\n\n // Static methods.\n /**\n * Helper method to package account credential.\n *\n * @param {string | Credential} meth - validation method or object with validation data.\n * @param {string=} val - validation value (e.g. email or phone number).\n * @param {Object=} params - validation parameters.\n * @param {string=} resp - validation response.\n *\n * @returns {Array.} array with a single credential or null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.} tags - array of string tags for user discovery.\n * @property {string} scheme - Temporary authentication scheme for password reset.\n * @property {string} secret - Temporary authentication secret for password reset.\n * @property {Array.=} attachments - Array of references to out of band attachments used in account description.\n */\n /**\n * @typedef DefAcs\n * @type {Object}\n * @property {string=} auth - Access mode for me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.=} attachments - URLs of out of band attachments used in parameters.\n */\n /**\n * @typedef SetDesc\n * @type {Object}\n * @property {DefAcs=} defacs - Default access mode.\n * @property {Object=} public - Free-form topic description, publically accessible.\n * @property {Object=} private - Free-form topic description accessible only to the owner.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n */\n /**\n * @typedef SetSub\n * @type {Object}\n * @property {string=} user - UID of the user affected by the request. Default (empty) - current user.\n * @property {string=} mode - User access mode, either requested or assigned dependent on context.\n */\n /**\n * Send a topic subscription request.\n *\n * @param {string} topic - Name of the topic to subscribe to.\n * @param {GetQuery=} getParams - Optional subscription metadata query\n * @param {SetParams=} setParams - Optional initialization parameters\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n subscribe(topicName, getParams, setParams) {\n const pkt = this.#initPacket('sub', topicName)\n if (!topicName) {\n topicName = Const.TOPIC_NEW;\n }\n\n pkt.sub.get = getParams;\n\n if (setParams) {\n if (setParams.sub) {\n pkt.sub.set.sub = setParams.sub;\n }\n\n if (setParams.desc) {\n const desc = setParams.desc;\n if (Tinode.isNewGroupTopicName(topicName)) {\n // Full set.desc params are used for new topics only\n pkt.sub.set.desc = desc;\n } else if (Tinode.isP2PTopicName(topicName) && desc.defacs) {\n // Use optional default permissions only.\n pkt.sub.set.desc = {\n defacs: desc.defacs\n };\n }\n }\n\n // See if external objects were used in topic description.\n if (Array.isArray(setParams.attachments) && setParams.attachments.length > 0) {\n pkt.extra = {\n attachments: setParams.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n\n if (setParams.tags) {\n pkt.sub.set.tags = setParams.tags;\n }\n }\n return this.#send(pkt, pkt.sub.id);\n }\n\n /**\n * Detach and optionally unsubscribe from the topic\n *\n * @param {string} topic - Topic to detach from.\n * @param {boolean} unsub - If true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.=} attachments - array of URLs with attachments.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publishMessage(pub, attachments) {\n // Make a shallow copy. Needed in order to clear locally-assigned temp values;\n pub = Object.assign({}, pub);\n pub.seq = undefined;\n pub.from = undefined;\n pub.ts = undefined;\n const msg = {\n pub: pub,\n };\n if (attachments) {\n msg.extra = {\n attachments: attachments.filter(ref => isUrlRelative(ref))\n };\n }\n return this.#send(msg, pub.id);\n }\n\n /**\n * Out of band notification: notify topic that an external (push) notification was recived by the client.\n *\n * @param {object} data - notification payload.\n * @param {string} data.what - notification type, 'msg', 'read', 'sub'.\n * @param {string} data.topic - name of the updated topic.\n * @param {number=} data.seq - seq ID of the affected message.\n * @param {string=} data.xfrom - UID of the sender.\n * @param {object=} data.given - new subscription 'given', e.g. 'ASWP...'.\n * @param {object=} data.want - new subscription 'want', e.g. 'RWJ...'.\n */\n oobNotification(data) {\n this.logger('oob: ' + (this._trimLongStrings ? JSON.stringify(data, jsonLoggerHelper) : data));\n\n switch (data.what) {\n case 'msg':\n if (!data.seq || data.seq < 1 || !data.topic) {\n // Server sent invalid data.\n break;\n }\n\n if (!this.isConnected()) {\n // Let's ignore the message if there is no connection: no connection means there are no open\n // tabs with Tinode.\n break;\n }\n\n const topic = this.#cacheGet('topic', data.topic);\n if (!topic) {\n // TODO: check if there is a case when a message can arrive from an unknown topic.\n break;\n }\n\n if (topic.isSubscribed()) {\n // No need to fetch: topic is already subscribed and got data through normal channel.\n break;\n }\n\n if (topic.maxMsgSeq() < data.seq) {\n if (topic.isChannelType()) {\n topic._updateReceived(data.seq, 'fake-uid');\n }\n\n // New message.\n if (data.xfrom && !this.#cacheGet('user', data.xfrom)) {\n // Message from unknown sender, fetch description from the server.\n // Sending asynchronously without a subscription.\n this.getMeta(data.xfrom, new MetaGetBuilder().withDesc().build()).catch(err => {\n this.logger(\"Failed to get the name of a new sender\", err);\n });\n }\n\n topic.subscribe(null).then(_ => {\n return topic.getMeta(new MetaGetBuilder(topic).withLaterData(24).withLaterDel(24).build());\n }).then(_ => {\n // Allow data fetch to complete and get processed successfully.\n topic.leaveDelayed(false, 1000);\n }).catch(err => {\n this.logger(\"On push data fetch failed\", err);\n }).finally(_ => {\n this.getMeTopic()._refreshContact('msg', topic);\n });\n }\n break;\n\n case 'read':\n this.getMeTopic()._routePres({\n what: 'read',\n seq: data.seq\n });\n break;\n\n case 'sub':\n if (!this.isMe(data.xfrom)) {\n // TODO: handle updates from other users.\n break;\n }\n\n const mode = {\n given: data.modeGiven,\n want: data.modeWant\n };\n const acs = new AccessMode(mode);\n const pres = (!acs.mode || acs.mode == AccessMode._NONE) ?\n // Subscription deleted.\n {\n what: 'gone',\n src: data.topic\n } :\n // New subscription or subscription updated.\n {\n what: 'acs',\n src: data.topic,\n dacs: mode\n };\n this.getMeTopic()._routePres(pres);\n break;\n\n default:\n this.logger(\"Unknown push type ignored\", data.what);\n }\n }\n\n /**\n * @typedef GetQuery\n * @type {Object}\n * @property {GetOptsType=} desc - If provided (even if empty), fetch topic description.\n * @property {GetOptsType=} sub - If provided (even if empty), fetch topic subscriptions.\n * @property {GetDataType=} data - If provided (even if empty), get messages.\n */\n\n /**\n * @typedef GetOptsType\n * @type {Object}\n * @property {Date=} ims - \"If modified since\", fetch data only it was was modified since stated date.\n * @property {number=} limit - Maximum number of results to return. Ignored when querying topic description.\n */\n\n /**\n * @typedef GetDataType\n * @type {Object}\n * @property {number=} since - Load messages with seq id equal or greater than this value.\n * @property {number=} before - Load messages with seq id lower than this number.\n * @property {number=} limit - Maximum number of results to return.\n */\n\n /**\n * Request topic metadata\n *\n * @param {string} topic - Name of the topic to query.\n * @param {GetQuery} params - Parameters of the query. Use {@link Tinode.MetaGetBuilder} to generate.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n getMeta(topic, params) {\n const pkt = this.#initPacket('get', topic);\n\n pkt.get = mergeObj(pkt.get, params);\n\n return this.#send(pkt, pkt.get.id);\n }\n\n /**\n * Update topic's metadata: description, subscribtions.\n *\n * @param {string} topic - Topic to update.\n * @param {SetParams} params - topic metadata to update.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n setMeta(topic, params) {\n const pkt = this.#initPacket('set', topic);\n const what = [];\n\n if (params) {\n ['desc', 'sub', 'tags', 'cred', 'ephemeral'].forEach(function(key) {\n if (params.hasOwnProperty(key)) {\n what.push(key);\n pkt.set[key] = params[key];\n }\n });\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n if (what.length == 0) {\n return Promise.reject(new Error(\"Invalid {set} parameters\"));\n }\n\n return this.#send(pkt, pkt.set.id);\n }\n\n /**\n * Range of message IDs to delete.\n *\n * @typedef DelRange\n * @type {Object}\n * @property {number} low - low end of the range, inclusive (closed).\n * @property {number=} hi - high end of the range, exclusive (open).\n */\n /**\n * Delete some or all messages in a topic.\n *\n * @param {string} topic - Topic name to delete messages from.\n * @param {DelRange[]} list - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delMessages(topic, ranges, hard) {\n const pkt = this.#initPacket('del', topic);\n\n pkt.del.what = 'msg';\n pkt.del.delseq = ranges;\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete the topic alltogether. Requires Owner permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {boolean} hard - hard-delete topic.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delTopic(topicName, hard) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'topic';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete subscription. Requires Share permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delSubscription(topicName, user) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'sub';\n pkt.del.user = user;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete credential. Always sent on 'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n"],"names":["root","factory","exports","module","define","amd","this","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","name","start","end","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","val","test","url","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","undefined","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","logger","bin","atob","length","buf","ArrayBuffer","arr","Uint8Array","i","charCodeAt","URL","createObjectURL","Blob","type","err","message","base64toDataUrl","DECORATORS","open","_","close","data","props","href","target","id","act","ref","mime","Drafty","src","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","chunkify","line","spans","chunks","span","at","push","chunk","tp","chld","children","toSpanTree","tree","last","draftyToTree","doc","Array","isArray","text","len","key","attachments","forEach","includes","sort","a","b","diff","indexOf","spansToTree","treeTopDown","node","child","parent","addNode","n","substring","att","subspans","inner","tag","treeToDrafty","keymap","c","Object","keys","newKey","transformer","context","dst","call","treeBottomUp","formatter","index","stack","values","pop","shortenTree","limit","tail","lightEntity","allow","copyEntData","lTrim","trimStart","shift","attachmentsToEnd","concat","draftify","startAt","plain","ranges","drafty","light","entries","dc","init","plainText","parse","content","lines","split","entityMap","entityIndex","blx","entities","block","original","re_start","re_end","result","exec","start_offset","lastIndexOf","end_offset","spannify","match","extracted","entity","offset","unique","idx","filter","el","extractEntities","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","params","assign","quote","header","uid","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","appendButton","attachJSON","UNSAFE_toHTML","join","format","shorten","forwardedContent","replyContent","startsWith","forwarding","toPlainText","isPlainText","toMarkdown","def","isValid","txt_type","hasAttachments","callback","count","hasEntities","styles","sanitizeEntities","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","__esModule","d","definition","o","defineProperty","enumerable","get","g","globalThis","Function","e","window","obj","prop","prototype","hasOwnProperty","r","Symbol","toStringTag","value","AccessMode","constructor","acs","given","decode","want","mode","static","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","bit","charAt","toUpperCase","_INVALID","res","upd","action","val0","parts","a1","a2","toString","encode","jsonHelper","setMode","m","updateMode","u","update","getMode","setGiven","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","side","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","flag","Error","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_GRP","LOCAL_SEQID","EXPIRE_PROMISES_TIMEOUT","EXPIRE_PROMISES_PERIOD","DEL_CHAR","CommError","code","super","jsonParseHelper","date","Date","isNaN","isUrlRelative","isValidDate","getTime","mergeObj","ignore","mergeToCache","cache","newval","simplify","getOwnPropertyNames","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","initialized","wsProvider","xhrProvider","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","_lpURL","_poller","_sender","lp_poller","url_","resolve","poller","promiseCompleted","onreadystatechange","evt","readyState","status","pkt","JSON","responseText","ctrl","sid","send","onOpen","onMessage","onDisconnect","abort","sender","lp_sender","OPEN","conn","onerror","onopen","onclose","onmessage","DB_NAME","IDBProvider","DB","onError","initDatabase","req","onsuccess","event","db","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","put","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","updUser","pub","arguments","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","mapSubscriptions","getAll","addMessage","add","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","since","before","openCursor","cursor","continue","idbProvider","source","f","tags","_tags","setAccessMode","read","unread","max","getAccessMode","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","withTags","withCred","withDel","withLaterDel","_maxDel","extract","build","updated","isP2PType","CBuffer","compare_","unique_","getAt","buffer","getLast","insert","delAt","splice","delRange","reset","startIdx","beforeIdx","find","elem","nearest","isEmpty","exact","pivot","found","Topic","callbacks","created","touched","private","trusted","_users","_queuedSeqId","Const","_noEarlierMsgs","_recvNotificationTimer","_credentials","_messageVersions","_messages","_attached","_new","_delayedLeaveTimer","onData","onMeta","onPres","onInfo","onMetaDesc","onMetaSub","onSubsUpdated","onTagsUpdated","onCredsUpdated","onDeleteTopic","onAllMessagesReceived","topicType","isP2PTopicName","isGroupTopicName","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","desc","_noForwarding","_processMetaDesc","createMessage","noEcho","publish","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_db","_cancelled","_fatal","leave","unsub","_resetSub","_gone","leaveDelayed","delay","getMeta","getMessagesPage","forward","startMetaQuery","_loadMessages","promise","setMeta","out","t","trim","toLowerCase","item","pos","ary","normalizeArray","_processMetaSub","_processMetaTags","cred","_processMetaCreds","subscriber","am","invite","archive","arch","delMessages","hard","r1","r2","low","hi","tosend","reduce","del","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","list","prev","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","_refreshContact","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","recv","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","cb","origSeq","versions","messages","sinceId","beforeId","msgs","unused1","unused2","_isReplacementMsg","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","msgHasMoreMessages","newer","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isArchived","isMeType","isMeTopicName","isChannelType","isChannelTopicName","isGroupType","isCommType","isCommTopicName","isMe","head","replace","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","clear","delseq","_routePres","pres","online","isTopicCached","dacs","_routeInfo","info","subs","deleted","_updateCachedUser","creds","_allMessagesReceived","cached","_cachePutUser","_updateReceived","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","updateCount","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","method","contacts","getContact","getCredentials","TopicFnd","_contacts","indexBy","getPrototypeOf","IndexedDBProvider","b64EncodeUnicode","btoa","encodeURIComponent","p1","String","fromCharCode","jsonBuildHelper","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","rfc3339DateString","jsonLoggerHelper","WebSocket","XMLHttpRequest","indexedDB","chars","global","output","charCode","bc","bs","setNetworkProviders","setNetworkProvider","DBCache","initForNonBrowserApp","Tinode","onComplete","floor","_appName","appName","_platform","platform","navigator","_browser","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","getBrowserInfo","userAgent","_hwos","_humanLanguage","language","detectTransport","_connection","_persist","persist","all","_loggingEnabled","dateString","args","console","log","isNewGroupTopicName","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","searchParams","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","hello","_serverInfo","onConnect","setDeviceToken","dt","sent","_deviceToken","loginBasic","uname","_login","loginToken","requestResetAuthSecret","expires","now","setAuthToken","dft","oobNotification","_trimLongStrings","stringify","xfrom","finally","modeGiven","modeWant","delCurrentUser","func","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_pendingPromises","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_cache","_cacheDelUser","onLogin","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file
+{"version":3,"file":"tinode.prod.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,GAClB,CATD,CASGK,MAAM,I,kCCmDT,MAEMC,EAAwB,GACxBC,EAAiB,mBAEjBC,EAAqB,CAAC,MAAO,SAAU,WAAY,WAAY,OAAQ,OAAQ,UAAW,SAAU,UACxG,MAAO,OAAQ,QAAS,MAAO,MAAO,SAKlCC,EAAgB,CAEpB,CACEC,KAAM,KACNC,MAAO,wBACPC,IAAK,yBAGP,CACEF,KAAM,KACNC,MAAO,oBACPC,IAAK,qBAGP,CACEF,KAAM,KACNC,MAAO,uBACPC,IAAK,wBAGP,CACEF,KAAM,KACNC,MAAO,kBACPC,IAAK,oBAKHC,EAAa,CAAC,MAGdC,EAAe,CAEnB,CACEJ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4B,GS0pEnCxH,GAAOyH,wBTzpEgC,GS0pEvCzH,GAAO0H,oBTzpE4B,GS0pEnC1H,GAAO2H,qBTzpE6B,GS4pEpC3H,GAAO/gB,SAAWqR,EAGlB0P,GAAO4H,iBAAmB,iBAC1B5H,GAAO6H,qBAAuB,qBAC9B7H,GAAO8H,cAAgB,cACvB9H,GAAO+H,qBAAuB,oBAC9B/H,GAAOgI,oBAAsB,S","sources":["webpack://tinode/webpack/universalModuleDefinition","webpack://tinode/./src/drafty.js","webpack://tinode/webpack/bootstrap","webpack://tinode/webpack/runtime/compat get default export","webpack://tinode/webpack/runtime/define property getters","webpack://tinode/webpack/runtime/global","webpack://tinode/webpack/runtime/hasOwnProperty shorthand","webpack://tinode/webpack/runtime/make namespace object","webpack://tinode/./src/access-mode.js","webpack://tinode/./version.js","webpack://tinode/./src/config.js","webpack://tinode/./src/comm-error.js","webpack://tinode/./src/utils.js","webpack://tinode/./src/connection.js","webpack://tinode/./src/db.js","webpack://tinode/./src/large-file.js","webpack://tinode/./src/meta-builder.js","webpack://tinode/./src/cbuffer.js","webpack://tinode/./src/topic.js","webpack://tinode/./src/tinode.js"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"tinode\"] = factory();\n\telse\n\t\troot[\"tinode\"] = factory();\n})(this, () => {\nreturn ","/**\n * @copyright 2015-2022 Tinode LLC.\n * @summary Minimally rich text representation and formatting for Tinode.\n * @license Apache 2.0\n *\n * @file Basic parser and formatter for very simple text markup. Mostly targeted at\n * mobile use cases similar to Telegram, WhatsApp, and FB Messenger.\n *\n * Supports conversion of user keyboard input to formatted text:
\n * \n * - *abc* → abc
\n * - _abc_ → abc
\n * - ~abc~ →
abc \n * - `abc` → abc
\n *
\n * Also supports forms and buttons.\n *\n * Nested formatting is supported, e.g. *abc _def_* -> abc def\n * URLs, @mentions, and #hashtags are extracted and converted into links.\n * Forms and buttons can be added procedurally.\n * JSON data representation is inspired by Draft.js raw formatting.\n *\n *\n * @example\n * Text:\n * \n * this is *bold*, `code` and _italic_, ~strike~\n * combined *bold and _italic_*\n * an url: https://www.example.com/abc#fragment and another _www.tinode.co_\n * this is a @mention and a #hashtag in a string\n * second #hashtag\n *
\n *\n * Sample JSON representation of the text above:\n * {\n * \"txt\": \"this is bold, code and italic, strike combined bold and italic an url: https://www.example.com/abc#fragment \" +\n * \"and another www.tinode.co this is a @mention and a #hashtag in a string second #hashtag\",\n * \"fmt\": [\n * { \"at\":8, \"len\":4,\"tp\":\"ST\" },{ \"at\":14, \"len\":4, \"tp\":\"CO\" },{ \"at\":23, \"len\":6, \"tp\":\"EM\"},\n * { \"at\":31, \"len\":6, \"tp\":\"DL\" },{ \"tp\":\"BR\", \"len\":1, \"at\":37 },{ \"at\":56, \"len\":6, \"tp\":\"EM\" },\n * { \"at\":47, \"len\":15, \"tp\":\"ST\" },{ \"tp\":\"BR\", \"len\":1, \"at\":62 },{ \"at\":120, \"len\":13, \"tp\":\"EM\" },\n * { \"at\":71, \"len\":36, \"key\":0 },{ \"at\":120, \"len\":13, \"key\":1 },{ \"tp\":\"BR\", \"len\":1, \"at\":133 },\n * { \"at\":144, \"len\":8, \"key\":2 },{ \"at\":159, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":179 },\n * { \"at\":187, \"len\":8, \"key\":3 },{ \"tp\":\"BR\", \"len\":1, \"at\":195 }\n * ],\n * \"ent\": [\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"https://www.example.com/abc#fragment\" } },\n * { \"tp\":\"LN\", \"data\":{ \"url\":\"http://www.tinode.co\" } },\n * { \"tp\":\"MN\", \"data\":{ \"val\":\"mention\" } },\n * { \"tp\":\"HT\", \"data\":{ \"val\":\"hashtag\" } }\n * ]\n * }\n */\n\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst MAX_FORM_ELEMENTS = 8;\nconst MAX_PREVIEW_ATTACHMENTS = 3;\nconst MAX_PREVIEW_DATA_SIZE = 64;\nconst JSON_MIME_TYPE = 'application/json';\nconst DRAFTY_MIME_TYPE = 'text/x-drafty';\nconst ALLOWED_ENT_FIELDS = ['act', 'height', 'duration', 'incoming', 'mime', 'name', 'premime', 'preref', 'preview',\n 'ref', 'size', 'state', 'url', 'val', 'width'\n];\n\n// Regular expressions for parsing inline formats. Javascript does not support lookbehind,\n// so it's a bit messy.\nconst INLINE_STYLES = [\n // Strong = bold, *bold text*\n {\n name: 'ST',\n start: /(?:^|[\\W_])(\\*)[^\\s*]/,\n end: /[^\\s*](\\*)(?=$|[\\W_])/\n },\n // Emphesized = italic, _italic text_\n {\n name: 'EM',\n start: /(?:^|\\W)(_)[^\\s_]/,\n end: /[^\\s_](_)(?=$|\\W)/\n },\n // Deleted, ~strike this though~\n {\n name: 'DL',\n start: /(?:^|[\\W_])(~)[^\\s~]/,\n end: /[^\\s~](~)(?=$|[\\W_])/\n },\n // Code block `this is monospace`\n {\n name: 'CO',\n start: /(?:^|\\W)(`)[^`]/,\n end: /[^`](`)(?=$|\\W)/\n }\n];\n\n// Relative weights of formatting spans. Greater index in array means greater weight.\nconst FMT_WEIGHT = ['QQ'];\n\n// RegExps for entity extraction (RF = reference)\nconst ENTITY_TYPES = [\n // URLs\n {\n name: 'LN',\n dataName: 'url',\n pack: function(val) {\n // Check if the protocol is specified, if not use http\n if (!/^[a-z]+:\\/\\//i.test(val)) {\n val = 'http://' + val;\n }\n return {\n url: val\n };\n },\n re: /(?:(?:https?|ftp):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]/ig\n },\n // Mentions @user (must be 2 or more characters)\n {\n name: 'MN',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B@([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n },\n // Hashtags #hashtag, like metion 2 or more characters.\n {\n name: 'HT',\n dataName: 'val',\n pack: function(val) {\n return {\n val: val.slice(1)\n };\n },\n re: /\\B#([\\p{L}\\p{N}][._\\p{L}\\p{N}]*[\\p{L}\\p{N}])/ug\n }\n];\n\n// HTML tag name suggestions\nconst FORMAT_TAGS = {\n AU: {\n html_tag: 'audio',\n md_tag: undefined,\n isVoid: false\n },\n BN: {\n html_tag: 'button',\n md_tag: undefined,\n isVoid: false\n },\n BR: {\n html_tag: 'br',\n md_tag: '\\n',\n isVoid: true\n },\n CO: {\n html_tag: 'tt',\n md_tag: '`',\n isVoid: false\n },\n DL: {\n html_tag: 'del',\n md_tag: '~',\n isVoid: false\n },\n EM: {\n html_tag: 'i',\n md_tag: '_',\n isVoid: false\n },\n EX: {\n html_tag: '',\n md_tag: undefined,\n isVoid: true\n },\n FM: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n HD: {\n html_tag: '',\n md_tag: undefined,\n isVoid: false\n },\n HL: {\n html_tag: 'span',\n md_tag: undefined,\n isVoid: false\n },\n HT: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n IM: {\n html_tag: 'img',\n md_tag: undefined,\n isVoid: false\n },\n LN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n MN: {\n html_tag: 'a',\n md_tag: undefined,\n isVoid: false\n },\n RW: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false,\n },\n QQ: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n ST: {\n html_tag: 'b',\n md_tag: '*',\n isVoid: false\n },\n VC: {\n html_tag: 'div',\n md_tag: undefined,\n isVoid: false\n },\n VD: {\n html_tag: 'video',\n md_tag: undefined,\n isVoid: false\n }\n};\n\n// Convert base64-encoded string into Blob.\nfunction base64toObjectUrl(b64, contentType, logger) {\n if (!b64) {\n return null;\n }\n\n try {\n const bin = atob(b64);\n const length = bin.length;\n const buf = new ArrayBuffer(length);\n const arr = new Uint8Array(buf);\n for (let i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n\n return URL.createObjectURL(new Blob([buf], {\n type: contentType\n }));\n } catch (err) {\n if (logger) {\n logger(\"Drafty: failed to convert object.\", err.message);\n }\n }\n\n return null;\n}\n\nfunction base64toDataUrl(b64, contentType) {\n if (!b64) {\n return null;\n }\n contentType = contentType || 'image/jpeg';\n return 'data:' + contentType + ';base64,' + b64;\n}\n\n// Helpers for converting Drafty to HTML.\nconst DECORATORS = {\n // Visial styles\n ST: {\n open: _ => '',\n close: _ => ''\n },\n EM: {\n open: _ => '',\n close: _ => ''\n },\n DL: {\n open: _ => '',\n close: _ => ''\n },\n CO: {\n open: _ => '',\n close: _ => ''\n },\n // Line break\n BR: {\n open: _ => '
',\n close: _ => ''\n },\n // Hidden element\n HD: {\n open: _ => '',\n close: _ => ''\n },\n // Highlighted element.\n HL: {\n open: _ => '',\n close: _ => ''\n },\n // Link (URL)\n LN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n href: data.url,\n target: '_blank'\n } : null;\n },\n },\n // Mention\n MN: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Hashtag\n HT: {\n open: (data) => {\n return '';\n },\n close: _ => '',\n props: (data) => {\n return data ? {\n id: data.val\n } : null;\n },\n },\n // Button\n BN: {\n open: _ => '',\n props: (data) => {\n return data ? {\n 'data-act': data.act,\n 'data-val': data.val,\n 'data-name': data.name,\n 'data-ref': data.ref\n } : null;\n },\n },\n // Audio recording\n AU: {\n open: (data) => {\n const url = data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger);\n return '',\n props: (data) => {\n if (!data) return null;\n return {\n // Embedded data or external link.\n src: data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-duration': data.duration,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n // Image\n IM: {\n open: data => {\n // Don't use data.ref for preview: it's a security risk.\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = base64toObjectUrl(data.val, data.mime, Drafty.logger);\n const downloadUrl = data.ref || previewUrl;\n return (data.name ? '' : '') +\n '
';\n },\n close: data => {\n return (data.name ? '' : '');\n },\n props: data => {\n if (!data) return null;\n return {\n // Temporary preview, or permanent preview, or external link.\n src: base64toDataUrl(data._tempPreview, data.mime) ||\n data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n title: data.name,\n alt: data.name,\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n },\n },\n // Form - structured layout of elements.\n FM: {\n open: _ => '',\n close: _ => ''\n },\n // Row: logic grouping of elements\n RW: {\n open: _ => '',\n close: _ => ''\n },\n // Quoted block.\n QQ: {\n open: _ => '',\n close: _ => '',\n props: (data) => {\n return data ? {} : null;\n },\n },\n // Video call\n VC: {\n open: _ => '',\n close: _ => '',\n props: data => {\n if (!data) return {};\n return {\n 'data-duration': data.duration,\n 'data-state': data.state,\n };\n }\n },\n // Video.\n VD: {\n open: data => {\n const tmpPreviewUrl = base64toDataUrl(data._tempPreview, data.mime);\n const previewUrl = data.ref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return '
';\n },\n close: _ => '',\n props: data => {\n if (!data) return null;\n const poster = data.preref || base64toObjectUrl(data.preview, data.premime || 'image/jpeg', Drafty.logger);\n return {\n // Embedded data or external link.\n src: poster,\n 'data-src': data.ref || base64toObjectUrl(data.val, data.mime, Drafty.logger),\n 'data-width': data.width,\n 'data-height': data.height,\n 'data-preload': data.ref ? 'metadata' : 'auto',\n 'data-preview': poster,\n 'data-duration': data.duration | 0,\n 'data-name': data.name,\n 'data-size': data.val ? ((data.val.length * 0.75) | 0) : (data.size | 0),\n 'data-mime': data.mime,\n };\n }\n },\n};\n\n/**\n * The main object which performs all the formatting actions.\n * @class Drafty\n * @constructor\n */\nconst Drafty = function() {\n this.txt = '';\n this.fmt = [];\n this.ent = [];\n}\n\n/**\n * Initialize Drafty document to a plain text string.\n *\n * @param {string} plainText - string to use as Drafty content.\n *\n * @returns new Drafty document or null is plainText is not a string or undefined.\n */\nDrafty.init = function(plainText) {\n if (typeof plainText == 'undefined') {\n plainText = '';\n } else if (typeof plainText != 'string') {\n return null;\n }\n\n return {\n txt: plainText\n };\n}\n\n/**\n * Parse plain text into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} content - plain-text content to parse.\n * @return {Drafty} parsed document or null if the source is not plain text.\n */\nDrafty.parse = function(content) {\n // Make sure we are parsing strings only.\n if (typeof content != 'string') {\n return null;\n }\n\n // Split text into lines. It makes further processing easier.\n const lines = content.split(/\\r?\\n/);\n\n // Holds entities referenced from text\n const entityMap = [];\n const entityIndex = {};\n\n // Processing lines one by one, hold intermediate result in blx.\n const blx = [];\n lines.forEach((line) => {\n let spans = [];\n let entities;\n\n // Find formatted spans in the string.\n // Try to match each style.\n INLINE_STYLES.forEach((tag) => {\n // Each style could be matched multiple times.\n spans = spans.concat(spannify(line, tag.start, tag.end, tag.name));\n });\n\n let block;\n if (spans.length == 0) {\n block = {\n txt: line\n };\n } else {\n // Sort spans by style occurence early -> late, then by length: first long then short.\n spans.sort((a, b) => {\n const diff = a.at - b.at;\n return diff != 0 ? diff : b.end - a.end;\n });\n\n // Convert an array of possibly overlapping spans into a tree.\n spans = toSpanTree(spans);\n\n // Build a tree representation of the entire string, not\n // just the formatted parts.\n const chunks = chunkify(line, 0, line.length, spans);\n\n const drafty = draftify(chunks, 0);\n\n block = {\n txt: drafty.txt,\n fmt: drafty.fmt\n };\n }\n\n // Extract entities from the cleaned up string.\n entities = extractEntities(block.txt);\n if (entities.length > 0) {\n const ranges = [];\n for (let i in entities) {\n // {offset: match['index'], unique: match[0], len: match[0].length, data: ent.packer(), type: ent.name}\n const entity = entities[i];\n let index = entityIndex[entity.unique];\n if (!index) {\n index = entityMap.length;\n entityIndex[entity.unique] = index;\n entityMap.push({\n tp: entity.type,\n data: entity.data\n });\n }\n ranges.push({\n at: entity.offset,\n len: entity.len,\n key: index\n });\n }\n block.ent = ranges;\n }\n\n blx.push(block);\n });\n\n const result = {\n txt: ''\n };\n\n // Merge lines and save line breaks as BR inline formatting.\n if (blx.length > 0) {\n result.txt = blx[0].txt;\n result.fmt = (blx[0].fmt || []).concat(blx[0].ent || []);\n\n for (let i = 1; i < blx.length; i++) {\n const block = blx[i];\n const offset = result.txt.length + 1;\n\n result.fmt.push({\n tp: 'BR',\n len: 1,\n at: offset - 1\n });\n\n result.txt += ' ' + block.txt;\n if (block.fmt) {\n result.fmt = result.fmt.concat(block.fmt.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n if (block.ent) {\n result.fmt = result.fmt.concat(block.ent.map((s) => {\n s.at += offset;\n return s;\n }));\n }\n }\n\n if (result.fmt.length == 0) {\n delete result.fmt;\n }\n\n if (entityMap.length > 0) {\n result.ent = entityMap;\n }\n }\n return result;\n}\n\n/**\n * Append one Drafty document to another.\n *\n * @param {Drafty} first - Drafty document to append to.\n * @param {Drafty|string} second - Drafty document or string being appended.\n *\n * @return {Drafty} first document with the second appended to it.\n */\nDrafty.append = function(first, second) {\n if (!first) {\n return second;\n }\n if (!second) {\n return first;\n }\n\n first.txt = first.txt || '';\n const len = first.txt.length;\n\n if (typeof second == 'string') {\n first.txt += second;\n } else if (second.txt) {\n first.txt += second.txt;\n }\n\n if (Array.isArray(second.fmt)) {\n first.fmt = first.fmt || [];\n if (Array.isArray(second.ent)) {\n first.ent = first.ent || [];\n }\n second.fmt.forEach(src => {\n const fmt = {\n at: (src.at | 0) + len,\n len: src.len | 0\n };\n // Special case for the outside of the normal rendering flow styles.\n if (src.at == -1) {\n fmt.at = -1;\n fmt.len = 0;\n }\n if (src.tp) {\n fmt.tp = src.tp;\n } else {\n fmt.key = first.ent.length;\n first.ent.push(second.ent[src.key || 0]);\n }\n first.fmt.push(fmt);\n });\n }\n\n return first;\n}\n\n/**\n * @typedef Drafty.ImageDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the image, e.g. \"image/png\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded image content. Could be null/undefined.\n * @param {string} preview - base64-encoded thumbnail of the image.\n * @param {integer} width - width of the image.\n * @param {integer} height - height of the image.\n * @param {string} filename - file name suggestion for downloading the image.\n * @param {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {integer} at - index where the object is inserted. The length of the image is always 1.\n * @param {ImageDesc} imageDesc - object with image paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertImage = function(content, at, imageDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'IM',\n data: {\n mime: imageDesc.mime,\n ref: imageDesc.refurl,\n val: imageDesc.bits || imageDesc.preview,\n width: imageDesc.width,\n height: imageDesc.height,\n name: imageDesc.filename,\n size: imageDesc.size | 0,\n }\n };\n\n if (imageDesc.urlPromise) {\n ex.data._tempPreview = imageDesc._tempPreview;\n ex.data._processing = true;\n imageDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.VideoDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @param {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @param {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @param {integer} width - width of the video.\n * @param {integer} height - height of the video.\n * @param {integer} duration - duration of the video.\n * @param {string} filename - file name suggestion for downloading the video.\n * @param {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @param {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @param {Promise} urlPromise - array of two promises, which return URLs of video and preview uploads correspondingly\n * (either could be null).\n */\n\n/**\n * Insert inline image into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add video to.\n * @param {integer} at - index where the object is inserted. The length of the video is always 1.\n * @param {VideoDesc} videoDesc - object with video paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertVideo = function(content, at, videoDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'VD',\n data: {\n mime: videoDesc.mime,\n ref: videoDesc.refurl,\n val: videoDesc.bits,\n preref: videoDesc.preref,\n preview: videoDesc.preview,\n width: videoDesc.width,\n height: videoDesc.height,\n duration: videoDesc.duration | 0,\n name: videoDesc.filename,\n size: videoDesc.size | 0,\n }\n };\n\n if (videoDesc.urlPromise) {\n ex.data._tempPreview = videoDesc._tempPreview;\n ex.data._processing = true;\n videoDesc.urlPromise.then(\n urls => {\n ex.data.ref = urls[0];\n ex.data.preref = urls[1];\n ex.data._tempPreview = undefined;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * @typedef Drafty.AudioDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @param {string} refurl - reference to the content. Could be null/undefined.\n * @param {string} bits - base64-encoded audio content. Could be null/undefined.\n * @param {integer} duration - duration of the record in milliseconds.\n * @param {string} preview - base64 encoded short array of amplitude values 0..100.\n * @param {string} filename - file name suggestion for downloading the audio.\n * @param {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Insert audio recording into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add audio record to.\n * @param {integer} at - index where the object is inserted. The length of the record is always 1.\n * @param {AudioDesc} audioDesc - object with the audio paramenets and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertAudio = function(content, at, audioDesc) {\n content = content || {\n txt: ' '\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: 1,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'AU',\n data: {\n mime: audioDesc.mime,\n val: audioDesc.bits,\n duration: audioDesc.duration | 0,\n preview: audioDesc.preview,\n name: audioDesc.filename,\n size: audioDesc.size | 0,\n ref: audioDesc.refurl\n }\n };\n\n if (audioDesc.urlPromise) {\n ex.data._processing = true;\n audioDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n // Catch the error, otherwise it will appear in the console.\n ex.data._processing = undefined;\n }\n );\n }\n\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Create a (self-contained) video call Drafty document.\n * @memberof Drafty\n * @static\n * @param {boolean} audioOnly true if the call is initially audio-only.\n * @returns Video Call drafty document.\n */\nDrafty.videoCall = function(audioOnly) {\n const content = {\n txt: ' ',\n fmt: [{\n at: 0,\n len: 1,\n key: 0\n }],\n ent: [{\n tp: 'VC',\n data: {\n aonly: audioOnly\n },\n }]\n };\n return content;\n}\n\n/**\n * Update video call (VC) entity with the new status and duration.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - VC document to update.\n * @param {object} params - new video call parameters.\n * @param {string} params.state - state of video call.\n * @param {number} params.duration - duration of the video call in milliseconds.\n *\n * @returns the same document with update applied.\n */\nDrafty.updateVideoCall = function(content, params) {\n // The video element could be just a format or a format + entity.\n // Must ensure it's the latter first.\n const fmt = ((content || {}).fmt || [])[0];\n if (!fmt) {\n // Unrecognized content.\n return content;\n }\n\n let ent;\n if (fmt.tp == 'VC') {\n // Just a format, convert to format + entity.\n delete fmt.tp;\n fmt.key = 0;\n ent = {\n tp: 'VC'\n };\n content.ent = [ent];\n } else {\n ent = (content.ent || [])[fmt.key | 0];\n if (!ent || ent.tp != 'VC') {\n // Not a VC entity.\n return content;\n }\n }\n ent.data = ent.data || {};\n Object.assign(ent.data, params);\n return content;\n}\n\n/**\n * Create a quote to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {string} header - Quote header (title, etc.).\n * @param {string} uid - UID of the author to mention.\n * @param {Drafty} body - Body of the quoted message.\n *\n * @returns Reply quote Drafty doc with the quote formatting.\n */\nDrafty.quote = function(header, uid, body) {\n const quote = Drafty.append(Drafty.appendLineBreak(Drafty.mention(header, uid)), body);\n\n // Wrap into a quote.\n quote.fmt.push({\n at: 0,\n len: quote.txt.length,\n tp: 'QQ'\n });\n\n return quote;\n}\n\n/**\n * Create a Drafty document with a mention.\n *\n * @param {string} name - mentioned name.\n * @param {string} uid - mentioned user ID.\n *\n * @returns {Drafty} document with the mention.\n */\nDrafty.mention = function(name, uid) {\n return {\n txt: name || '',\n fmt: [{\n at: 0,\n len: (name || '').length,\n key: 0\n }],\n ent: [{\n tp: 'MN',\n data: {\n val: uid\n }\n }]\n };\n}\n\n/**\n * Append a link to a Drafty document.\n *\n * @param {Drafty} content - Drafty document to append link to.\n * @param {Object} linkData - Link info in format {txt: 'ankor text', url: 'http://...'}.\n *\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLink = function(content, linkData) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: content.txt.length,\n len: linkData.txt.length,\n key: content.ent.length\n });\n content.txt += linkData.txt;\n\n const ex = {\n tp: 'LN',\n data: {\n url: linkData.url\n }\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Append image to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add image to.\n * @param {ImageDesc} imageDesc - object with image paramenets.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendImage = function(content, imageDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertImage(content, content.txt.length - 1, imageDesc);\n}\n\n/**\n * Append audio recodring to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to add recording to.\n * @param {AudioDesc} audioDesc - object with audio data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendAudio = function(content, audioDesc) {\n content = content || {\n txt: ''\n };\n content.txt += ' ';\n return Drafty.insertAudio(content, content.txt.length - 1, audioDesc);\n}\n\n/**\n * @typedef Drafty.AttachmentDesc\n * @memberof Drafty\n * @type Object\n * @param {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @param {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @param {string} filename - file name suggestion for downloading the attachment.\n * @param {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @param {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @param {Promise} urlPromise - Promise which returns content URL when resolved.\n */\n\n/**\n * Attach file to Drafty content. Either as a blob or as a reference.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to attach file to.\n * @param {AttachmentDesc} object - containing attachment description and data.\n *\n * @return {Drafty} updated document.\n */\nDrafty.attachFile = function(content, attachmentDesc) {\n content = content || {\n txt: ''\n };\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n const ex = {\n tp: 'EX',\n data: {\n mime: attachmentDesc.mime,\n val: attachmentDesc.data,\n name: attachmentDesc.filename,\n ref: attachmentDesc.refurl,\n size: attachmentDesc.size | 0\n }\n }\n if (attachmentDesc.urlPromise) {\n ex.data._processing = true;\n attachmentDesc.urlPromise.then(\n url => {\n ex.data.ref = url;\n ex.data._processing = undefined;\n },\n _ => {\n /* catch the error, otherwise it will appear in the console. */\n ex.data._processing = undefined;\n }\n );\n }\n content.ent.push(ex);\n\n return content;\n}\n\n/**\n * Wraps drafty document into a simple formatting style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - document or string to wrap into a style.\n * @param {string} style - two-letter style to wrap into.\n * @param {number} at - index where the style starts, default 0.\n * @param {number} len - length of the form content, default all of it.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapInto = function(content, style, at, len) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at || 0,\n len: len || content.txt.length,\n tp: style,\n });\n\n return content;\n}\n\n/**\n * Wraps content into an interactive form.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - to wrap into a form.\n * @param {number} at - index where the forms starts.\n * @param {number} len - length of the form content.\n *\n * @return {Drafty} updated document.\n */\nDrafty.wrapAsForm = function(content, at, len) {\n return Drafty.wrapInto(content, 'FM', at, len);\n}\n\n/**\n * Insert clickable button into Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {number} at - location where the button is inserted.\n * @param {number} len - the length of the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.insertButton = function(content, at, len, name, actionType, actionValue, refUrl) {\n if (typeof content == 'string') {\n content = {\n txt: content\n };\n }\n\n if (!content || !content.txt || content.txt.length < at + len) {\n return null;\n }\n\n if (len <= 0 || ['url', 'pub'].indexOf(actionType) == -1) {\n return null;\n }\n // Ensure refUrl is a string.\n if (actionType == 'url' && !refUrl) {\n return null;\n }\n refUrl = '' + refUrl;\n\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: at | 0,\n len: len,\n key: content.ent.length\n });\n content.ent.push({\n tp: 'BN',\n data: {\n act: actionType,\n val: actionValue,\n ref: refUrl,\n name: name\n }\n });\n\n return content;\n}\n\n/**\n * Append clickable button to Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} content - Drafty document to insert button to or a string to be used as button text.\n * @param {string} title - the text to be used as button title.\n * @param {string} name - the button. Client should return it to the server when the button is clicked.\n * @param {string} actionType - the type of the button, one of 'url' or 'pub'.\n * @param {string} actionValue - the value to return on click:\n * @param {string} refUrl - the URL to go to when the 'url' button is clicked.\n *\n * @return {Drafty} updated document.\n */\nDrafty.appendButton = function(content, title, name, actionType, actionValue, refUrl) {\n content = content || {\n txt: ''\n };\n const at = content.txt.length;\n content.txt += title;\n return Drafty.insertButton(content, at, title.length, name, actionType, actionValue, refUrl);\n}\n\n/**\n * Attach a generic JS object. The object is attached as a json string.\n * Intended for representing a form response.\n *\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to attach file to.\n * @param {Object} data - data to convert to json string and attach.\n * @returns {Drafty} the same document as content.\n */\nDrafty.attachJSON = function(content, data) {\n content = content || {\n txt: ''\n };\n content.ent = content.ent || [];\n content.fmt = content.fmt || [];\n\n content.fmt.push({\n at: -1,\n len: 0,\n key: content.ent.length\n });\n\n content.ent.push({\n tp: 'EX',\n data: {\n mime: JSON_MIME_TYPE,\n val: data\n }\n });\n\n return content;\n}\n/**\n * Append line break to a Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - Drafty document to append linebreak to.\n * @returns {Drafty} the same document as content.\n */\nDrafty.appendLineBreak = function(content) {\n content = content || {\n txt: ''\n };\n content.fmt = content.fmt || [];\n content.fmt.push({\n at: content.txt.length,\n len: 1,\n tp: 'BR'\n });\n content.txt += ' ';\n\n return content;\n}\n/**\n * Given Drafty document, convert it to HTML.\n * No attempt is made to strip pre-existing html markup.\n * This is potentially unsafe because content.txt may contain malicious HTML\n * markup.\n * @memberof Tinode.Drafty\n * @static\n *\n * @param {Drafty} doc - document to convert.\n *\n * @returns {string} HTML-representation of content.\n */\nDrafty.UNSAFE_toHTML = function(doc) {\n const tree = draftyToTree(doc);\n const htmlFormatter = function(type, data, values) {\n const tag = DECORATORS[type];\n let result = values ? values.join('') : '';\n if (tag) {\n result = tag.open(data) + result + tag.close(data);\n }\n return result;\n };\n return treeBottomUp(tree, htmlFormatter, 0);\n}\n\n/**\n * Callback for applying custom formatting to a Drafty document.\n * Called once for each style span.\n * @memberof Drafty\n * @static\n *\n * @callback Formatter\n * @param {string} style - style code such as \"ST\" or \"IM\".\n * @param {Object} data - entity's data.\n * @param {Object} values - possibly styled subspans contained in this style span.\n * @param {number} index - index of the element guaranteed to be unique.\n */\n\n/**\n * Convert Drafty document to a representation suitable for display.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|Object} content - Drafty document to transform.\n * @param {Formatter} formatter - callback which formats individual elements.\n * @param {Object} context - context provided to formatter as this.\n *\n * @return {Object} transformed object\n */\nDrafty.format = function(original, formatter, context) {\n return treeBottomUp(draftyToTree(original), formatter, 0, [], context);\n}\n\n/**\n * Shorten Drafty document making the drafty text no longer than the limit.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characrets to shorten to.\n * @param {boolean} light - remove heavy data from entities.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.shorten = function(original, limit, light) {\n let tree = draftyToTree(original);\n tree = shortenTree(tree, limit, '…');\n if (tree && light) {\n tree = lightEntity(tree);\n }\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Transform Drafty doc for forwarding: strip leading @mention and any leading line breaks or whitespace.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.forwardedContent = function(original) {\n let tree = draftyToTree(original);\n const rmMention = function(node) {\n if (node.type == 'MN') {\n if (!node.parent || !node.parent.type) {\n return null;\n }\n }\n return node;\n }\n // Strip leading mention.\n tree = treeTopDown(tree, rmMention);\n // Remove leading whitespace.\n tree = lTrim(tree);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Prepare Drafty doc for wrapping into QQ as a reply:\n * - Replace forwarding mention with symbol '➦' and remove data (UID).\n * - Remove quoted text completely.\n * - Replace line breaks with spaces.\n * - Strip entities of heavy content.\n * - Move attachments to the end of the document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @returns converted Drafty object leaving the original intact.\n */\nDrafty.replyContent = function(original, limit) {\n const convMNnQQnBR = function(node) {\n if (node.type == 'QQ') {\n return null;\n } else if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n delete node.data;\n }\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.type;\n delete node.children;\n }\n return node;\n }\n\n let tree = draftyToTree(original);\n if (!tree) {\n return original;\n }\n\n // Strip leading mention.\n tree = treeTopDown(tree, convMNnQQnBR);\n // Move attachments to the end of the doc.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n // Shorten the doc.\n tree = shortenTree(tree, limit, '…');\n // Strip heavy elements except IM.data['val'] and VD.data['preview'] (have to keep them to generate previews later).\n const filter = node => {\n switch (node.type) {\n case 'IM':\n return ['val'];\n case 'VD':\n return ['preview'];\n }\n return null;\n };\n tree = lightEntity(tree, filter);\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n\n/**\n * Generate drafty preview:\n * - Shorten the document.\n * - Strip all heavy entity data leaving just inline styles and entity references.\n * - Replace line breaks with spaces.\n * - Replace content of QQ with a space.\n * - Replace forwarding mention with symbol '➦'.\n * move all attachments to the end of the document and make them visible.\n * The context may expose a function getFormatter(style). If it's available\n * it will call it to obtain a formatter for a subtree of styles under the style.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty|string} original - Drafty object to shorten.\n * @param {number} limit - length in characters to shorten to.\n * @param {boolean} forwarding - this a forwarding message preview.\n * @returns new shortened Drafty object leaving the original intact.\n */\nDrafty.preview = function(original, limit, forwarding) {\n let tree = draftyToTree(original);\n\n // Move attachments to the end.\n tree = attachmentsToEnd(tree, MAX_PREVIEW_ATTACHMENTS);\n\n // Convert leading mention to '➦' and replace QQ and BR with a space ' '.\n const convMNnQQnBR = function(node) {\n if (node.type == 'MN') {\n if ((!node.parent || !node.parent.type) && (node.text || '').startsWith('➦')) {\n node.text = '➦';\n delete node.children;\n }\n } else if (node.type == 'QQ') {\n node.text = ' ';\n delete node.children;\n } else if (node.type == 'BR') {\n node.text = ' ';\n delete node.children;\n delete node.type;\n }\n return node;\n }\n tree = treeTopDown(tree, convMNnQQnBR);\n\n tree = shortenTree(tree, limit, '…');\n if (forwarding) {\n // Keep some IM and VD data for preview.\n const filter = {\n IM: ['val'],\n VD: ['preview']\n };\n tree = lightEntity(tree, node => {\n return filter[node.type];\n });\n } else {\n tree = lightEntity(tree);\n }\n\n // Convert back to Drafty.\n return treeToDrafty({}, tree, []);\n}\n\n/**\n * Given Drafty document, convert it to plain text.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text.\n * @returns {string} plain-text representation of the drafty document.\n */\nDrafty.toPlainText = function(content) {\n return typeof content == 'string' ? content : content.txt;\n}\n\n/**\n * Check if the document has no markup and no entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for presence of markup.\n * @returns true is content is plain text, false otherwise.\n */\nDrafty.isPlainText = function(content) {\n return typeof content == 'string' || !(content.fmt || content.ent);\n}\n\n/**\n * Convert document to plain text with markdown. All elements which cannot\n * be represented in markdown are stripped.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to convert to plain text with markdown.\n */\nDrafty.toMarkdown = function(content) {\n let tree = draftyToTree(content);\n const mdFormatter = function(type, _, values) {\n const def = FORMAT_TAGS[type];\n let result = (values ? values.join('') : '');\n if (def) {\n if (def.isVoid) {\n result = def.md_tag || '';\n } else if (def.md_tag) {\n result = def.md_tag + result + def.md_tag;\n }\n }\n return result;\n };\n return treeBottomUp(tree, mdFormatter, 0);\n}\n\n/**\n * Checks if the object represets is a valid Drafty document.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - content to check for validity.\n * @returns true is content is valid, false otherwise.\n */\nDrafty.isValid = function(content) {\n if (!content) {\n return false;\n }\n\n const {\n txt,\n fmt,\n ent\n } = content;\n\n if (!txt && txt !== '' && !fmt && !ent) {\n return false;\n }\n\n const txt_type = typeof txt;\n if (txt_type != 'string' && txt_type != 'undefined' && txt !== null) {\n return false;\n }\n\n if (typeof fmt != 'undefined' && !Array.isArray(fmt) && fmt !== null) {\n return false;\n }\n\n if (typeof ent != 'undefined' && !Array.isArray(ent) && ent !== null) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if the drafty document has attachments: style EX and outside of normal rendering flow,\n * i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for attachments.\n * @returns true if there are attachments.\n */\nDrafty.hasAttachments = function(content) {\n if (!Array.isArray(content.fmt)) {\n return false;\n }\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n return ent && ent.tp == 'EX' && ent.data;\n }\n }\n return false;\n}\n\n/**\n * Callback for enumerating entities in a Drafty document.\n * Called once for each entity.\n * @memberof Drafty\n * @static\n *\n * @callback EntityCallback\n * @param {Object} data entity data.\n * @param {string} entity type.\n * @param {number} index entity's index in `content.ent`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate attachments: style EX and outside of normal rendering flow, i.e. at = -1.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to process for attachments.\n * @param {EntityCallback} callback - callback to call for each attachment.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.attachments = function(content, callback, context) {\n if (!Array.isArray(content.fmt)) {\n return;\n }\n let count = 0;\n for (let i in content.ent) {\n let fmt = content.fmt[i];\n if (fmt && fmt.at < 0) {\n const ent = content.ent[fmt.key | 0];\n if (ent && ent.tp == 'EX' && ent.data) {\n if (callback.call(context, ent.data, count++, 'EX')) {\n break;\n }\n }\n }\n };\n}\n\n/**\n * Check if the drafty document has entities.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document to check for entities.\n * @returns true if there are entities.\n */\nDrafty.hasEntities = function(content) {\n return content.ent && content.ent.length > 0;\n}\n\n/**\n * Enumerate entities. Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @param {EntityCallback} callback - callback to call for each entity.\n * @param {Object} context - value of \"this\" for callback.\n *\n */\nDrafty.entities = function(content, callback, context) {\n if (content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n if (content.ent[i]) {\n if (callback.call(context, content.ent[i].data, i, content.ent[i].tp)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Callback for enumerating styles (inline formats) in a Drafty document.\n * Called once for each style.\n * @memberof Drafty\n * @static\n *\n * @callback StyleCallback\n * @param {string} tp - format type.\n * @param {number} at - starting position of the format in text.\n * @param {number} len - extent of the format in characters.\n * @param {number} key - index of the entity if format is a reference.\n * @param {number} index - style's index in `content.fmt`.\n *\n * @return 'true-ish' to stop processing, 'false-ish' otherwise.\n */\n\n/**\n * Enumerate styles (inline formats). Enumeration stops if callback returns 'true'.\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with styles (formats) to enumerate.\n * @param {StyleCallback} callback - callback to call for each format.\n * @param {Object} context - value of \"this\" for callback.\n */\nDrafty.styles = function(content, callback, context) {\n if (content.fmt && content.fmt.length > 0) {\n for (let i in content.fmt) {\n const fmt = content.fmt[i];\n if (fmt) {\n if (callback.call(context, fmt.tp, fmt.at, fmt.len, fmt.key, i)) {\n break;\n }\n }\n }\n }\n}\n\n/**\n * Remove unrecognized fields from entity data\n * @memberof Drafty\n * @static\n *\n * @param {Drafty} content - document with entities to enumerate.\n * @returns content.\n */\nDrafty.sanitizeEntities = function(content) {\n if (content && content.ent && content.ent.length > 0) {\n for (let i in content.ent) {\n const ent = content.ent[i];\n if (ent && ent.data) {\n const data = copyEntData(ent.data);\n if (data) {\n content.ent[i].data = data;\n } else {\n delete content.ent[i].data;\n }\n }\n }\n }\n return content;\n}\n\n/**\n * Given the entity, get URL which can be used for downloading\n * entity data.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the URl from.\n * @returns {string} URL to download entity data or null.\n */\nDrafty.getDownloadUrl = function(entData) {\n let url = null;\n if (entData.mime != JSON_MIME_TYPE && entData.val) {\n url = base64toObjectUrl(entData.val, entData.mime, Drafty.logger);\n } else if (typeof entData.ref == 'string') {\n url = entData.ref;\n }\n return url;\n}\n\n/**\n * Check if the entity data is not ready for sending, such as being uploaded to the server.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n * @returns {boolean} true if upload is in progress, false otherwise.\n */\nDrafty.isProcessing = function(entData) {\n return !!entData._processing;\n}\n\n/**\n * Given the entity, get URL which can be used for previewing\n * the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entity.data to get the URl from.\n *\n * @returns {string} url for previewing or null if no such url is available.\n */\nDrafty.getPreviewUrl = function(entData) {\n return entData.val ? base64toObjectUrl(entData.val, entData.mime, Drafty.logger) : null;\n}\n\n/**\n * Get approximate size of the entity.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the size for.\n * @returns {number} size of entity data in bytes.\n */\nDrafty.getEntitySize = function(entData) {\n // Either size hint or length of value. The value is base64 encoded,\n // the actual object size is smaller than the encoded length.\n return entData.size ? entData.size : entData.val ? (entData.val.length * 0.75) | 0 : 0;\n}\n\n/**\n * Get entity mime type.\n * @memberof Drafty\n * @static\n *\n * @param {Object} entData - entity.data to get the type for.\n * @returns {string} mime type of entity.\n */\nDrafty.getEntityMimeType = function(entData) {\n return entData.mime || 'text/plain';\n}\n\n/**\n * Get HTML tag for a given two-letter style name.\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style, like ST or LN.\n *\n * @returns {string} HTML tag name if style is found, {code: undefined} if style is falsish or not found.\n */\nDrafty.tagName = function(style) {\n return FORMAT_TAGS[style] && FORMAT_TAGS[style].html_tag;\n}\n\n/**\n * For a given data bundle generate an object with HTML attributes,\n * for instance, given {url: \"http://www.example.com/\"} return\n * {href: \"http://www.example.com/\"}\n * @memberof Drafty\n * @static\n *\n * @param {string} style - two-letter style to generate attributes for.\n * @param {Object} data - data bundle to convert to attributes\n *\n * @returns {Object} object with HTML attributes.\n */\nDrafty.attrValue = function(style, data) {\n if (data && DECORATORS[style]) {\n return DECORATORS[style].props(data);\n }\n\n return undefined;\n}\n\n/**\n * Drafty MIME type.\n * @memberof Drafty\n * @static\n *\n * @returns {string} content-Type \"text/x-drafty\".\n */\nDrafty.getContentType = function() {\n return DRAFTY_MIME_TYPE;\n}\n\n// =================\n// Utility methods.\n// =================\n\n// Take a string and defined earlier style spans, re-compose them into a tree where each leaf is\n// a same-style (including unstyled) string. I.e. 'hello *bold _italic_* and ~more~ world' ->\n// ('hello ', (b: 'bold ', (i: 'italic')), ' and ', (s: 'more'), ' world');\n//\n// This is needed in order to clear markup, i.e. 'hello *world*' -> 'hello world' and convert\n// ranges from markup-ed offsets to plain text offsets.\nfunction chunkify(line, start, end, spans) {\n const chunks = [];\n\n if (spans.length == 0) {\n return [];\n }\n\n for (let i in spans) {\n // Get the next chunk from the queue\n const span = spans[i];\n\n // Grab the initial unstyled chunk\n if (span.at > start) {\n chunks.push({\n txt: line.slice(start, span.at)\n });\n }\n\n // Grab the styled chunk. It may include subchunks.\n const chunk = {\n tp: span.tp\n };\n const chld = chunkify(line, span.at + 1, span.end, span.children);\n if (chld.length > 0) {\n chunk.children = chld;\n } else {\n chunk.txt = span.txt;\n }\n chunks.push(chunk);\n start = span.end + 1; // '+1' is to skip the formatting character\n }\n\n // Grab the remaining unstyled chunk, after the last span\n if (start < end) {\n chunks.push({\n txt: line.slice(start, end)\n });\n }\n\n return chunks;\n}\n\n// Detect starts and ends of formatting spans. Unformatted spans are\n// ignored at this stage.\nfunction spannify(original, re_start, re_end, type) {\n const result = [];\n let index = 0;\n let line = original.slice(0); // make a copy;\n\n while (line.length > 0) {\n // match[0]; // match, like '*abc*'\n // match[1]; // match captured in parenthesis, like 'abc'\n // match['index']; // offset where the match started.\n\n // Find the opening token.\n const start = re_start.exec(line);\n if (start == null) {\n break;\n }\n\n // Because javascript RegExp does not support lookbehind, the actual offset may not point\n // at the markup character. Find it in the matched string.\n let start_offset = start['index'] + start[0].lastIndexOf(start[1]);\n // Clip the processed part of the string.\n line = line.slice(start_offset + 1);\n // start_offset is an offset within the clipped string. Convert to original index.\n start_offset += index;\n // Index now point to the beginning of 'line' within the 'original' string.\n index = start_offset + 1;\n\n // Find the matching closing token.\n const end = re_end ? re_end.exec(line) : null;\n if (end == null) {\n break;\n }\n let end_offset = end['index'] + end[0].indexOf(end[1]);\n // Clip the processed part of the string.\n line = line.slice(end_offset + 1);\n // Update offsets\n end_offset += index;\n // Index now points to the beginning of 'line' within the 'original' string.\n index = end_offset + 1;\n\n result.push({\n txt: original.slice(start_offset + 1, end_offset),\n children: [],\n at: start_offset,\n end: end_offset,\n tp: type\n });\n }\n\n return result;\n}\n\n// Convert linear array or spans into a tree representation.\n// Keep standalone and nested spans, throw away partially overlapping spans.\nfunction toSpanTree(spans) {\n if (spans.length == 0) {\n return [];\n }\n\n const tree = [spans[0]];\n let last = spans[0];\n for (let i = 1; i < spans.length; i++) {\n // Keep spans which start after the end of the previous span or those which\n // are complete within the previous span.\n if (spans[i].at > last.end) {\n // Span is completely outside of the previous span.\n tree.push(spans[i]);\n last = spans[i];\n } else if (spans[i].end <= last.end) {\n // Span is fully inside of the previous span. Push to subnode.\n last.children.push(spans[i]);\n }\n // Span could partially overlap, ignoring it as invalid.\n }\n\n // Recursively rearrange the subnodes.\n for (let i in tree) {\n tree[i].children = toSpanTree(tree[i].children);\n }\n\n return tree;\n}\n\n// Convert drafty document to a tree.\nfunction draftyToTree(doc) {\n if (!doc) {\n return null;\n }\n\n doc = (typeof doc == 'string') ? {\n txt: doc\n } : doc;\n let {\n txt,\n fmt,\n ent\n } = doc;\n\n txt = txt || '';\n if (!Array.isArray(ent)) {\n ent = [];\n }\n\n if (!Array.isArray(fmt) || fmt.length == 0) {\n if (ent.length == 0) {\n return {\n text: txt\n };\n }\n\n // Handle special case when all values in fmt are 0 and fmt therefore is skipped.\n fmt = [{\n at: 0,\n len: 0,\n key: 0\n }];\n }\n\n // Sanitize spans.\n const spans = [];\n const attachments = [];\n fmt.forEach((span) => {\n if (!span || typeof span != 'object') {\n return;\n }\n\n if (!['undefined', 'number'].includes(typeof span.at)) {\n // Present, but non-numeric 'at'.\n return;\n }\n if (!['undefined', 'number'].includes(typeof span.len)) {\n // Present, but non-numeric 'len'.\n return;\n }\n let at = span.at | 0;\n let len = span.len | 0;\n if (len < 0) {\n // Invalid span length.\n return;\n }\n\n let key = span.key || 0;\n if (ent.length > 0 && (typeof key != 'number' || key < 0 || key >= ent.length)) {\n // Invalid key value.\n return;\n }\n\n if (at <= -1) {\n // Attachment. Store attachments separately.\n attachments.push({\n start: -1,\n end: 0,\n key: key\n });\n return;\n } else if (at + len > txt.length) {\n // Span is out of bounds.\n return;\n }\n\n if (!span.tp) {\n if (ent.length > 0 && (typeof ent[key] == 'object')) {\n spans.push({\n start: at,\n end: at + len,\n key: key\n });\n }\n } else {\n spans.push({\n type: span.tp,\n start: at,\n end: at + len\n });\n }\n });\n\n // Sort spans first by start index (asc) then by length (desc), then by weight.\n spans.sort((a, b) => {\n let diff = a.start - b.start;\n if (diff != 0) {\n return diff;\n }\n diff = b.end - a.end;\n if (diff != 0) {\n return diff;\n }\n return FMT_WEIGHT.indexOf(b.type) - FMT_WEIGHT.indexOf(a.type);\n });\n\n // Move attachments to the end of the list.\n if (attachments.length > 0) {\n spans.push(...attachments);\n }\n\n spans.forEach((span) => {\n if (ent.length > 0 && !span.type && ent[span.key] && typeof ent[span.key] == 'object') {\n span.type = ent[span.key].tp;\n span.data = ent[span.key].data;\n }\n\n // Is type still undefined? Hide the invalid element!\n if (!span.type) {\n span.type = 'HD';\n }\n });\n\n let tree = spansToTree({}, txt, 0, txt.length, spans);\n\n // Flatten tree nodes.\n const flatten = function(node) {\n if (Array.isArray(node.children) && node.children.length == 1) {\n // Unwrap.\n const child = node.children[0];\n if (!node.type) {\n const parent = node.parent;\n node = child;\n node.parent = parent;\n } else if (!child.type && !child.children) {\n node.text = child.text;\n delete node.children;\n }\n }\n return node;\n }\n tree = treeTopDown(tree, flatten);\n\n return tree;\n}\n\n// Add tree node to a parent tree.\nfunction addNode(parent, n) {\n if (!n) {\n return parent;\n }\n\n if (!parent.children) {\n parent.children = [];\n }\n\n // If text is present, move it to a subnode.\n if (parent.text) {\n parent.children.push({\n text: parent.text,\n parent: parent\n });\n delete parent.text;\n }\n\n n.parent = parent;\n parent.children.push(n);\n\n return parent;\n}\n\n// Returns a tree of nodes.\nfunction spansToTree(parent, text, start, end, spans) {\n if (!spans || spans.length == 0) {\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n return parent;\n }\n\n // Process subspans.\n for (let i = 0; i < spans.length; i++) {\n const span = spans[i];\n if (span.start < 0 && span.type == 'EX') {\n addNode(parent, {\n type: span.type,\n data: span.data,\n key: span.key,\n att: true\n });\n continue;\n }\n\n // Add un-styled range before the styled span starts.\n if (start < span.start) {\n addNode(parent, {\n text: text.substring(start, span.start)\n });\n start = span.start;\n }\n\n // Get all spans which are within the current span.\n const subspans = [];\n while (i < spans.length - 1) {\n const inner = spans[i + 1];\n if (inner.start < 0) {\n // Attachments are in the end. Stop.\n break;\n } else if (inner.start < span.end) {\n if (inner.end <= span.end) {\n const tag = FORMAT_TAGS[inner.tp] || {};\n if (inner.start < inner.end || tag.isVoid) {\n // Valid subspan: completely within the current span and\n // either non-zero length or zero length is acceptable.\n subspans.push(inner);\n }\n }\n i++;\n // Overlapping subspans are ignored.\n } else {\n // Past the end of the current span. Stop.\n break;\n }\n }\n\n addNode(parent, spansToTree({\n type: span.type,\n data: span.data,\n key: span.key\n }, text, start, span.end, subspans));\n start = span.end;\n }\n\n // Add the last unformatted range.\n if (start < end) {\n addNode(parent, {\n text: text.substring(start, end)\n });\n }\n\n return parent;\n}\n\n// Append a tree to a Drafty doc.\nfunction treeToDrafty(doc, tree, keymap) {\n if (!tree) {\n return doc;\n }\n\n doc.txt = doc.txt || '';\n\n // Checkpoint to measure length of the current tree node.\n const start = doc.txt.length;\n\n if (tree.text) {\n doc.txt += tree.text;\n } else if (Array.isArray(tree.children)) {\n tree.children.forEach((c) => {\n treeToDrafty(doc, c, keymap);\n });\n }\n\n if (tree.type) {\n const len = doc.txt.length - start;\n doc.fmt = doc.fmt || [];\n if (Object.keys(tree.data || {}).length > 0) {\n doc.ent = doc.ent || [];\n const newKey = (typeof keymap[tree.key] == 'undefined') ? doc.ent.length : keymap[tree.key];\n keymap[tree.key] = newKey;\n doc.ent[newKey] = {\n tp: tree.type,\n data: tree.data\n };\n if (tree.att) {\n // Attachment.\n doc.fmt.push({\n at: -1,\n len: 0,\n key: newKey\n });\n } else {\n doc.fmt.push({\n at: start,\n len: len,\n key: newKey\n });\n }\n } else {\n doc.fmt.push({\n tp: tree.type,\n at: start,\n len: len\n });\n }\n }\n return doc;\n}\n\n// Traverse the tree top down transforming the nodes: apply transformer to every tree node.\nfunction treeTopDown(src, transformer, context) {\n if (!src) {\n return null;\n }\n\n let dst = transformer.call(context, src);\n if (!dst || !dst.children) {\n return dst;\n }\n\n const children = [];\n for (let i in dst.children) {\n let n = dst.children[i];\n if (n) {\n n = treeTopDown(n, transformer, context);\n if (n) {\n children.push(n);\n }\n }\n }\n\n if (children.length == 0) {\n dst.children = null;\n } else {\n dst.children = children;\n }\n\n return dst;\n}\n\n// Traverse the tree bottom-up: apply formatter to every node.\n// The formatter must maintain its state through context.\nfunction treeBottomUp(src, formatter, index, stack, context) {\n if (!src) {\n return null;\n }\n\n if (stack && src.type) {\n stack.push(src.type);\n }\n\n let values = [];\n for (let i in src.children) {\n const n = treeBottomUp(src.children[i], formatter, i, stack, context);\n if (n) {\n values.push(n);\n }\n }\n if (values.length == 0) {\n if (src.text) {\n values = [src.text];\n } else {\n values = null;\n }\n }\n\n if (stack && src.type) {\n stack.pop();\n }\n\n return formatter.call(context, src.type, src.data, values, index, stack);\n}\n\n// Clip tree to the provided limit.\nfunction shortenTree(tree, limit, tail) {\n if (!tree) {\n return null;\n }\n\n if (tail) {\n limit -= tail.length;\n }\n\n const shortener = function(node) {\n if (limit <= -1) {\n // Limit -1 means the doc was already clipped.\n return null;\n }\n\n if (node.att) {\n // Attachments are unchanged.\n return node;\n }\n if (limit == 0) {\n node.text = tail;\n limit = -1;\n } else if (node.text) {\n const len = node.text.length;\n if (len > limit) {\n node.text = node.text.substring(0, limit) + tail;\n limit = -1;\n } else {\n limit -= len;\n }\n }\n return node;\n }\n\n return treeTopDown(tree, shortener);\n}\n\n// Strip heavy entities from a tree.\nfunction lightEntity(tree, allow) {\n const lightCopy = node => {\n const data = copyEntData(node.data, true, allow ? allow(node) : null);\n if (data) {\n node.data = data;\n } else {\n delete node.data;\n }\n return node;\n }\n return treeTopDown(tree, lightCopy);\n}\n\n// Remove spaces and breaks on the left.\nfunction lTrim(tree) {\n if (tree.type == 'BR') {\n tree = null;\n } else if (tree.text) {\n if (!tree.type) {\n tree.text = tree.text.trimStart();\n if (!tree.text) {\n tree = null;\n }\n }\n } else if (!tree.type && tree.children && tree.children.length > 0) {\n const c = lTrim(tree.children[0]);\n if (c) {\n tree.children[0] = c;\n } else {\n tree.children.shift();\n if (!tree.type && tree.children.length == 0) {\n tree = null;\n }\n }\n }\n return tree;\n}\n\n// Move attachments to the end. Attachments must be at the top level, no need to traverse the tree.\nfunction attachmentsToEnd(tree, limit) {\n if (!tree) {\n return null;\n }\n\n if (tree.att) {\n tree.text = ' ';\n delete tree.att;\n delete tree.children;\n } else if (tree.children) {\n const attachments = [];\n const children = [];\n for (let i in tree.children) {\n const c = tree.children[i];\n if (c.att) {\n if (attachments.length == limit) {\n // Too many attachments to preview;\n continue;\n }\n if (c.data['mime'] == JSON_MIME_TYPE) {\n // JSON attachments are not shown in preview.\n continue;\n }\n\n delete c.att;\n delete c.children;\n c.text = ' ';\n attachments.push(c);\n } else {\n children.push(c);\n }\n }\n tree.children = children.concat(attachments);\n }\n return tree;\n}\n\n// Get a list of entities from a text.\nfunction extractEntities(line) {\n let match;\n let extracted = [];\n ENTITY_TYPES.forEach((entity) => {\n while ((match = entity.re.exec(line)) !== null) {\n extracted.push({\n offset: match['index'],\n len: match[0].length,\n unique: match[0],\n data: entity.pack(match[0]),\n type: entity.name\n });\n }\n });\n\n if (extracted.length == 0) {\n return extracted;\n }\n\n // Remove entities detected inside other entities, like #hashtag in a URL.\n extracted.sort((a, b) => {\n return a.offset - b.offset;\n });\n\n let idx = -1;\n extracted = extracted.filter((el) => {\n const result = (el.offset > idx);\n idx = el.offset + el.len;\n return result;\n });\n\n return extracted;\n}\n\n// Convert the chunks into format suitable for serialization.\nfunction draftify(chunks, startAt) {\n let plain = '';\n let ranges = [];\n for (let i in chunks) {\n const chunk = chunks[i];\n if (!chunk.txt) {\n const drafty = draftify(chunk.children, plain.length + startAt);\n chunk.txt = drafty.txt;\n ranges = ranges.concat(drafty.fmt);\n }\n\n if (chunk.tp) {\n ranges.push({\n at: plain.length + startAt,\n len: chunk.txt.length,\n tp: chunk.tp\n });\n }\n\n plain += chunk.txt;\n }\n return {\n txt: plain,\n fmt: ranges\n };\n}\n\n// Create a copy of entity data with (light=false) or without (light=true) the large payload.\n// The array 'allow' contains a list of fields exempt from stripping.\nfunction copyEntData(data, light, allow) {\n if (data && Object.entries(data).length > 0) {\n allow = allow || [];\n const dc = {};\n ALLOWED_ENT_FIELDS.forEach(key => {\n if (data[key]) {\n if (light && !allow.includes(key) &&\n (typeof data[key] == 'string' || Array.isArray(data[key])) &&\n data[key].length > MAX_PREVIEW_DATA_SIZE) {\n return;\n }\n if (typeof data[key] == 'object') {\n return;\n }\n dc[key] = data[key];\n }\n });\n\n if (Object.entries(dc).length != 0) {\n return dc;\n }\n }\n return null;\n}\n\nif (typeof module != 'undefined') {\n module.exports = Drafty;\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * @file Access control model.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\n/**\n * Helper class for handling access mode.\n *\n * @class AccessMode\n * @memberof Tinode\n *\n * @param {AccessMode|Object=} acs - AccessMode to copy or access mode object received from the server.\n */\nexport default class AccessMode {\n constructor(acs) {\n if (acs) {\n this.given = typeof acs.given == 'number' ? acs.given : AccessMode.decode(acs.given);\n this.want = typeof acs.want == 'number' ? acs.want : AccessMode.decode(acs.want);\n this.mode = acs.mode ? (typeof acs.mode == 'number' ? acs.mode : AccessMode.decode(acs.mode)) :\n (this.given & this.want);\n }\n }\n\n static #checkFlag(val, side, flag) {\n side = side || 'mode';\n if (['given', 'want', 'mode'].includes(side)) {\n return ((val[side] & flag) != 0);\n }\n throw new Error(`Invalid AccessMode component '${side}'`);\n }\n /**\n * Parse string into an access mode value.\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {string | Number} mode - either a String representation of the access mode to parse or a set of bits to assign.\n * @returns {number} - Access mode as a numeric value.\n */\n static decode(str) {\n if (!str) {\n return null;\n } else if (typeof str == 'number') {\n return str & AccessMode._BITMASK;\n } else if (str === 'N' || str === 'n') {\n return AccessMode._NONE;\n }\n\n const bitmask = {\n 'J': AccessMode._JOIN,\n 'R': AccessMode._READ,\n 'W': AccessMode._WRITE,\n 'P': AccessMode._PRES,\n 'A': AccessMode._APPROVE,\n 'S': AccessMode._SHARE,\n 'D': AccessMode._DELETE,\n 'O': AccessMode._OWNER\n };\n\n let m0 = AccessMode._NONE;\n\n for (let i = 0; i < str.length; i++) {\n const bit = bitmask[str.charAt(i).toUpperCase()];\n if (!bit) {\n // Unrecognized bit, skip.\n continue;\n }\n m0 |= bit;\n }\n return m0;\n }\n /**\n * Convert numeric representation of the access mode into a string.\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to convert to a string.\n * @returns {string} - Access mode as a string.\n */\n static encode(val) {\n if (val === null || val === AccessMode._INVALID) {\n return null;\n } else if (val === AccessMode._NONE) {\n return 'N';\n }\n\n const bitmask = ['J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'];\n let res = '';\n for (let i = 0; i < bitmask.length; i++) {\n if ((val & (1 << i)) != 0) {\n res = res + bitmask[i];\n }\n }\n return res;\n }\n /**\n * Update numeric representation of access mode with the new value. The value\n * is one of the following:\n * - a string starting with '+' or '-' then the bits to add or remove, e.g. '+R-W' or '-PS'.\n * - a new value of access mode\n *\n * @memberof Tinode.AccessMode\n * @static\n *\n * @param {number} val - access mode value to update.\n * @param {string} upd - update to apply to val.\n * @returns {number} - updated access mode.\n */\n static update(val, upd) {\n if (!upd || typeof upd != 'string') {\n return val;\n }\n\n let action = upd.charAt(0);\n if (action == '+' || action == '-') {\n let val0 = val;\n // Split delta-string like '+ABC-DEF+Z' into an array of parts including + and -.\n const parts = upd.split(/([-+])/);\n // Starting iteration from 1 because String.split() creates an array with the first empty element.\n // Iterating by 2 because we parse pairs +/- then data.\n for (let i = 1; i < parts.length - 1; i += 2) {\n action = parts[i];\n const m0 = AccessMode.decode(parts[i + 1]);\n if (m0 == AccessMode._INVALID) {\n return val;\n }\n if (m0 == null) {\n continue;\n }\n if (action === '+') {\n val0 |= m0;\n } else if (action === '-') {\n val0 &= ~m0;\n }\n }\n val = val0;\n } else {\n // The string is an explicit new value 'ABC' rather than delta.\n const val0 = AccessMode.decode(upd);\n if (val0 != AccessMode._INVALID) {\n val = val0;\n }\n }\n\n return val;\n }\n /**\n * Bits present in a1 but missing in a2.\n *\n * @static\n * @memberof Tinode\n *\n * @param {number | string} a1 - access mode to subtract from.\n * @param {number | string} a2 - access mode to subtract.\n * @returns {number} access mode with bits present in a1 but missing in a2.\n */\n static diff(a1, a2) {\n a1 = AccessMode.decode(a1);\n a2 = AccessMode.decode(a2);\n\n if (a1 == AccessMode._INVALID || a2 == AccessMode._INVALID) {\n return AccessMode._INVALID;\n }\n return a1 & ~a2;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Custom formatter\n */\n toString() {\n return '{\"mode\": \"' + AccessMode.encode(this.mode) +\n '\", \"given\": \"' + AccessMode.encode(this.given) +\n '\", \"want\": \"' + AccessMode.encode(this.want) + '\"}';\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Converts numeric values to strings.\n */\n jsonHelper() {\n return {\n mode: AccessMode.encode(this.mode),\n given: AccessMode.encode(this.given),\n want: AccessMode.encode(this.want)\n };\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign value to 'mode'.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} m - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setMode(m) {\n this.mode = AccessMode.decode(m);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update mode value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateMode(u) {\n this.mode = AccessMode.update(this.mode, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get mode value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - mode value.\n */\n getMode() {\n return AccessMode.encode(this.mode);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign given value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} g - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setGiven(g) {\n this.given = AccessMode.decode(g);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'given' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateGiven(u) {\n this.given = AccessMode.update(this.given, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'given' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - given value.\n */\n getGiven() {\n return AccessMode.encode(this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Assign 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string | Number} w - either a string representation of the access mode or a set of bits.\n * @returns {AccessMode} - this AccessMode.\n */\n setWant(w) {\n this.want = AccessMode.decode(w);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want' value.\n * @memberof Tinode.AccessMode\n *\n * @param {string} u - string representation of the changes to apply to access mode.\n * @returns {AccessMode} - this AccessMode.\n */\n updateWant(u) {\n this.want = AccessMode.update(this.want, u);\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get 'want' value as a string.\n * @memberof Tinode.AccessMode\n *\n * @returns {string} - want value.\n */\n getWant() {\n return AccessMode.encode(this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'want' but missing in 'given'.\n * Inverse of {@link Tinode.AccessMode#getExcessive}\n *\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in want but missing in given.\n */\n getMissing() {\n return AccessMode.encode(this.want & ~this.given);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Get permissions present in 'given' but missing in 'want'.\n * Inverse of {@link Tinode.AccessMode#getMissing}\n * @memberof Tinode.AccessMode\n *\n * @returns {string} permissions present in given but missing in want.\n */\n getExcessive() {\n return AccessMode.encode(this.given & ~this.want);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Update 'want', 'give', and 'mode' values.\n * @memberof Tinode.AccessMode\n *\n * @param {AccessMode} val - new access mode value.\n * @returns {AccessMode} - this AccessMode.\n */\n updateAll(val) {\n if (val) {\n this.updateGiven(val.given);\n this.updateWant(val.want);\n this.mode = this.given & this.want;\n }\n return this;\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Owner (O) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isOwner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._OWNER);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isPresencer(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._PRES);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Presence (P) flag is NOT set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isMuted(side) {\n return !this.isPresencer(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Join (J) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isJoiner(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._JOIN);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Reader (R) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isReader(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._READ);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Writer (W) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isWriter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._WRITE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Approver (A) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isApprover(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._APPROVE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O) or Approver (A) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isAdmin(side) {\n return this.isOwner(side) || this.isApprover(side);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if either one of Owner (O), Approver (A), or Sharer (S) flags is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isSharer(side) {\n return this.isAdmin(side) || AccessMode.#checkFlag(this, side, AccessMode._SHARE);\n }\n /**\n * AccessMode is a class representing topic access mode.\n *\n * @memberof Tinode\n * @class AccessMode\n */\n /**\n * Check if Deleter (D) flag is set.\n * @memberof Tinode.AccessMode\n * @param {string=} side - which permission to check: given, want, mode; default: mode.\n * @returns {boolean} - true if flag is set.\n */\n isDeleter(side) {\n return AccessMode.#checkFlag(this, side, AccessMode._DELETE);\n }\n}\n\nAccessMode._NONE = 0x00;\nAccessMode._JOIN = 0x01;\nAccessMode._READ = 0x02;\nAccessMode._WRITE = 0x04;\nAccessMode._PRES = 0x08;\nAccessMode._APPROVE = 0x10;\nAccessMode._SHARE = 0x20;\nAccessMode._DELETE = 0x40;\nAccessMode._OWNER = 0x80;\n\nAccessMode._BITMASK = AccessMode._JOIN | AccessMode._READ | AccessMode._WRITE | AccessMode._PRES |\n AccessMode._APPROVE | AccessMode._SHARE | AccessMode._DELETE | AccessMode._OWNER;\nAccessMode._INVALID = 0x100000;\n","export const PACKAGE_VERSION = \"0.21.0\";\n","/**\n * @file Global constants and configuration parameters.\n *\n * @copyright 2015-2023 Tinode LLC\n */\n'use strict';\n\nimport {\n PACKAGE_VERSION\n} from '../version.js';\n\n// Global constants\nexport const PROTOCOL_VERSION = '0'; // Major component of the version, e.g. '0' in '0.17.1'.\nexport const VERSION = PACKAGE_VERSION || '0.21';\nexport const LIBRARY = 'tinodejs/' + VERSION;\n\n// Topic name prefixes.\nexport const TOPIC_NEW = 'new';\nexport const TOPIC_NEW_CHAN = 'nch';\nexport const TOPIC_ME = 'me';\nexport const TOPIC_FND = 'fnd';\nexport const TOPIC_SYS = 'sys';\nexport const TOPIC_CHAN = 'chn';\nexport const TOPIC_GRP = 'grp';\nexport const TOPIC_P2P = 'p2p';\nexport const USER_NEW = 'new';\n\n// Starting value of a locally-generated seqId used for pending messages.\nexport const LOCAL_SEQID = 0xFFFFFFF;\n\n// Status codes.\nexport const MESSAGE_STATUS_NONE = 0; // Status not assigned.\nexport const MESSAGE_STATUS_QUEUED = 10; // Local ID assigned, in progress to be sent.\nexport const MESSAGE_STATUS_SENDING = 20; // Transmission started.\nexport const MESSAGE_STATUS_FAILED = 30; // At least one attempt was made to send the message.\nexport const MESSAGE_STATUS_FATAL = 40; // Message sending failed and it should not be retried.\nexport const MESSAGE_STATUS_SENT = 50; // Delivered to the server.\nexport const MESSAGE_STATUS_RECEIVED = 60; // Received by the client.\nexport const MESSAGE_STATUS_READ = 70; // Read by the user.\nexport const MESSAGE_STATUS_TO_ME = 80; // The message is received from another user.\n\n// Reject unresolved futures after this many milliseconds.\nexport const EXPIRE_PROMISES_TIMEOUT = 5_000;\n// Periodicity of garbage collection of unresolved futures.\nexport const EXPIRE_PROMISES_PERIOD = 1_000;\n\n// Delay before acknowledging that a message was recived.\nexport const RECV_TIMEOUT = 100;\n\n// Default number of messages to pull into memory from persistent cache.\nexport const DEFAULT_MESSAGES_PAGE = 24;\n\n// Unicode DEL character indicating data was deleted.\nexport const DEL_CHAR = '\\u2421';\n","/**\n * @file Throwable error with numeric error code.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nexport default class CommError extends Error {\n constructor(message, code) {\n super(`${message} (${code})`);\n this.name = 'CommError';\n this.code = code;\n }\n}\n","/**\n * @file Utilities used in multiple places.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport {\n DEL_CHAR\n} from './config.js';\n\n// Attempt to convert date and AccessMode strings to objects.\nexport function jsonParseHelper(key, val) {\n // Try to convert string timestamps with optional milliseconds to Date,\n // e.g. 2015-09-02T01:45:43[.123]Z\n if (typeof val == 'string' && val.length >= 20 && val.length <= 24 && ['ts', 'touched', 'updated', 'created', 'when', 'deleted', 'expires'].includes(key)) {\n const date = new Date(val);\n if (!isNaN(date)) {\n return date;\n }\n } else if (key === 'acs' && typeof val === 'object') {\n return new AccessMode(val);\n }\n return val;\n}\n\n// Checks if URL is a relative url, i.e. has no 'scheme://', including the case of missing scheme '//'.\n// The scheme is expected to be RFC-compliant, e.g. [a-z][a-z0-9+.-]*\n// example.html - ok\n// https:example.com - not ok.\n// http:/example.com - not ok.\n// ' ↲ https://example.com' - not ok. (↲ means carriage return)\nexport function isUrlRelative(url) {\n return url && !/^\\s*([a-z][a-z0-9+.-]*:|\\/\\/)/im.test(url);\n}\n\nfunction isValidDate(d) {\n return (d instanceof Date) && !isNaN(d) && (d.getTime() != 0);\n}\n\n// RFC3339 formater of Date\nexport function rfc3339DateString(d) {\n if (!isValidDate(d)) {\n return undefined;\n }\n\n const pad = function(val, sp) {\n sp = sp || 2;\n return '0'.repeat(sp - ('' + val).length) + val;\n };\n\n const millis = d.getUTCMilliseconds();\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +\n 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) +\n (millis ? '.' + pad(millis, 3) : '') + 'Z';\n}\n\n// Recursively merge src's own properties to dst.\n// Ignore properties where ignore[property] is true.\n// Array and Date objects are shallow-copied.\nexport function mergeObj(dst, src, ignore) {\n if (typeof src != 'object') {\n if (src === undefined) {\n return dst;\n }\n if (src === DEL_CHAR) {\n return undefined;\n }\n return src;\n }\n // JS is crazy: typeof null is 'object'.\n if (src === null) {\n return src;\n }\n\n // Handle Date\n if (src instanceof Date && !isNaN(src)) {\n return (!dst || !(dst instanceof Date) || isNaN(dst) || dst < src) ? src : dst;\n }\n\n // Access mode\n if (src instanceof AccessMode) {\n return new AccessMode(src);\n }\n\n // Handle Array\n if (src instanceof Array) {\n return src;\n }\n\n if (!dst || dst === DEL_CHAR) {\n dst = src.constructor();\n }\n\n for (let prop in src) {\n if (src.hasOwnProperty(prop) && (!ignore || !ignore[prop]) && (prop != '_noForwarding')) {\n try {\n dst[prop] = mergeObj(dst[prop], src[prop]);\n } catch (err) {\n // FIXME: probably need to log something here.\n }\n }\n }\n return dst;\n}\n\n// Update object stored in a cache. Returns updated value.\nexport function mergeToCache(cache, key, newval, ignore) {\n cache[key] = mergeObj(cache[key], newval, ignore);\n return cache[key];\n}\n\n// Strips all values from an object of they evaluate to false or if their name starts with '_'.\n// Used on all outgoing object before serialization to string.\nexport function simplify(obj) {\n Object.keys(obj).forEach((key) => {\n if (key[0] == '_') {\n // Strip fields like \"obj._key\".\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (Array.isArray(obj[key]) && obj[key].length == 0) {\n // Strip empty arrays.\n delete obj[key];\n } else if (!obj[key]) {\n // Strip fields which evaluate to false.\n delete obj[key];\n } else if (obj[key] instanceof Date) {\n // Strip invalid or zero date.\n if (!isValidDate(obj[key])) {\n delete obj[key];\n }\n } else if (typeof obj[key] == 'object') {\n simplify(obj[key]);\n // Strip empty objects.\n if (Object.getOwnPropertyNames(obj[key]).length == 0) {\n delete obj[key];\n }\n }\n });\n return obj;\n};\n\n\n// Trim whitespace, strip empty and duplicate elements elements.\n// If the result is an empty array, add a single element \"\\u2421\" (Unicode Del character).\nexport function normalizeArray(arr) {\n let out = [];\n if (Array.isArray(arr)) {\n // Trim, throw away very short and empty tags.\n for (let i = 0, l = arr.length; i < l; i++) {\n let t = arr[i];\n if (t) {\n t = t.trim().toLowerCase();\n if (t.length > 1) {\n out.push(t);\n }\n }\n }\n out.sort().filter(function(item, pos, ary) {\n return !pos || item != ary[pos - 1];\n });\n }\n if (out.length == 0) {\n // Add single tag with a Unicode Del character, otherwise an ampty array\n // is ambiguos. The Del tag will be stripped by the server.\n out.push(DEL_CHAR);\n }\n return out;\n}\n","/**\n * @file Abstraction layer for websocket and long polling connections.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n jsonParseHelper\n} from './utils.js';\n\nlet WebSocketProvider;\nlet XHRProvider;\n\n// Error code to return in case of a network problem.\nconst NETWORK_ERROR = 503;\nconst NETWORK_ERROR_TEXT = \"Connection failed\";\n\n// Error code to return when user disconnected from server.\nconst NETWORK_USER = 418;\nconst NETWORK_USER_TEXT = \"Disconnected by client\";\n\n// Settings for exponential backoff\nconst _BOFF_BASE = 2000; // 2000 milliseconds, minimum delay between reconnects\nconst _BOFF_MAX_ITER = 10; // Maximum delay between reconnects 2^10 * 2000 ~ 34 minutes\nconst _BOFF_JITTER = 0.3; // Add random delay\n\n// Helper function for creating an endpoint URL.\nfunction makeBaseUrl(host, protocol, version, apiKey) {\n let url = null;\n\n if (['http', 'https', 'ws', 'wss'].includes(protocol)) {\n url = `${protocol}://${host}`;\n if (url.charAt(url.length - 1) !== '/') {\n url += '/';\n }\n url += 'v' + version + '/channels';\n if (['http', 'https'].includes(protocol)) {\n // Long polling endpoint ends with \"lp\", i.e.\n // '/v0/channels/lp' vs just '/v0/channels' for ws\n url += '/lp';\n }\n url += '?apikey=' + apiKey;\n }\n return url;\n}\n\n/**\n * An abstraction for a websocket or a long polling connection.\n *\n * @class Connection\n * @memberof Tinode\n\n * @param {Object} config - configuration parameters.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - Network transport to use, either \"ws\"/\"wss\" for websocket or\n * lp for long polling.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} version_ - Major value of the protocol version, e.g. '0' in '0.17.1'.\n * @param {boolean} autoreconnect_ - If connection is lost, try to reconnect automatically.\n */\nexport default class Connection {\n // Logger, does nothing by default.\n static #log = _ => {};\n\n #boffTimer = null;\n #boffIteration = 0;\n #boffClosed = false; // Indicator if the socket was manually closed - don't autoreconnect if true.\n\n // Websocket.\n #socket = null;\n\n host;\n secure;\n apiKey;\n\n version;\n autoreconnect;\n\n initialized;\n\n // (config.host, config.apiKey, config.transport, config.secure), PROTOCOL_VERSION, true\n constructor(config, version_, autoreconnect_) {\n this.host = config.host;\n this.secure = config.secure;\n this.apiKey = config.apiKey;\n\n this.version = version_;\n this.autoreconnect = autoreconnect_;\n\n if (config.transport === 'lp') {\n // explicit request to use long polling\n this.#init_lp();\n this.initialized = 'lp';\n } else if (config.transport === 'ws') {\n // explicit request to use web socket\n // if websockets are not available, horrible things will happen\n this.#init_ws();\n this.initialized = 'ws';\n }\n\n if (!this.initialized) {\n // Invalid or undefined network transport.\n Connection.#log(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n throw new Error(\"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.\");\n }\n }\n\n /**\n * To use Connection in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n * @memberof Connection\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n }\n\n /**\n * Assign a non-default logger.\n * @static\n * @memberof Connection\n * @param {function} l variadic logging function.\n */\n static set logger(l) {\n Connection.#log = l;\n }\n\n /**\n * Initiate a new connection\n * @memberof Tinode.Connection#\n * @param {string} host_ Host name to connect to; if null the old host name will be used.\n * @param {boolean} force Force new connection even if one already exists.\n * @return {Promise} Promise resolved/rejected when the connection call completes, resolution is called without\n * parameters, rejection passes the {Error} as parameter.\n */\n connect(host_, force) {\n return Promise.reject(null);\n }\n\n /**\n * Try to restore a network connection, also reset backoff.\n * @memberof Tinode.Connection#\n *\n * @param {boolean} force - reconnect even if there is a live connection already.\n */\n reconnect(force) {}\n\n /**\n * Terminate the network connection\n * @memberof Tinode.Connection#\n */\n disconnect() {}\n\n /**\n * Send a string to the server.\n * @memberof Tinode.Connection#\n *\n * @param {string} msg - String to send.\n * @throws Throws an exception if the underlying connection is not live.\n */\n sendText(msg) {}\n\n /**\n * Check if connection is alive.\n * @memberof Tinode.Connection#\n * @returns {boolean} true if connection is live, false otherwise.\n */\n isConnected() {\n return false;\n }\n\n /**\n * Get the name of the current network transport.\n * @memberof Tinode.Connection#\n * @returns {string} name of the transport such as \"ws\" or \"lp\".\n */\n transport() {\n return this.initialized;\n }\n\n /**\n * Send network probe to check if connection is indeed live.\n * @memberof Tinode.Connection#\n */\n probe() {\n this.sendText('1');\n }\n\n /**\n * Reset autoreconnect counter to zero.\n * @memberof Tinode.Connection#\n */\n backoffReset() {\n this.#boffReset();\n }\n\n // Backoff implementation - reconnect after a timeout.\n #boffReconnect() {\n // Clear timer\n clearTimeout(this.#boffTimer);\n // Calculate when to fire the reconnect attempt\n const timeout = _BOFF_BASE * (Math.pow(2, this.#boffIteration) * (1.0 + _BOFF_JITTER * Math.random()));\n // Update iteration counter for future use\n this.#boffIteration = (this.#boffIteration >= _BOFF_MAX_ITER ? this.#boffIteration : this.#boffIteration + 1);\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout);\n }\n\n this.#boffTimer = setTimeout(_ => {\n Connection.#log(`Reconnecting, iter=${this.#boffIteration}, timeout=${timeout}`);\n // Maybe the socket was closed while we waited for the timer?\n if (!this.#boffClosed) {\n const prom = this.connect();\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(0, prom);\n } else {\n // Suppress error if it's not used.\n prom.catch(_ => {\n /* do nothing */\n });\n }\n } else if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(-1);\n }\n }, timeout);\n }\n\n // Terminate auto-reconnect process.\n #boffStop() {\n clearTimeout(this.#boffTimer);\n this.#boffTimer = null;\n }\n\n // Reset auto-reconnect iteration counter.\n #boffReset() {\n this.#boffIteration = 0;\n }\n\n // Initialization for long polling.\n #init_lp() {\n const XDR_UNSENT = 0; // Client has been created. open() not called yet.\n const XDR_OPENED = 1; // open() has been called.\n const XDR_HEADERS_RECEIVED = 2; // send() has been called, and headers and status are available.\n const XDR_LOADING = 3; // Downloading; responseText holds partial data.\n const XDR_DONE = 4; // The operation is complete.\n\n // Fully composed endpoint URL, with API key & SID\n let _lpURL = null;\n\n let _poller = null;\n let _sender = null;\n\n let lp_sender = (url_) => {\n const sender = new XHRProvider();\n sender.onreadystatechange = (evt) => {\n if (sender.readyState == XDR_DONE && sender.status >= 400) {\n // Some sort of error response\n throw new CommError(\"LP sender failed\", sender.status);\n }\n };\n\n sender.open('POST', url_, true);\n return sender;\n }\n\n let lp_poller = (url_, resolve, reject) => {\n let poller = new XHRProvider();\n let promiseCompleted = false;\n\n poller.onreadystatechange = evt => {\n if (poller.readyState == XDR_DONE) {\n if (poller.status == 201) { // 201 == HTTP.Created, get SID\n let pkt = JSON.parse(poller.responseText, jsonParseHelper);\n _lpURL = url_ + '&sid=' + pkt.ctrl.params.sid;\n poller = lp_poller(_lpURL);\n poller.send(null);\n if (this.onOpen) {\n this.onOpen();\n }\n\n if (resolve) {\n promiseCompleted = true;\n resolve();\n }\n\n if (this.autoreconnect) {\n this.#boffStop();\n }\n } else if (poller.status > 0 && poller.status < 400) { // 0 = network error; 400 = HTTP.BadRequest\n if (this.onMessage) {\n this.onMessage(poller.responseText);\n }\n poller = lp_poller(_lpURL);\n poller.send(null);\n } else {\n // Don't throw an error here, gracefully handle server errors\n if (reject && !promiseCompleted) {\n promiseCompleted = true;\n reject(poller.responseText);\n }\n if (this.onMessage && poller.responseText) {\n this.onMessage(poller.responseText);\n }\n if (this.onDisconnect) {\n const code = poller.status || (this.#boffClosed ? NETWORK_USER : NETWORK_ERROR);\n const text = poller.responseText || (this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT);\n this.onDisconnect(new CommError(text, code), code);\n }\n\n // Polling has stopped. Indicate it by setting poller to null.\n poller = null;\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n }\n }\n };\n // Using POST to avoid caching response by service worker.\n poller.open('POST', url_, true);\n return poller;\n }\n\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (_poller) {\n if (!force) {\n return Promise.resolve();\n }\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'https' : 'http', this.version, this.apiKey);\n Connection.#log(\"LP connecting to:\", url);\n _poller = lp_poller(url, resolve, reject);\n _poller.send(null);\n }).catch(err => {\n Connection.#log(\"LP connection failed:\", err);\n });\n };\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (_sender) {\n _sender.onreadystatechange = undefined;\n _sender.abort();\n _sender = null;\n }\n if (_poller) {\n _poller.onreadystatechange = undefined;\n _poller.abort();\n _poller = null;\n }\n\n if (this.onDisconnect) {\n this.onDisconnect(new CommError(NETWORK_USER_TEXT, NETWORK_USER), NETWORK_USER);\n }\n // Ensure it's reconstructed\n _lpURL = null;\n };\n\n this.sendText = (msg) => {\n _sender = lp_sender(_lpURL);\n if (_sender && (_sender.readyState == XDR_OPENED)) { // 1 == OPENED\n _sender.send(msg);\n } else {\n throw new Error(\"Long poller failed to connect\");\n }\n };\n\n this.isConnected = _ => {\n return (_poller && true);\n };\n }\n\n // Initialization for Websocket\n #init_ws() {\n this.connect = (host_, force) => {\n this.#boffClosed = false;\n\n if (this.#socket) {\n if (!force && this.#socket.readyState == this.#socket.OPEN) {\n return Promise.resolve();\n }\n this.#socket.close();\n this.#socket = null;\n }\n\n if (host_) {\n this.host = host_;\n }\n\n return new Promise((resolve, reject) => {\n const url = makeBaseUrl(this.host, this.secure ? 'wss' : 'ws', this.version, this.apiKey);\n\n Connection.#log(\"WS connecting to: \", url);\n\n // It throws when the server is not accessible but the exception cannot be caught:\n // https://stackoverflow.com/questions/31002592/javascript-doesnt-catch-error-in-websocket-instantiation/31003057\n const conn = new WebSocketProvider(url);\n\n conn.onerror = err => {\n reject(err);\n };\n\n conn.onopen = _ => {\n if (this.autoreconnect) {\n this.#boffStop();\n }\n\n if (this.onOpen) {\n this.onOpen();\n }\n\n resolve();\n };\n\n conn.onclose = _ => {\n this.#socket = null;\n\n if (this.onDisconnect) {\n const code = this.#boffClosed ? NETWORK_USER : NETWORK_ERROR;\n this.onDisconnect(new CommError(this.#boffClosed ? NETWORK_USER_TEXT : NETWORK_ERROR_TEXT, code), code);\n }\n\n if (!this.#boffClosed && this.autoreconnect) {\n this.#boffReconnect();\n }\n };\n\n conn.onmessage = evt => {\n if (this.onMessage) {\n this.onMessage(evt.data);\n }\n };\n\n this.#socket = conn;\n });\n }\n\n this.reconnect = force => {\n this.#boffStop();\n this.connect(null, force);\n };\n\n this.disconnect = _ => {\n this.#boffClosed = true;\n this.#boffStop();\n\n if (!this.#socket) {\n return;\n }\n this.#socket.close();\n this.#socket = null;\n };\n\n this.sendText = msg => {\n if (this.#socket && (this.#socket.readyState == this.#socket.OPEN)) {\n this.#socket.send(msg);\n } else {\n throw new Error(\"Websocket is not connected\");\n }\n };\n\n this.isConnected = _ => {\n return (this.#socket && (this.#socket.readyState == this.#socket.OPEN));\n };\n }\n\n // Callbacks:\n\n /**\n * A callback to pass incoming messages to. See {@link Tinode.Connection#onMessage}.\n * @callback Tinode.Connection.OnMessage\n * @memberof Tinode.Connection\n * @param {string} message - Message to process.\n */\n onMessage = undefined;\n\n /**\n * A callback for reporting a dropped connection.\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onDisconnect = undefined;\n\n /**\n * A callback called when the connection is ready to be used for sending. For websockets it's socket open,\n * for long polling it's readyState=1 (OPENED)\n * @type {function}\n * @memberof Tinode.Connection#\n */\n onOpen = undefined;\n\n /**\n * A callback to notify of reconnection attempts. See {@link Tinode.Connection#onAutoreconnectIteration}.\n * @memberof Tinode.Connection\n * @callback AutoreconnectIterationType\n * @param {string} timeout - time till the next reconnect attempt in milliseconds. -1 means reconnect was skipped.\n * @param {Promise} promise resolved or rejected when the reconnect attemp completes.\n *\n */\n /**\n * A callback to inform when the next attampt to reconnect will happen and to receive connection promise.\n * @memberof Tinode.Connection#\n * @type {Tinode.Connection.AutoreconnectIterationType}\n */\n onAutoreconnectIteration = undefined;\n}\n\nConnection.NETWORK_ERROR = NETWORK_ERROR;\nConnection.NETWORK_ERROR_TEXT = NETWORK_ERROR_TEXT;\nConnection.NETWORK_USER = NETWORK_USER;\nConnection.NETWORK_USER_TEXT = NETWORK_USER_TEXT;\n","/**\n * @file Helper methods for dealing with IndexedDB cache of messages, users, and topics.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nconst DB_VERSION = 1;\nconst DB_NAME = 'tinode-web';\n\nlet IDBProvider;\n\nexport default class DB {\n #onError = _ => {};\n #logger = _ => {};\n\n // Instance of IndexDB.\n db = null;\n // Indicator that the cache is disabled.\n disabled = false;\n\n constructor(onError, logger) {\n this.#onError = onError || this.#onError;\n this.#logger = logger || this.#logger;\n }\n\n #mapObjects(source, callback, context) {\n if (!this.db) {\n return disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction([source]);\n trx.onerror = event => {\n this.#logger('PCache', 'mapObjects', source, event.target.error);\n reject(event.target.error);\n };\n trx.objectStore(source).getAll().onsuccess = event => {\n if (callback) {\n event.target.result.forEach(topic => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n /**\n * Initialize persistent cache: open or create/upgrade if needed.\n * @returns {Promise} promise to be resolved/rejected when the DB is initialized.\n */\n initDatabase() {\n return new Promise((resolve, reject) => {\n // Open the database and initialize callbacks.\n const req = IDBProvider.open(DB_NAME, DB_VERSION);\n req.onsuccess = event => {\n this.db = event.target.result;\n this.disabled = false;\n resolve(this.db);\n };\n req.onerror = event => {\n this.#logger('PCache', \"failed to initialize\", event);\n reject(event.target.error);\n this.#onError(event.target.error);\n };\n req.onupgradeneeded = event => {\n this.db = event.target.result;\n\n this.db.onerror = event => {\n this.#logger('PCache', \"failed to create storage\", event);\n this.#onError(event.target.error);\n };\n\n // Individual object stores.\n // Object store (table) for topics. The primary key is topic name.\n this.db.createObjectStore('topic', {\n keyPath: 'name'\n });\n\n // Users object store. UID is the primary key.\n this.db.createObjectStore('user', {\n keyPath: 'uid'\n });\n\n // Subscriptions object store topic <-> user. Topic name + UID is the primary key.\n this.db.createObjectStore('subscription', {\n keyPath: ['topic', 'uid']\n });\n\n // Messages object store. The primary key is topic name + seq.\n this.db.createObjectStore('message', {\n keyPath: ['topic', 'seq']\n });\n };\n });\n }\n\n /**\n * Delete persistent cache.\n */\n deleteDatabase() {\n // Close connection, otherwise operations will fail with 'onblocked'.\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n return new Promise((resolve, reject) => {\n const req = IDBProvider.deleteDatabase(DB_NAME);\n req.onblocked = _ => {\n if (this.db) {\n this.db.close();\n }\n const err = new Error(\"blocked\");\n this.#logger('PCache', 'deleteDatabase', err);\n reject(err);\n };\n req.onsuccess = _ => {\n this.db = null;\n this.disabled = true;\n resolve(true);\n };\n req.onerror = event => {\n this.#logger('PCache', 'deleteDatabase', event.target.error);\n reject(event.target.error);\n };\n });\n }\n\n /**\n * Check if persistent cache is ready for use.\n * @memberOf DB\n * @returns {boolean} true if cache is ready, false otherwise.\n */\n isReady() {\n return !!this.db;\n }\n\n // Topics.\n\n /**\n * Save to cache or update topic in persistent cache.\n * @memberOf DB\n * @param {Topic} topic - topic to be added or updated.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updTopic(topic) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updTopic', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(topic.name);\n req.onsuccess = _ => {\n trx.objectStore('topic').put(DB.#serializeTopic(req.result, topic));\n trx.commit();\n };\n });\n }\n\n /**\n * Mark or unmark topic as deleted.\n * @memberOf DB\n * @param {string} name - name of the topic to mark or unmark.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n markTopicAsDeleted(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'markTopicAsDeleted', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('topic').get(name);\n req.onsuccess = event => {\n const topic = event.target.result;\n topic._deleted = true;\n trx.objectStore('topic').put(topic);\n trx.commit();\n };\n });\n }\n\n /**\n * Remove topic from persistent cache.\n * @memberOf DB\n * @param {string} name - name of the topic to remove from database.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remTopic(name) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['topic', 'subscription', 'message'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remTopic', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('topic').delete(IDBKeyRange.only(name));\n trx.objectStore('subscription').delete(IDBKeyRange.bound([name, '-'], [name, '~']));\n trx.objectStore('message').delete(IDBKeyRange.bound([name, 0], [name, Number.MAX_SAFE_INTEGER]));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored topic.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapTopics(callback, context) {\n return this.#mapObjects('topic', callback, context);\n }\n\n /**\n * Copy data from serialized object to topic.\n * @memberOf DB\n * @param {Topic} topic - target to deserialize to.\n * @param {Object} src - serialized data to copy from.\n */\n deserializeTopic(topic, src) {\n DB.#deserializeTopic(topic, src);\n }\n\n // Users.\n /**\n * Add or update user object in the persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to save or update.\n * @param {Object} pub - user's public information.\n * @returns {Promise} promise resolved/rejected on operation completion.\n */\n updUser(uid, pub) {\n if (arguments.length < 2 || pub === undefined) {\n // No point inupdating user with invalid data.\n return;\n }\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').put({\n uid: uid,\n public: pub\n });\n trx.commit();\n });\n }\n\n /**\n * Remove user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to remove from the cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'remUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').delete(IDBKeyRange.only(uid));\n trx.commit();\n });\n }\n\n /**\n * Execute a callback for each stored user.\n * @memberOf DB\n * @param {function} callback - function to call for each topic.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapUsers(callback, context) {\n return this.#mapObjects('user', callback, context);\n }\n\n /**\n * Read a single user from persistent cache.\n * @memberOf DB\n * @param {string} uid - ID of the user to fetch from cache.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n getUser(uid) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['user']);\n trx.oncomplete = event => {\n const user = event.target.result;\n resolve({\n user: user.uid,\n public: user.public\n });\n };\n trx.onerror = event => {\n this.#logger('PCache', 'getUser', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('user').get(uid);\n });\n }\n\n // Subscriptions.\n /**\n * Add or update subscription in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {string} uid - ID of the subscribed user.\n * @param {Object} sub - subscription to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updSubscription(topicName, uid, sub) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription'], 'readwrite');\n trx.oncomplete = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updSubscription', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').get([topicName, uid]).onsuccess = (event) => {\n trx.objectStore('subscription').put(DB.#serializeSubscription(event.target.result, topicName, uid, sub));\n trx.commit();\n };\n });\n }\n\n /**\n * Execute a callback for each cached subscription in a given topic.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the subscriptions.\n * @param {function} callback - function to call for each subscription.\n * @param {Object} context - the value or this inside the callback.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n mapSubscriptions(topicName, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['subscription']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'mapSubscriptions', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('subscription').getAll(IDBKeyRange.bound([topicName, '-'], [topicName, '~'])).onsuccess = (event) => {\n if (callback) {\n event.target.result.forEach((topic) => {\n callback.call(context, topic);\n });\n }\n resolve(event.target.result);\n };\n });\n }\n\n // Messages.\n\n /**\n * Save message to persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {Object} msg - message to save.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n addMessage(msg) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'addMessage', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').add(DB.#serializeMessage(null, msg));\n trx.commit();\n });\n }\n\n /**\n * Update delivery status of a message stored in persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} seq - ID of the message to update\n * @param {number} status - new delivery status of the message.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n updMessageStatus(topicName, seq, status) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = event => {\n resolve(event.target.result);\n };\n trx.onerror = event => {\n this.#logger('PCache', 'updMessageStatus', event.target.error);\n reject(event.target.error);\n };\n const req = trx.objectStore('message').get(IDBKeyRange.only([topicName, seq]));\n req.onsuccess = event => {\n const src = req.result || event.target.result;\n if (!src || src._status == status) {\n trx.commit();\n return;\n }\n trx.objectStore('message').put(DB.#serializeMessage(src, {\n topic: topicName,\n seq: seq,\n _status: status\n }));\n trx.commit();\n };\n });\n }\n\n /**\n * Remove one or more messages from persistent cache.\n * @memberOf DB\n * @param {string} topicName - name of the topic which owns the message.\n * @param {number} from - id of the message to remove or lower boundary when removing range (inclusive).\n * @param {number=} to - upper boundary (exclusive) when removing a range of messages.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n remMessages(topicName, from, to) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve() :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n if (!from && !to) {\n from = 0;\n to = Number.MAX_SAFE_INTEGER;\n }\n const range = to > 0 ? IDBKeyRange.bound([topicName, from], [topicName, to], false, true) :\n IDBKeyRange.only([topicName, from]);\n const trx = this.db.transaction(['message'], 'readwrite');\n trx.onsuccess = (event) => {\n resolve(event.target.result);\n };\n trx.onerror = (event) => {\n this.#logger('PCache', 'remMessages', event.target.error);\n reject(event.target.error);\n };\n trx.objectStore('message').delete(range);\n trx.commit();\n });\n }\n\n /**\n * Retrieve messages from persistent store.\n * @memberOf DB\n * @param {string} topicName - name of the topic to retrieve messages from.\n * @param {function} callback to call for each retrieved message.\n * @param {Object} query - parameters of the message range to retrieve.\n * @param {number=} query.since - the least message ID to retrieve (inclusive).\n * @param {number=} query.before - the greatest message ID to retrieve (exclusive).\n * @param {number=} query.limit - the maximum number of messages to retrieve.\n * @return {Promise} promise resolved/rejected on operation completion.\n */\n readMessages(topicName, query, callback, context) {\n if (!this.isReady()) {\n return this.disabled ?\n Promise.resolve([]) :\n Promise.reject(new Error(\"not initialized\"));\n }\n return new Promise((resolve, reject) => {\n query = query || {};\n const since = query.since > 0 ? query.since : 0;\n const before = query.before > 0 ? query.before : Number.MAX_SAFE_INTEGER;\n const limit = query.limit | 0;\n\n const result = [];\n const range = IDBKeyRange.bound([topicName, since], [topicName, before], false, true);\n const trx = this.db.transaction(['message']);\n trx.onerror = (event) => {\n this.#logger('PCache', 'readMessages', event.target.error);\n reject(event.target.error);\n };\n // Iterate in descending order.\n trx.objectStore('message').openCursor(range, 'prev').onsuccess = (event) => {\n const cursor = event.target.result;\n if (cursor) {\n if (callback) {\n callback.call(context, cursor.value);\n }\n result.push(cursor.value);\n if (limit <= 0 || result.length < limit) {\n cursor.continue();\n } else {\n resolve(result);\n }\n } else {\n resolve(result);\n }\n };\n });\n }\n\n // Private methods.\n\n // Serializable topic fields.\n static #topic_fields = ['created', 'updated', 'deleted', 'read', 'recv', 'seq', 'clear', 'defacs',\n 'creds', 'public', 'trusted', 'private', 'touched', '_deleted'\n ];\n\n // Copy data from src to Topic object.\n static #deserializeTopic(topic, src) {\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n topic[f] = src[f];\n }\n });\n if (Array.isArray(src.tags)) {\n topic._tags = src.tags;\n }\n if (src.acs) {\n topic.setAccessMode(src.acs);\n }\n topic.seq |= 0;\n topic.read |= 0;\n topic.unread = Math.max(0, topic.seq - topic.read);\n }\n\n // Copy values from 'src' to 'dst'. Allocate dst if it's null or undefined.\n static #serializeTopic(dst, src) {\n const res = dst || {\n name: src.name\n };\n DB.#topic_fields.forEach((f) => {\n if (src.hasOwnProperty(f)) {\n res[f] = src[f];\n }\n });\n if (Array.isArray(src._tags)) {\n res.tags = src._tags;\n }\n if (src.acs) {\n res.acs = src.getAccessMode().jsonHelper();\n }\n return res;\n }\n\n static #serializeSubscription(dst, topicName, uid, sub) {\n const fields = ['updated', 'mode', 'read', 'recv', 'clear', 'lastSeen', 'userAgent'];\n const res = dst || {\n topic: topicName,\n uid: uid\n };\n\n fields.forEach((f) => {\n if (sub.hasOwnProperty(f)) {\n res[f] = sub[f];\n }\n });\n\n return res;\n }\n\n static #serializeMessage(dst, msg) {\n // Serializable fields.\n const fields = ['topic', 'seq', 'ts', '_status', 'from', 'head', 'content'];\n const res = dst || {};\n fields.forEach((f) => {\n if (msg.hasOwnProperty(f)) {\n res[f] = msg[f];\n }\n });\n return res;\n }\n\n /**\n * To use DB in a non browser context, supply indexedDB provider.\n * @static\n * @memberof DB\n * @param idbProvider indexedDB provider, e.g. for node require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IDBProvider = idbProvider;\n }\n}\n","/**\n * @file Utilities for uploading and downloading files.\n *\n * @copyright 2015-2023 Tinode LLC.\n */\n'use strict';\n\nimport CommError from './comm-error.js';\nimport {\n isUrlRelative,\n jsonParseHelper\n} from './utils.js';\n\nlet XHRProvider;\n\n/**\n * @class LargeFileHelper - utilities for uploading and downloading files out of band.\n * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead.\n * @memberof Tinode\n *\n * @param {Tinode} tinode - the main Tinode object.\n * @param {string} version - protocol version, i.e. '0'.\n */\nexport default class LargeFileHelper {\n constructor(tinode, version) {\n this._tinode = tinode;\n this._version = version;\n\n this._apiKey = tinode._apiKey;\n this._authToken = tinode.getAuthToken();\n\n // Ongoing requests.\n this.xhr = [];\n }\n\n /**\n * Start uploading the file to an endpoint at baseUrl.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} baseUrl base URL of upload server.\n * @param {File|Blob} data data to upload.\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure) {\n let url = `/v${this._version}/file/u/`;\n if (baseUrl) {\n let base = baseUrl;\n if (base.endsWith('/')) {\n // Removing trailing slash.\n base = base.slice(0, -1);\n }\n if (base.startsWith('http://') || base.startsWith('https://')) {\n url = base + url;\n } else {\n throw new Error(`Invalid base URL '${baseUrl}'`);\n }\n }\n\n const instance = this;\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n xhr.open('POST', url, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n if (this._authToken) {\n xhr.setRequestHeader('X-Tinode-Auth', `Token ${this._authToken.token}`);\n }\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n xhr.upload.onprogress = e => {\n if (e.lengthComputable) {\n if (onProgress) {\n onProgress(e.loaded / e.total);\n }\n if (this.onProgress) {\n this.onProgress(e.loaded / e.total);\n }\n }\n };\n\n xhr.onload = function() {\n let pkt;\n try {\n pkt = JSON.parse(this.response, jsonParseHelper);\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.response);\n pkt = {\n ctrl: {\n code: this.status,\n text: this.statusText\n }\n };\n }\n\n if (this.status >= 200 && this.status < 300) {\n if (toResolve) {\n toResolve(pkt.ctrl.params.url);\n }\n if (onSuccess) {\n onSuccess(pkt.ctrl);\n }\n } else if (this.status >= 400) {\n if (toReject) {\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n }\n if (onFailure) {\n onFailure(pkt.ctrl);\n }\n } else {\n instance._tinode.logger(\"ERROR: Unexpected server response status\", this.status, this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(e || new Error(\"failed\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n xhr.onabort = function(e) {\n if (toReject) {\n toReject(new Error(\"upload cancelled by user\"));\n }\n if (onFailure) {\n onFailure(null);\n }\n };\n\n try {\n const form = new FormData();\n form.append('file', data);\n form.set('id', this._tinode.getNextUniqueId());\n if (avatarFor) {\n form.set('topic', avatarFor);\n }\n xhr.send(form);\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onFailure) {\n onFailure(null);\n }\n }\n\n return result;\n }\n /**\n * Start uploading the file to default endpoint.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {File|Blob} data to upload\n * @param {string} avatarFor topic name if the upload represents an avatar.\n * @param {Callback} onProgress callback. Takes one {float} parameter 0..1\n * @param {Callback} onSuccess callback. Called when the file is successfully uploaded.\n * @param {Callback} onFailure callback. Called in case of a failure.\n *\n * @returns {Promise} resolved/rejected when the upload is completed/failed.\n */\n upload(data, avatarFor, onProgress, onSuccess, onFailure) {\n const baseUrl = (this._tinode._secure ? 'https://' : 'http://') + this._tinode._host;\n return this.uploadWithBaseUrl(baseUrl, data, avatarFor, onProgress, onSuccess, onFailure);\n }\n /**\n * Download the file from a given URL using GET request. This method works with the Tinode server only.\n *\n * @memberof Tinode.LargeFileHelper#\n *\n * @param {string} relativeUrl - URL to download the file from. Must be relative url, i.e. must not contain the host.\n * @param {string=} filename - file name to use for the downloaded file.\n *\n * @returns {Promise} resolved/rejected when the download is completed/failed.\n */\n download(relativeUrl, filename, mimetype, onProgress, onError) {\n if (!isUrlRelative(relativeUrl)) {\n // As a security measure refuse to download from an absolute URL.\n if (onError) {\n onError(`The URL '${relativeUrl}' must be relative, not absolute`);\n }\n return;\n }\n if (!this._authToken) {\n if (onError) {\n onError(\"Must authenticate first\");\n }\n return;\n }\n const instance = this;\n\n const xhr = new XHRProvider();\n this.xhr.push(xhr);\n\n // Get data as blob (stored by the browser as a temporary file).\n xhr.open('GET', relativeUrl, true);\n xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey);\n xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token);\n xhr.responseType = 'blob';\n\n xhr.onprogress = function(e) {\n if (onProgress) {\n // Passing e.loaded instead of e.loaded/e.total because e.total\n // is always 0 with gzip compression enabled by the server.\n onProgress(e.loaded);\n }\n };\n\n let toResolve = null;\n let toReject = null;\n\n const result = new Promise((resolve, reject) => {\n toResolve = resolve;\n toReject = reject;\n });\n\n // The blob needs to be saved as file. There is no known way to\n // save the blob as file other than to fake a click on an .\n xhr.onload = function() {\n if (this.status == 200) {\n const link = document.createElement('a');\n // URL.createObjectURL is not available in non-browser environment. This call will fail.\n link.href = window.URL.createObjectURL(new Blob([this.response], {\n type: mimetype\n }));\n link.style.display = 'none';\n link.setAttribute('download', filename);\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n window.URL.revokeObjectURL(link.href);\n if (toResolve) {\n toResolve();\n }\n } else if (this.status >= 400 && toReject) {\n // The this.responseText is undefined, must use this.response which is a blob.\n // Need to convert this.response to JSON. The blob can only be accessed by the\n // FileReader.\n const reader = new FileReader();\n reader.onload = function() {\n try {\n const pkt = JSON.parse(this.result, jsonParseHelper);\n toReject(new CommError(pkt.ctrl.text, pkt.ctrl.code));\n } catch (err) {\n instance._tinode.logger(\"ERROR: Invalid server response in LargeFileHelper\", this.result);\n toReject(err);\n }\n };\n reader.readAsText(this.response);\n }\n };\n\n xhr.onerror = function(e) {\n if (toReject) {\n toReject(new Error(\"failed\"));\n }\n if (onError) {\n onError(e);\n }\n };\n\n xhr.onabort = function() {\n if (toReject) {\n toReject(null);\n }\n };\n\n try {\n xhr.send();\n } catch (err) {\n if (toReject) {\n toReject(err);\n }\n if (onError) {\n onError(err);\n }\n }\n\n return result;\n }\n /**\n * Try to cancel all ongoing uploads or downloads.\n * @memberof Tinode.LargeFileHelper#\n */\n cancel() {\n this.xhr.forEach(req => {\n if (req.readyState < 4) {\n req.abort();\n }\n });\n }\n /**\n * To use LargeFileHelper in a non browser context, supply XMLHttpRequest provider.\n * @static\n * @memberof LargeFileHelper\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProvider(xhrProvider) {\n XHRProvider = xhrProvider;\n }\n}\n","/**\n * @file Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * Helper class for constructing {@link Tinode.GetQuery}.\n *\n * @class MetaGetBuilder\n * @memberof Tinode\n *\n * @param {Tinode.Topic} parent topic which instantiated this builder.\n */\nexport default class MetaGetBuilder {\n constructor(parent) {\n this.topic = parent;\n this.what = {};\n }\n\n // Get timestamp of the most recent desc update.\n #get_desc_ims() {\n return this.topic.updated;\n }\n\n // Get timestamp of the most recent subs update.\n #get_subs_ims() {\n if (this.topic.isP2PType()) {\n return this.#get_desc_ims();\n }\n return this.topic._lastSubsUpdate;\n }\n /**\n * Add query parameters to fetch messages within explicit limits.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - messages newer than this (inclusive);\n * @param {number=} before - older than this (exclusive)\n * @param {number=} limit - number of messages to fetch\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withData(since, before, limit) {\n this.what['data'] = {\n since: since,\n before: before,\n limit: limit\n };\n return this;\n }\n /**\n * Add query parameters to fetch messages newer than the latest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of messages to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterData(limit) {\n return this.withData(this.topic._maxSeq > 0 ? this.topic._maxSeq + 1 : undefined, undefined, limit);\n }\n /**\n * Add query parameters to fetch messages older than the earliest saved message.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of messages to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withEarlierData(limit) {\n return this.withData(undefined, this.topic._minSeq > 0 ? this.topic._minSeq : undefined, limit);\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the given timestamp.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch messages newer than this timestamp.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDesc(ims) {\n this.what['desc'] = {\n ims: ims\n };\n return this;\n }\n /**\n * Add query parameters to fetch topic description if it's newer than the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDesc() {\n return this.withDesc(this.#get_desc_ims());\n }\n /**\n * Add query parameters to fetch subscriptions.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {number=} limit - maximum number of subscriptions to fetch.\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withSub(ims, limit, userOrTopic) {\n const opts = {\n ims: ims,\n limit: limit\n };\n if (this.topic.getType() == 'me') {\n opts.topic = userOrTopic;\n } else {\n opts.user = userOrTopic;\n }\n this.what['sub'] = opts;\n return this;\n }\n /**\n * Add query parameters to fetch a single subscription.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {Date=} ims - fetch subscriptions modified more recently than this timestamp\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withOneSub(ims, userOrTopic) {\n return this.withSub(ims, undefined, userOrTopic);\n }\n /**\n * Add query parameters to fetch a single subscription if it's been updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {string=} userOrTopic - user ID or topic name to fetch for fetching one subscription.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterOneSub(userOrTopic) {\n return this.withOneSub(this.topic._lastSubsUpdate, userOrTopic);\n }\n /**\n * Add query parameters to fetch subscriptions updated since the last update.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - maximum number of subscriptions to fetch.\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterSub(limit) {\n return this.withSub(this.#get_subs_ims(), limit);\n }\n /**\n * Add query parameters to fetch topic tags.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withTags() {\n this.what['tags'] = true;\n return this;\n }\n /**\n * Add query parameters to fetch user's credentials. 'me' topic only.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withCred() {\n if (this.topic.getType() == 'me') {\n this.what['cred'] = true;\n } else {\n this.topic._tinode.logger(\"ERROR: Invalid topic type for MetaGetBuilder:withCreds\", this.topic.getType());\n }\n return this;\n }\n /**\n * Add query parameters to fetch deleted messages within explicit limits. Any/all parameters can be null.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} since - ids of messages deleted since this 'del' id (inclusive)\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withDel(since, limit) {\n if (since || limit) {\n this.what['del'] = {\n since: since,\n limit: limit\n };\n }\n return this;\n }\n /**\n * Add query parameters to fetch messages deleted after the saved 'del' id.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @param {number=} limit - number of deleted message ids to fetch\n *\n * @returns {Tinode.MetaGetBuilder} this object.\n */\n withLaterDel(limit) {\n // Specify 'since' only if we have already received some messages. If\n // we have no locally cached messages then we don't care if any messages were deleted.\n return this.withDel(this.topic._maxSeq > 0 ? this.topic._maxDel + 1 : undefined, limit);\n }\n\n /**\n * Extract subquery: get an object that contains specified subquery.\n * @memberof Tinode.MetaGetBuilder#\n * @param {string} what - subquery to return: one of 'data', 'sub', 'desc', 'tags', 'cred', 'del'.\n * @returns {Object} requested subquery or undefined.\n */\n extract(what) {\n return this.what[what];\n }\n\n /**\n * Construct parameters.\n * @memberof Tinode.MetaGetBuilder#\n *\n * @returns {Tinode.GetQuery} Get query\n */\n build() {\n const what = [];\n let params = {};\n ['data', 'sub', 'desc', 'tags', 'cred', 'del'].forEach((key) => {\n if (this.what.hasOwnProperty(key)) {\n what.push(key);\n if (Object.getOwnPropertyNames(this.what[key]).length > 0) {\n params[key] = this.what[key];\n }\n }\n });\n if (what.length > 0) {\n params.what = what.join(' ');\n } else {\n params = undefined;\n }\n return params;\n }\n}\n","/**\n * @file In-memory sorted cache of objects.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\n/**\n * In-memory sorted cache of objects.\n *\n * @class CBuffer\n * @memberof Tinode\n * @protected\n *\n * @param {function} compare custom comparator of objects. Takes two parameters a and b;\n * returns -1 if a < b, 0 if a == b, 1 otherwise.\n * @param {boolean} unique enforce element uniqueness: when true replace existing element with a new\n * one on conflict; when false keep both elements.\n */\nexport default class CBuffer {\n #comparator = undefined;\n #unique = false;\n buffer = [];\n\n constructor(compare_, unique_) {\n this.#comparator = compare_ || ((a, b) => {\n return a === b ? 0 : a < b ? -1 : 1;\n });\n this.#unique = unique_;\n }\n\n #findNearest(elem, arr, exact) {\n let start = 0;\n let end = arr.length - 1;\n let pivot = 0;\n let diff = 0;\n let found = false;\n\n while (start <= end) {\n pivot = (start + end) / 2 | 0;\n diff = this.#comparator(arr[pivot], elem);\n if (diff < 0) {\n start = pivot + 1;\n } else if (diff > 0) {\n end = pivot - 1;\n } else {\n found = true;\n break;\n }\n }\n if (found) {\n return {\n idx: pivot,\n exact: true\n };\n }\n if (exact) {\n return {\n idx: -1\n };\n }\n // Not exact - insertion point\n return {\n idx: diff < 0 ? pivot + 1 : pivot\n };\n }\n\n // Insert element into a sorted array.\n #insertSorted(elem, arr) {\n const found = this.#findNearest(elem, arr, false);\n const count = (found.exact && this.#unique) ? 1 : 0;\n arr.splice(found.idx, count, elem);\n return arr;\n }\n\n /**\n * Get an element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to fetch from.\n * @returns {Object} Element at the given position or undefined.\n */\n getAt(at) {\n return this.buffer[at];\n }\n\n /**\n * Convenience method for getting the element from the end of the buffer.\n * @memberof Tinode.CBuffer#\n * @param {number} at - position to fetch from, counting from the end;\n * undefined or null mean \"last\".\n * @returns {Object} The last element in the buffer or undefined if buffer is empty.\n */\n getLast(at) {\n at |= 0;\n return this.buffer.length > at ? this.buffer[this.buffer.length - 1 - at] : undefined;\n }\n\n /**\n * Add new element(s) to the buffer. Variadic: takes one or more arguments. If an array is passed as a single\n * argument, its elements are inserted individually.\n * @memberof Tinode.CBuffer#\n *\n * @param {...Object|Array} - One or more objects to insert.\n */\n put() {\n let insert;\n // inspect arguments: if array, insert its elements, if one or more non-array arguments, insert them one by one\n if (arguments.length == 1 && Array.isArray(arguments[0])) {\n insert = arguments[0];\n } else {\n insert = arguments;\n }\n for (let idx in insert) {\n this.#insertSorted(insert[idx], this.buffer);\n }\n }\n\n /**\n * Remove element at the given position.\n * @memberof Tinode.CBuffer#\n * @param {number} at - Position to delete at.\n * @returns {Object} Element at the given position or undefined.\n */\n delAt(at) {\n at |= 0;\n let r = this.buffer.splice(at, 1);\n if (r && r.length > 0) {\n return r[0];\n }\n return undefined;\n }\n\n /**\n * Remove elements between two positions.\n * @memberof Tinode.CBuffer#\n * @param {number} since - Position to delete from (inclusive).\n * @param {number} before - Position to delete to (exclusive).\n *\n * @returns {Array} array of removed elements (could be zero length).\n */\n delRange(since, before) {\n return this.buffer.splice(since, before - since);\n }\n\n /**\n * Return the number of elements the buffer holds.\n * @memberof Tinode.CBuffer#\n * @return {number} Number of elements in the buffer.\n */\n length() {\n return this.buffer.length;\n }\n\n /**\n * Reset the buffer discarding all elements\n * @memberof Tinode.CBuffer#\n */\n reset() {\n this.buffer = [];\n }\n\n /**\n * Callback for iterating contents of buffer. See {@link Tinode.CBuffer#forEach}.\n * @callback ForEachCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {Object} prev - Previous element of the buffer.\n * @param {Object} next - Next element of the buffer.\n * @param {number} index - Index of the current element.\n */\n\n /**\n * Apply given callback to all elements of the buffer.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.ForEachCallbackType} callback - Function to call for each element.\n * @param {number} startIdx - Optional index to start iterating from (inclusive).\n * @param {number} beforeIdx - Optional index to stop iterating before (exclusive).\n * @param {Object} context - calling context (i.e. value of this in callback)\n */\n forEach(callback, startIdx, beforeIdx, context) {\n startIdx = startIdx | 0;\n beforeIdx = beforeIdx || this.buffer.length;\n\n for (let i = startIdx; i < beforeIdx; i++) {\n callback.call(context, this.buffer[i],\n (i > startIdx ? this.buffer[i - 1] : undefined),\n (i < beforeIdx - 1 ? this.buffer[i + 1] : undefined), i);\n }\n }\n\n /**\n * Find element in buffer using buffer's comparison function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Object} elem - element to find.\n * @param {boolean=} nearest - when true and exact match is not found, return the nearest element (insertion point).\n * @returns {number} index of the element in the buffer or -1.\n */\n find(elem, nearest) {\n const {\n idx\n } = this.#findNearest(elem, this.buffer, !nearest);\n return idx;\n }\n\n /**\n * Callback for filtering the buffer. See {@link Tinode.CBuffer#filter}.\n * @callback FilterCallbackType\n * @memberof Tinode.CBuffer#\n * @param {Object} elem - Current element of the buffer.\n * @param {number} index - Index of the current element.\n * @returns {boolen} true to keep the element, false to remove.\n */\n\n /**\n * Remove all elements that do not pass the test implemented by the provided callback function.\n * @memberof Tinode.CBuffer#\n *\n * @param {Tinode.FilterCallbackType} callback - Function to call for each element.\n * @param {Object} context - calling context (i.e. value of this in the callback)\n */\n filter(callback, context) {\n let count = 0;\n for (let i = 0; i < this.buffer.length; i++) {\n if (callback.call(context, this.buffer[i], i)) {\n this.buffer[count] = this.buffer[i];\n count++;\n }\n }\n\n this.buffer.splice(count);\n }\n\n /**\n * Check if buffer is empty.\n * @returns {boolean} true if the buffer is empty, false otherwise.\n */\n isEmpty() {\n return this.buffer.length == 0;\n }\n}\n","/**\n * @file Topic management.\n *\n * @copyright 2015-2022 Tinode LLC.\n */\n'use strict';\n\nimport AccessMode from './access-mode.js';\nimport CBuffer from './cbuffer.js';\nimport CommError from './comm-error.js';\nimport * as Const from './config.js';\nimport Drafty from './drafty.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n mergeObj,\n mergeToCache,\n normalizeArray\n} from './utils.js';\n\nexport class Topic {\n /**\n * @callback Tinode.Topic.onData\n * @param {Data} data - Data packet\n */\n /**\n * Topic is a class representing a logical communication channel.\n * @class Topic\n * @memberof Tinode\n *\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {Tinode.Topic.onData} callbacks.onData - Callback which receives a {data} message.\n * @param {callback} callbacks.onMeta - Callback which receives a {meta} message.\n * @param {callback} callbacks.onPres - Callback which receives a {pres} message.\n * @param {callback} callbacks.onInfo - Callback which receives an {info} message.\n * @param {callback} callbacks.onMetaDesc - Callback which receives changes to topic desctioption {@link desc}.\n * @param {callback} callbacks.onMetaSub - Called for a single subscription record change.\n * @param {callback} callbacks.onSubsUpdated - Called after a batch of subscription changes have been recieved and cached.\n * @param {callback} callbacks.onDeleteTopic - Called after the topic is deleted.\n * @param {callback} callbacls.onAllMessagesReceived - Called when all requested {data} messages have been recived.\n */\n constructor(name, callbacks) {\n // Parent Tinode object.\n this._tinode = null;\n\n // Server-provided data, locally immutable.\n // topic name\n this.name = name;\n // Timestamp when the topic was created.\n this.created = null;\n // Timestamp when the topic was last updated.\n this.updated = null;\n // Timestamp of the last messages\n this.touched = new Date(0);\n // Access mode, see AccessMode\n this.acs = new AccessMode(null);\n // Per-topic private data (accessible by current user only).\n this.private = null;\n // Per-topic public data (accessible by all users).\n this.public = null;\n // Per-topic system-provided data (accessible by all users).\n this.trusted = null;\n\n // Locally cached data\n // Subscribed users, for tracking read/recv/msg notifications.\n this._users = {};\n\n // Current value of locally issued seqId, used for pending messages.\n this._queuedSeqId = Const.LOCAL_SEQID;\n\n // The maximum known {data.seq} value.\n this._maxSeq = 0;\n // The minimum known {data.seq} value.\n this._minSeq = 0;\n // Indicator that the last request for earlier messages returned 0.\n this._noEarlierMsgs = false;\n // The maximum known deletion ID.\n this._maxDel = 0;\n // Timer object used to send 'recv' notifications.\n this._recvNotificationTimer = null;\n\n // User discovery tags\n this._tags = [];\n // Credentials such as email or phone number.\n this._credentials = [];\n // Message versions cache (e.g. for edited messages).\n // Keys: original message seq ID.\n // Values: CBuffers containing newer versions of the original message\n // ordered by seq id.\n this._messageVersions = {};\n // Message cache, sorted by message seq values, from old to new.\n this._messages = new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n // Boolean, true if the topic is currently live\n this._attached = false;\n // Timestap of the most recently updated subscription.\n this._lastSubsUpdate = new Date(0);\n // Topic created but not yet synced with the server. Used only during initialization.\n this._new = true;\n // The topic is deleted at the server, this is a local copy.\n this._deleted = false;\n\n // Timer used to trgger {leave} request after a delay.\n this._delayedLeaveTimer = null;\n\n // Callbacks\n if (callbacks) {\n this.onData = callbacks.onData;\n this.onMeta = callbacks.onMeta;\n this.onPres = callbacks.onPres;\n this.onInfo = callbacks.onInfo;\n // A single desc update;\n this.onMetaDesc = callbacks.onMetaDesc;\n // A single subscription record;\n this.onMetaSub = callbacks.onMetaSub;\n // All subscription records received;\n this.onSubsUpdated = callbacks.onSubsUpdated;\n this.onTagsUpdated = callbacks.onTagsUpdated;\n this.onCredsUpdated = callbacks.onCredsUpdated;\n this.onDeleteTopic = callbacks.onDeleteTopic;\n this.onAllMessagesReceived = callbacks.onAllMessagesReceived;\n }\n }\n\n // Static methods.\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n const types = {\n 'me': Const.TOPIC_ME,\n 'fnd': Const.TOPIC_FND,\n 'grp': Const.TOPIC_GRP,\n 'new': Const.TOPIC_GRP,\n 'nch': Const.TOPIC_GRP,\n 'chn': Const.TOPIC_GRP,\n 'usr': Const.TOPIC_P2P,\n 'sys': Const.TOPIC_SYS\n };\n return types[(typeof name == 'string') ? name.substring(0, 3) : 'xxx'];\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_ME;\n }\n\n /**\n * Check if the given topic name is a name of a group topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_GRP;\n }\n\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.topicType(name) == Const.TOPIC_P2P;\n }\n\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isP2PTopicName(name) || Topic.isGroupTopicName(name);\n }\n\n /**\n * Check if the topic name is a name of a new topic.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_NEW || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic name is a name of a channel.\n * @memberof Tinode.Topic#\n * @static\n *\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return (typeof name == 'string') &&\n (name.substring(0, 3) == Const.TOPIC_CHAN || name.substring(0, 3) == Const.TOPIC_NEW_CHAN);\n }\n\n /**\n * Check if the topic is subscribed.\n * @memberof Tinode.Topic#\n * @returns {boolean} True is topic is attached/subscribed, false otherwise.\n */\n isSubscribed() {\n return this._attached;\n }\n\n /**\n * Request topic to subscribe. Wrapper for {@link Tinode#subscribe}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery=} getParams - get query parameters.\n * @param {Tinode.SetParams=} setParams - set parameters.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n subscribe(getParams, setParams) {\n // Clear request to leave topic.\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = null;\n\n // If the topic is already subscribed, return resolved promise\n if (this._attached) {\n return Promise.resolve(this);\n }\n\n // If the topic is deleted, reject subscription requests.\n if (this._deleted) {\n return Promise.reject(new Error(\"Conversation deleted\"));\n }\n\n // Send subscribe message, handle async response.\n // If topic name is explicitly provided, use it. If no name, then it's a new group topic,\n // use \"new\".\n return this._tinode.subscribe(this.name || Const.TOPIC_NEW, getParams, setParams).then(ctrl => {\n if (ctrl.code >= 300) {\n // Do nothing if subscription status has not changed.\n return ctrl;\n }\n\n this._attached = true;\n this._deleted = false;\n this.acs = (ctrl.params && ctrl.params.acs) ? ctrl.params.acs : this.acs;\n\n // Set topic name for new topics and add it to cache.\n if (this._new) {\n delete this._new;\n\n if (this.name != ctrl.topic) {\n // Name may change new123456 -> grpAbCdEf. Remove from cache under the old name.\n this._cacheDelSelf();\n this.name = ctrl.topic;\n }\n this._cachePutSelf();\n\n this.created = ctrl.ts;\n this.updated = ctrl.ts;\n\n if (this.name != Const.TOPIC_ME && this.name != Const.TOPIC_FND) {\n // Add the new topic to the list of contacts maintained by the 'me' topic.\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (setParams && setParams.desc) {\n setParams.desc._noForwarding = true;\n this._processMetaDesc(setParams.desc);\n }\n }\n return ctrl;\n });\n }\n\n /**\n * Create a draft of a message without sending it to the server.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Content to wrap in a draft.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * session. Otherwise the server will send a copy of the message to sender.\n *\n * @returns {Object} message draft.\n */\n createMessage(data, noEcho) {\n return this._tinode.createMessage(this.name, data, noEcho);\n }\n\n /**\n * Immediately publish data to topic. Wrapper for {@link Tinode#publish}.\n * @memberof Tinode.Topic#\n *\n * @param {string | Object} data - Message to publish, either plain string or a Drafty object.\n * @param {boolean=} noEcho - If true server will not echo message back to originating\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publish(data, noEcho) {\n return this.publishMessage(this.createMessage(data, noEcho));\n }\n\n /**\n * Publish message created by {@link Tinode.Topic#createMessage}.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - {data} object to publish. Must be created by {@link Tinode.Topic#createMessage}\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n publishMessage(pub) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot publish on inactive topic\"));\n }\n if (this._sending) {\n return Promise.reject(new Error(\"The message is already being sent\"));\n }\n\n // Send data.\n pub._sending = true;\n pub._failed = false;\n\n // Extract refereces to attachments and out of band image records.\n let attachments = null;\n if (Drafty.hasEntities(pub.content)) {\n attachments = [];\n Drafty.entities(pub.content, data => {\n if (data) {\n if (data.ref) {\n attachments.push(data.ref);\n }\n if (data.preref) {\n attachments.push(data.preref);\n }\n }\n });\n if (attachments.length == 0) {\n attachments = null;\n }\n }\n\n return this._tinode.publishMessage(pub, attachments).then(ctrl => {\n pub._sending = false;\n pub.ts = ctrl.ts;\n this.swapMessageId(pub, ctrl.params.seq);\n this._maybeUpdateMessageVersionsCache(pub);\n this._routeData(pub);\n return ctrl;\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message rejected by the server\", err);\n pub._sending = false;\n pub._failed = true;\n if (this.onData) {\n this.onData();\n }\n });\n }\n\n /**\n * Add message to local message cache, send to the server when the promise is resolved.\n * If promise is null or undefined, the message will be sent immediately.\n * The message is sent when the\n * The message should be created by {@link Tinode.Topic#createMessage}.\n * This is probably not the final API.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub - Message to use as a draft.\n * @param {Promise} prom - Message will be sent when this promise is resolved, discarded if rejected.\n *\n * @returns {Promise} derived promise.\n */\n publishDraft(pub, prom) {\n const seq = pub.seq || this._getQueuedSeqId();\n if (!pub._noForwarding) {\n // The 'seq', 'ts', and 'from' are added to mimic {data}. They are removed later\n // before the message is sent.\n pub._noForwarding = true;\n pub.seq = seq;\n pub.ts = new Date();\n pub.from = this._tinode.getCurrentUserID();\n\n // Don't need an echo message because the message is added to local cache right away.\n pub.noecho = true;\n // Add to cache.\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n\n if (this.onData) {\n this.onData(pub);\n }\n }\n // If promise is provided, send the queued message when it's resolved.\n // If no promise is provided, create a resolved one and send immediately.\n return (prom || Promise.resolve())\n .then(_ => {\n if (pub._cancelled) {\n return {\n code: 300,\n text: \"cancelled\"\n };\n }\n return this.publishMessage(pub);\n }).catch(err => {\n this._tinode.logger(\"WARNING: Message draft rejected\", err);\n pub._sending = false;\n pub._failed = true;\n pub._fatal = err instanceof CommError ? (err.code >= 400 && err.code < 500) : false;\n if (this.onData) {\n this.onData();\n }\n // Rethrow to let caller know that the operation failed.\n throw err;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean=} unsub - If true, unsubscribe, otherwise just leave.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n leave(unsub) {\n // It's possible to unsubscribe (unsub==true) from inactive topic.\n if (!this._attached && !unsub) {\n return Promise.reject(new Error(\"Cannot leave inactive topic\"));\n }\n\n // Send a 'leave' message, handle async response\n return this._tinode.leave(this.name, unsub).then(ctrl => {\n this._resetSub();\n if (unsub) {\n this._gone();\n }\n return ctrl;\n });\n }\n\n /**\n * Leave the topic, optionally unsibscribe after a delay. Leaving the topic means the topic will stop\n * receiving updates from the server. Unsubscribing will terminate user's relationship with the topic.\n * Wrapper for {@link Tinode#leave}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} unsub - If true, unsubscribe, otherwise just leave.\n * @param {number} delay - time in milliseconds to delay leave request.\n */\n leaveDelayed(unsub, delay) {\n clearTimeout(this._delayedLeaveTimer);\n this._delayedLeaveTimer = setTimeout(_ => {\n this._delayedLeaveTimer = null;\n this.leave(unsub)\n }, delay);\n }\n\n /**\n * Request topic metadata from the server.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.GetQuery} request parameters\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n getMeta(params) {\n // Send {get} message, return promise.\n return this._tinode.getMeta(this.name, params);\n }\n\n /**\n * Request more messages from the server\n * @memberof Tinode.Topic#\n *\n * @param {number} limit number of messages to get.\n * @param {boolean} forward if true, request newer messages.\n */\n getMessagesPage(limit, forward) {\n let query = forward ?\n this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n\n // First try fetching from DB, then from the server.\n return this._loadMessages(this._tinode._db, query.extract('data'))\n .then((count) => {\n if (count == limit) {\n // Got enough messages from local cache.\n return Promise.resolve({\n topic: this.name,\n code: 200,\n params: {\n count: count\n }\n });\n }\n\n // Reduce the count of requested messages.\n limit -= count;\n // Update query with new values loaded from DB.\n query = forward ? this.startMetaQuery().withLaterData(limit) :\n this.startMetaQuery().withEarlierData(limit);\n let promise = this.getMeta(query.build());\n if (!forward) {\n promise = promise.then(ctrl => {\n if (ctrl && ctrl.params && !ctrl.params.count) {\n this._noEarlierMsgs = true;\n }\n });\n }\n return promise;\n });\n }\n /**\n * Update topic metadata.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n if (params.tags) {\n params.tags = normalizeArray(params.tags);\n }\n // Send Set message, handle async response.\n return this._tinode.setMeta(this.name, params)\n .then(ctrl => {\n if (ctrl && ctrl.code >= 300) {\n // Not modified\n return ctrl;\n }\n\n if (params.sub) {\n params.sub.topic = this.name;\n if (ctrl.params && ctrl.params.acs) {\n params.sub.acs = ctrl.params.acs;\n params.sub.updated = ctrl.ts;\n }\n if (!params.sub.user) {\n // This is a subscription update of the current user.\n // Assign user ID otherwise the update will be ignored by _processMetaSub.\n params.sub.user = this._tinode.getCurrentUserID();\n if (!params.desc) {\n // Force update to topic's asc.\n params.desc = {};\n }\n }\n params.sub._noForwarding = true;\n this._processMetaSub([params.sub]);\n }\n\n if (params.desc) {\n if (ctrl.params && ctrl.params.acs) {\n params.desc.acs = ctrl.params.acs;\n params.desc.updated = ctrl.ts;\n }\n this._processMetaDesc(params.desc);\n }\n\n if (params.tags) {\n this._processMetaTags(params.tags);\n }\n if (params.cred) {\n this._processMetaCreds([params.cred], true);\n }\n\n return ctrl;\n });\n }\n /**\n * Update access mode of the current user or of another topic subsriber.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - UID of the user to update or null to update current user.\n * @param {string} update - the update value, full or delta.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n updateMode(uid, update) {\n const user = uid ? this.subscriber(uid) : null;\n const am = user ?\n user.acs.updateGiven(update).getGiven() :\n this.getAccessMode().updateWant(update).getWant();\n\n return this.setMeta({\n sub: {\n user: uid,\n mode: am\n }\n });\n }\n /**\n * Create new topic subscription. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to invite\n * @param {string=} mode - Access mode. null means to use default.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n invite(uid, mode) {\n return this.setMeta({\n sub: {\n user: uid,\n mode: mode\n }\n });\n }\n /**\n * Archive or un-archive the topic. Wrapper for {@link Tinode#setMeta}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} arch - true to archive the topic, false otherwise.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n archive(arch) {\n if (this.private && (!this.private.arch == !arch)) {\n return Promise.resolve(arch);\n }\n return this.setMeta({\n desc: {\n private: {\n arch: arch ? true : Const.DEL_CHAR\n }\n }\n });\n }\n /**\n * Delete messages. Hard-deleting messages requires Owner permission.\n * Wrapper for {@link Tinode#delMessages}.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.DelRange[]} ranges - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessages(ranges, hard) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete messages in inactive topic\"));\n }\n\n // Sort ranges in accending order by low, the descending by hi.\n ranges.sort((r1, r2) => {\n if (r1.low < r2.low) {\n return true;\n }\n if (r1.low == r2.low) {\n return !r2.hi || (r1.hi >= r2.hi);\n }\n return false;\n });\n\n // Remove pending messages from ranges possibly clipping some ranges.\n let tosend = ranges.reduce((out, r) => {\n if (r.low < Const.LOCAL_SEQID) {\n if (!r.hi || r.hi < Const.LOCAL_SEQID) {\n out.push(r);\n } else {\n // Clip hi to max allowed value.\n out.push({\n low: r.low,\n hi: this._maxSeq + 1\n });\n }\n }\n return out;\n }, []);\n\n // Send {del} message, return promise\n let result;\n if (tosend.length > 0) {\n result = this._tinode.delMessages(this.name, tosend, hard);\n } else {\n result = Promise.resolve({\n params: {\n del: 0\n }\n });\n }\n // Update local cache.\n return result.then(ctrl => {\n if (ctrl.params.del > this._maxDel) {\n this._maxDel = ctrl.params.del;\n }\n\n ranges.forEach((r) => {\n if (r.hi) {\n this.flushMessageRange(r.low, r.hi);\n } else {\n this.flushMessage(r.low);\n }\n });\n\n if (this.onData) {\n // Calling with no parameters to indicate the messages were deleted.\n this.onData();\n }\n return ctrl;\n });\n }\n /**\n * Delete all messages. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesAll(hardDel) {\n if (!this._maxSeq || this._maxSeq <= 0) {\n // There are no messages to delete.\n return Promise.resolve();\n }\n return this.delMessages([{\n low: 1,\n hi: this._maxSeq + 1,\n _all: true\n }], hardDel);\n }\n\n /**\n * Delete multiple messages defined by their IDs. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {Array.} list - list of seq IDs to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delMessagesList(list, hardDel) {\n // Sort the list in ascending order\n list.sort((a, b) => a - b);\n // Convert the array of IDs to ranges.\n let ranges = list.reduce((out, id) => {\n if (out.length == 0) {\n // First element.\n out.push({\n low: id\n });\n } else {\n let prev = out[out.length - 1];\n if ((!prev.hi && (id != prev.low + 1)) || (id > prev.hi)) {\n // New range.\n out.push({\n low: id\n });\n } else {\n // Expand existing range.\n prev.hi = prev.hi ? Math.max(prev.hi, id + 1) : id + 1;\n }\n }\n return out;\n }, []);\n // Send {del} message, return promise\n return this.delMessages(ranges, hardDel);\n }\n\n /**\n * Delete original message and edited variants. Hard-deleting messages requires Deleter permission.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message to delete.\n * @param {boolean=} hardDel - true if messages should be hard-deleted.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delMessagesEdits(seq, hardDel) {\n const list = [seq];\n this.messageVersions(seq, msg => list.push(msg.seq));\n // Send {del} message, return promise\n return this.delMessagesList(list, hardDel);\n }\n\n /**\n * Delete topic. Requires Owner permission. Wrapper for {@link Tinode#delTopic}.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} hard - had-delete topic.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to the request.\n */\n delTopic(hard) {\n if (this._deleted) {\n // The topic is already deleted at the server, just remove from DB.\n this._gone();\n return Promise.resolve(null);\n }\n\n return this._tinode.delTopic(this.name, hard).then(ctrl => {\n this._deleted = true;\n this._resetSub();\n this._gone();\n return ctrl;\n });\n }\n /**\n * Delete subscription. Requires Share permission. Wrapper for {@link Tinode#delSubscription}.\n * @memberof Tinode.Topic#\n *\n * @param {string} user - ID of the user to remove subscription for.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n delSubscription(user) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete subscription in inactive topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delSubscription(this.name, user).then(ctrl => {\n // Remove the object from the subscription cache;\n delete this._users[user];\n // Notify listeners\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n return ctrl;\n });\n }\n /**\n * Send a read/recv notification.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what notification to send: recv, read.\n * @param {number} seq - ID or the message read or received.\n */\n note(what, seq) {\n if (!this._attached) {\n // Cannot sending {note} on an inactive topic\".\n return;\n }\n\n // Update local cache with the new count.\n const user = this._users[this._tinode.getCurrentUserID()];\n let update = false;\n if (user) {\n // Self-subscription is found.\n if (!user[what] || user[what] < seq) {\n user[what] = seq;\n update = true;\n }\n } else {\n // Self-subscription is not found.\n update = (this[what] | 0) < seq;\n }\n\n if (update) {\n // Send notification to the server.\n this._tinode.note(this.name, what, seq);\n // Update locally cached contact with the new count.\n this._updateReadRecv(what, seq);\n\n if (this.acs != null && !this.acs.isMuted()) {\n const me = this._tinode.getMeTopic();\n // Sent a notification to 'me' listeners.\n me._refreshContact(what, this);\n }\n }\n }\n\n /**\n * Send a 'recv' receipt. Wrapper for {@link Tinode#noteRecv}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge.\n */\n noteRecv(seq) {\n this.note('recv', seq);\n }\n /**\n * Send a 'read' receipt. Wrapper for {@link Tinode#noteRead}.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - ID of the message to aknowledge or 0/undefined to acknowledge the latest messages.\n */\n noteRead(seq) {\n seq = seq || this._maxSeq;\n if (seq > 0) {\n this.note('read', seq);\n }\n }\n /**\n * Send a key-press notification. Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n */\n noteKeyPress() {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name);\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n /**\n * Send a notification than a video or audio message is . Wrapper for {@link Tinode#noteKeyPress}.\n * @memberof Tinode.Topic#\n * @param audioOnly - true if the recording is audio-only, false if it's a video recording.\n */\n noteRecording(audioOnly) {\n if (this._attached) {\n this._tinode.noteKeyPress(this.name, audioOnly ? 'kpa' : 'kpv');\n } else {\n this._tinode.logger(\"INFO: Cannot send notification in inactive topic\");\n }\n }\n\n /**\n * Send a {note what='call'}. Wrapper for {@link Tinode#videoCall}.\n * @memberof Tinode#\n *\n * @param {string} evt - Call event.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(evt, seq, payload) {\n if (!this._attached && !['ringing', 'hang-up'].includes(evt)) {\n // Cannot {call} on an inactive topic\".\n return;\n }\n return this._tinode.videoCall(this.name, seq, evt, payload);\n }\n\n // Update cached read/recv/unread counts.\n _updateReadRecv(what, seq, ts) {\n let oldVal, doUpdate = false;\n\n seq = seq | 0;\n this.seq = this.seq | 0;\n this.read = this.read | 0;\n this.recv = this.recv | 0;\n switch (what) {\n case 'recv':\n oldVal = this.recv;\n this.recv = Math.max(this.recv, seq);\n doUpdate = (oldVal != this.recv);\n break;\n case 'read':\n oldVal = this.read;\n this.read = Math.max(this.read, seq);\n doUpdate = (oldVal != this.read);\n break;\n case 'msg':\n oldVal = this.seq;\n this.seq = Math.max(this.seq, seq);\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = (oldVal != this.seq);\n break;\n }\n\n // Sanity checks.\n if (this.recv < this.read) {\n this.recv = this.read;\n doUpdate = true;\n }\n if (this.seq < this.recv) {\n this.seq = this.recv;\n if (!this.touched || this.touched < ts) {\n this.touched = ts;\n }\n doUpdate = true;\n }\n this.unread = this.seq - this.read;\n return doUpdate;\n }\n /**\n * Get user description from global cache. The user does not need to be a\n * subscriber of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - ID of the user to fetch.\n * @return {Object} user description or undefined.\n */\n userDesc(uid) {\n // TODO: handle asynchronous requests\n const user = this._cacheGetUser(uid);\n if (user) {\n return user; // Promise.resolve(user)\n }\n }\n /**\n * Get description of the p2p peer from subscription cache.\n * @memberof Tinode.Topic#\n *\n * @return {Object} peer's description or undefined.\n */\n p2pPeerDesc() {\n if (!this.isP2PType()) {\n return undefined;\n }\n return this._users[this.name];\n }\n /**\n * Iterate over cached subscribers. If callback is undefined, use this.onMetaSub.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive subscribers one by one.\n * @param {Object=} context - Value of `this` inside the `callback`.\n */\n subscribers(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._users) {\n cb.call(context, this._users[idx], idx, this._users);\n }\n }\n }\n /**\n * Get a copy of cached tags.\n * @memberof Tinode.Topic#\n *\n * @return {Array.} a copy of tags\n */\n tags() {\n // Return a copy.\n return this._tags.slice(0);\n }\n /**\n * Get cached subscription for the given user ID.\n * @memberof Tinode.Topic#\n *\n * @param {string} uid - id of the user to query for\n * @return user description or undefined.\n */\n subscriber(uid) {\n return this._users[uid];\n }\n /**\n * Iterate over versions of a message: call callback for each version (excluding original).\n * If callback is undefined, does nothing.\n * @memberof Tinode.Topic#\n *\n * @param {number} origSeq - seq ID of the original message.\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messageVersions(origSeq, callback, context) {\n if (!callback) {\n // No callback? We are done then.\n return;\n }\n const versions = this._messageVersions[origSeq];\n if (!versions) {\n return;\n }\n versions.forEach(callback, undefined, undefined, context);\n }\n /**\n * Iterate over cached messages: call callback for each message in the range [sinceIdx, beforeIdx).\n * If callback is undefined, use this.onData.\n * @memberof Tinode.Topic#\n *\n * @param {Tinode.ForEachCallbackType} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {number} sinceId - Optional seqId to start iterating from (inclusive).\n * @param {number} beforeId - Optional seqId to stop iterating before it is reached (exclusive).\n * @param {Object} context - Value of `this` inside the `callback`.\n */\n messages(callback, sinceId, beforeId, context) {\n const cb = (callback || this.onData);\n if (cb) {\n const startIdx = typeof sinceId == 'number' ? this._messages.find({\n seq: sinceId\n }, true) : undefined;\n const beforeIdx = typeof beforeId == 'number' ? this._messages.find({\n seq: beforeId\n }, true) : undefined;\n if (startIdx != -1 && beforeIdx != -1) {\n // Step 1. Filter out all replacement messages and\n // save displayable messages in a temporary buffer.\n let msgs = [];\n this._messages.forEach((msg, unused1, unused2, i) => {\n if (this._isReplacementMsg(msg)) {\n // Skip replacements.\n return;\n }\n // In case the massage was edited, replace timestamp of the version with the original's timestamp.\n const latest = this.latestMsgVersion(msg.seq) || msg;\n if (!latest._origTs) {\n latest._origTs = latest.ts;\n latest._origSeq = latest.seq;\n latest.ts = msg.ts;\n latest.seq = msg.seq;\n }\n msgs.push({\n data: latest,\n idx: i\n });\n }, startIdx, beforeIdx, {});\n // Step 2. Loop over displayble messages invoking cb on each of them.\n msgs.forEach((val, i) => {\n cb.call(context, val.data,\n (i > 0 ? msgs[i - 1].data : undefined),\n (i < msgs.length - 1 ? msgs[i + 1].data : undefined), val.idx);\n });\n }\n }\n }\n /**\n * Get the message from cache by seq.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message seqId to search for.\n * @returns {Object} the message with the given seq or undefined, if no such message is found.\n */\n findMessage(seq) {\n const idx = this._messages.find({\n seq: seq\n });\n if (idx >= 0) {\n return this._messages.getAt(idx);\n }\n return undefined;\n }\n /**\n * Get the most recent message from cache. This method counts all messages, including deleted ranges.\n * @memberof Tinode.Topic#\n *\n * @returns {Object} the most recent cached message or undefined, if no messages are cached.\n */\n latestMessage() {\n return this._messages.getLast();\n }\n /**\n * Get the latest version for message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - original seq ID of the message.\n * @returns {Object} the latest version of the message or null if message not found.\n */\n latestMsgVersion(seq) {\n const versions = this._messageVersions[seq];\n return versions ? versions.getLast() : null;\n }\n /**\n * Get the maximum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest seq ID in cache.\n */\n maxMsgSeq() {\n return this._maxSeq;\n }\n /**\n * Get the maximum deletion ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the greatest deletion ID.\n */\n maxClearId() {\n return this._maxDel;\n }\n /**\n * Get the number of messages in the cache.\n * @memberof Tinode.Topic#\n *\n * @returns {number} count of cached messages.\n */\n messageCount() {\n return this._messages.length();\n }\n /**\n * Iterate over cached unsent messages. Wraps {@link Tinode.Topic#messages}.\n * @memberof Tinode.Topic#\n *\n * @param {function} callback - Callback which will receive messages one by one. See {@link Tinode.CBuffer#forEach}\n * @param {Object} context - Value of this inside the callback.\n */\n queuedMessages(callback, context) {\n if (!callback) {\n throw new Error(\"Callback must be provided\");\n }\n this.messages(callback, Const.LOCAL_SEQID, undefined, context);\n }\n /**\n * Get the number of topic subscribers who marked this message as either recv or read\n * Current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {string} what - what action to consider: received \"recv\" or read \"read\".\n * @param {number} seq - ID or the message read or received.\n *\n * @returns {number} the number of subscribers who marked the message with the given ID as read or received.\n */\n msgReceiptCount(what, seq) {\n let count = 0;\n if (seq > 0) {\n const me = this._tinode.getCurrentUserID();\n for (let idx in this._users) {\n const user = this._users[idx];\n if (user.user !== me && user[what] >= seq) {\n count++;\n }\n }\n }\n return count;\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as read.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - message id to check.\n * @returns {number} number of subscribers who claim to have received the message.\n */\n msgReadCount(seq) {\n return this.msgReceiptCount('read', seq);\n }\n /**\n * Get the number of topic subscribers who marked this message (and all older messages) as received.\n * The current user is excluded from the count.\n * @memberof Tinode.Topic#\n *\n * @param {number} seq - Message id to check.\n * @returns {number} Number of subscribers who claim to have received the message.\n */\n msgRecvCount(seq) {\n return this.msgReceiptCount('recv', seq);\n }\n /**\n * Check if cached message IDs indicate that the server may have more messages.\n * @memberof Tinode.Topic#\n *\n * @param {boolean} newer - if true, check for newer messages only.\n */\n msgHasMoreMessages(newer) {\n return newer ? this.seq > this._maxSeq :\n // _minSeq could be more than 1, but earlier messages could have been deleted.\n (this._minSeq > 1 && !this._noEarlierMsgs);\n }\n /**\n * Check if the given seq Id is id of the most recent message.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to check\n */\n isNewMessage(seqId) {\n return this._maxSeq <= seqId;\n }\n /**\n * Remove one message from local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to remove from cache.\n * @returns {Message} removed message or undefined if such message was not found.\n */\n flushMessage(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n delete this._messageVersions[seqId];\n if (idx >= 0) {\n this._tinode._db.remMessages(this.name, seqId);\n return this._messages.delAt(idx);\n }\n return undefined;\n }\n /**\n * Remove a range of messages from the local cache.\n * @memberof Tinode.Topic#\n *\n * @param {number} fromId seq ID of the first message to remove (inclusive).\n * @param {number} untilId seqID of the last message to remove (exclusive).\n *\n * @returns {Message[]} array of removed messages (could be empty).\n */\n flushMessageRange(fromId, untilId) {\n // Remove range from persistent cache.\n this._tinode._db.remMessages(this.name, fromId, untilId);\n\n // Remove all versions keyed by IDs in the range.\n for (let i = fromId; i < untilId; i++) {\n delete this._messageVersions[i];\n }\n\n // start, end: find insertion points (nearest == true).\n const since = this._messages.find({\n seq: fromId\n }, true);\n return since >= 0 ? this._messages.delRange(since, this._messages.find({\n seq: untilId\n }, true)) : [];\n }\n /**\n * Update message's seqId.\n * @memberof Tinode.Topic#\n *\n * @param {Object} pub message object.\n * @param {number} newSeqId new seq id for pub.\n */\n swapMessageId(pub, newSeqId) {\n const idx = this._messages.find(pub);\n const numMessages = this._messages.length();\n if (0 <= idx && idx < numMessages) {\n // Remove message with the old seq ID.\n this._messages.delAt(idx);\n this._tinode._db.remMessages(this.name, pub.seq);\n // Add message with the new seq ID.\n pub.seq = newSeqId;\n this._messages.put(pub);\n this._tinode._db.addMessage(pub);\n }\n }\n /**\n * Attempt to stop message from being sent.\n * @memberof Tinode.Topic#\n *\n * @param {number} seqId id of the message to stop sending and remove from cache.\n *\n * @returns {boolean} true if message was cancelled, false otherwise.\n */\n cancelSend(seqId) {\n const idx = this._messages.find({\n seq: seqId\n });\n if (idx >= 0) {\n const msg = this._messages.getAt(idx);\n const status = this.msgStatus(msg);\n if (status == Const.MESSAGE_STATUS_QUEUED ||\n status == Const.MESSAGE_STATUS_FAILED ||\n status == Const.MESSAGE_STATUS_FATAL) {\n this._tinode._db.remMessages(this.name, seqId);\n msg._cancelled = true;\n this._messages.delAt(idx);\n if (this.onData) {\n // Calling with no parameters to indicate the message was deleted.\n this.onData();\n }\n return true;\n }\n }\n return false;\n }\n /**\n * Get type of the topic: me, p2p, grp, fnd...\n * @memberof Tinode.Topic#\n *\n * @returns {string} One of 'me', 'p2p', 'grp', 'fnd', 'sys' or undefined.\n */\n getType() {\n return Topic.topicType(this.name);\n }\n /**\n * Get current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.AccessMode} - user's access mode\n */\n getAccessMode() {\n return this.acs;\n }\n /**\n * Set current user's access mode of the topic.\n * @memberof Tinode.Topic#\n *\n * @param {AccessMode | Object} acs - access mode to set.\n */\n setAccessMode(acs) {\n return this.acs = new AccessMode(acs);\n }\n /**\n * Get topic's default access mode.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.DefAcs} - access mode, such as {auth: `RWP`, anon: `N`}.\n */\n getDefaultAccess() {\n return this.defacs;\n }\n /**\n * Initialize new meta {@link Tinode.GetQuery} builder. The query is attched to the current topic.\n * It will not work correctly if used with a different topic.\n * @memberof Tinode.Topic#\n *\n * @returns {Tinode.MetaGetBuilder} query attached to the current topic.\n */\n startMetaQuery() {\n return new MetaGetBuilder(this);\n }\n /**\n * Check if topic is archived, i.e. private.arch == true.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is archived, false otherwise.\n */\n isArchived() {\n return this.private && !!this.private.arch;\n }\n /**\n * Check if topic is a 'me' topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a 'me' topic, false otherwise.\n */\n isMeType() {\n return Topic.isMeTopicName(this.name);\n }\n /**\n * Check if topic is a channel.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a channel, false otherwise.\n */\n isChannelType() {\n return Topic.isChannelTopicName(this.name);\n }\n /**\n * Check if topic is a group topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a group, false otherwise.\n */\n isGroupType() {\n return Topic.isGroupTopicName(this.name);\n }\n /**\n * Check if topic is a p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p topic, false otherwise.\n */\n isP2PType() {\n return Topic.isP2PTopicName(this.name);\n }\n /**\n * Check if topic is a communication topic, i.e. a group or p2p topic.\n * @memberof Tinode.Topic#\n *\n * @returns {boolean} - true if topic is a p2p or group topic, false otherwise.\n */\n isCommType() {\n return Topic.isCommTopicName(this.name);\n }\n /**\n * Get status (queued, sent, received etc) of a given message in the context\n * of this topic.\n * @memberof Tinode.Topic#\n *\n * @param {Message} msg - message to check for status.\n * @param {boolean} upd - update chached message status.\n *\n * @returns message status constant.\n */\n msgStatus(msg, upd) {\n let status = Const.MESSAGE_STATUS_NONE;\n if (this._tinode.isMe(msg.from)) {\n if (msg._sending) {\n status = Const.MESSAGE_STATUS_SENDING;\n } else if (msg._fatal || msg._cancelled) {\n status = Const.MESSAGE_STATUS_FATAL;\n } else if (msg._failed) {\n status = Const.MESSAGE_STATUS_FAILED;\n } else if (msg.seq >= Const.LOCAL_SEQID) {\n status = Const.MESSAGE_STATUS_QUEUED;\n } else if (this.msgReadCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_READ;\n } else if (this.msgRecvCount(msg.seq) > 0) {\n status = Const.MESSAGE_STATUS_RECEIVED;\n } else if (msg.seq > 0) {\n status = Const.MESSAGE_STATUS_SENT;\n }\n } else {\n status = Const.MESSAGE_STATUS_TO_ME;\n }\n\n if (upd && msg._status != status) {\n msg._status = status;\n this._tinode._db.updMessageStatus(this.name, msg.seq, status);\n }\n\n return status;\n }\n\n // Returns true if pub is meant to replace another message (e.g. original message was edited).\n _isReplacementMsg(pub) {\n return pub.head && pub.head.replace;\n }\n\n // If msg is a replacement for another message, save the msg in the message versions cache\n // as a newer version for the message it's supposed to replace.\n _maybeUpdateMessageVersionsCache(msg) {\n if (!this._isReplacementMsg(msg)) {\n // Check if this message is the original in the chain of edits and if so\n // ensure all version have the same sender.\n if (this._messageVersions[msg.seq]) {\n // Remove versions with different 'from'.\n this._messageVersions[msg.seq].filter(version => version.from == msg.from);\n if (this._messageVersions[msg.seq].isEmpty()) {\n delete this._messageVersions[msg.seq];\n }\n }\n return;\n }\n\n const targetSeq = parseInt(msg.head.replace.split(':')[1]);\n if (targetSeq > msg.seq) {\n // Substitutes are supposed to have higher seq ids.\n return;\n }\n const targetMsg = this.findMessage(targetSeq);\n if (targetMsg && targetMsg.from != msg.from) {\n // Substitute cannot change the sender.\n return;\n }\n const versions = this._messageVersions[targetSeq] || new CBuffer((a, b) => {\n return a.seq - b.seq;\n }, true);\n versions.put(msg);\n this._messageVersions[targetSeq] = versions;\n }\n\n // Process data message\n _routeData(data) {\n if (data.content) {\n if (!this.touched || this.touched < data.ts) {\n this.touched = data.ts;\n this._tinode._db.updTopic(this);\n }\n }\n\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n this.msgStatus(data, true);\n // Ackn receiving the message.\n clearTimeout(this._recvNotificationTimer);\n this._recvNotificationTimer = setTimeout(_ => {\n this._recvNotificationTimer = null;\n this.noteRecv(this._maxSeq);\n }, Const.RECV_TIMEOUT);\n }\n\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n\n const outgoing = ((!this.isChannelType() && !data.from) || this._tinode.isMe(data.from));\n\n if (data.head && data.head.webrtc && data.head.mime == Drafty.getContentType() && data.content) {\n // Rewrite VC body with info from the headers.\n data.content = Drafty.updateVideoCall(data.content, {\n state: data.head.webrtc,\n duration: data.head['webrtc-duration'],\n incoming: !outgoing,\n });\n }\n\n if (!data._noForwarding) {\n this._messages.put(data);\n this._tinode._db.addMessage(data);\n this._maybeUpdateMessageVersionsCache(data);\n }\n\n if (this.onData) {\n this.onData(data);\n }\n\n // Update locally cached contact with the new message count.\n const what = outgoing ? 'read' : 'msg';\n this._updateReadRecv(what, data.seq, data.ts);\n // Notify 'me' listeners of the change.\n this._tinode.getMeTopic()._refreshContact(what, this);\n }\n\n // Process metadata message\n _routeMeta(meta) {\n if (meta.desc) {\n this._processMetaDesc(meta.desc);\n }\n if (meta.sub && meta.sub.length > 0) {\n this._processMetaSub(meta.sub);\n }\n if (meta.del) {\n this._processDelMessages(meta.del.clear, meta.del.delseq);\n }\n if (meta.tags) {\n this._processMetaTags(meta.tags);\n }\n if (meta.cred) {\n this._processMetaCreds(meta.cred);\n }\n if (this.onMeta) {\n this.onMeta(meta);\n }\n }\n // Process presence change message\n _routePres(pres) {\n let user, uid;\n switch (pres.what) {\n case 'del':\n // Delete cached messages.\n this._processDelMessages(pres.clear, pres.delseq);\n break;\n case 'on':\n case 'off':\n // Update online status of a subscription.\n user = this._users[pres.src];\n if (user) {\n user.online = pres.what == 'on';\n } else {\n this._tinode.logger(\"WARNING: Presence update for an unknown user\", this.name, pres.src);\n }\n break;\n case 'term':\n // Attachment to topic is terminated probably due to cluster rehashing.\n this._resetSub();\n break;\n case 'upd':\n // A topic subscriber has updated his description.\n // Issue {get sub} only if the current user has no p2p topics with the updated user (p2p name is not in cache).\n // Otherwise 'me' will issue a {get desc} request.\n if (pres.src && !this._tinode.isTopicCached(pres.src)) {\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n }\n break;\n case 'acs':\n uid = pres.src || this._tinode.getCurrentUserID();\n user = this._users[uid];\n if (!user) {\n // Update for an unknown user: notification of a new subscription.\n const acs = new AccessMode().updateAll(pres.dacs);\n if (acs && acs.mode != AccessMode._NONE) {\n user = this._cacheGetUser(uid);\n if (!user) {\n user = {\n user: uid,\n acs: acs\n };\n this.getMeta(this.startMetaQuery().withOneSub(undefined, uid).build());\n } else {\n user.acs = acs;\n }\n user.updated = new Date();\n this._processMetaSub([user]);\n }\n } else {\n // Known user\n user.acs.updateAll(pres.dacs);\n // Update user's access mode.\n this._processMetaSub([{\n user: uid,\n updated: new Date(),\n acs: user.acs\n }]);\n }\n break;\n default:\n this._tinode.logger(\"INFO: Ignored presence update\", pres.what);\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n // Process {info} message\n _routeInfo(info) {\n switch (info.what) {\n case 'recv':\n case 'read':\n const user = this._users[info.from];\n if (user) {\n user[info.what] = info.seq;\n if (user.recv < user.read) {\n user.recv = user.read;\n }\n }\n const msg = this.latestMessage();\n if (msg) {\n this.msgStatus(msg, true);\n }\n\n // If this is an update from the current user, update the cache with the new count.\n if (this._tinode.isMe(info.from)) {\n this._updateReadRecv(info.what, info.seq);\n }\n\n // Notify 'me' listener of the status change.\n this._tinode.getMeTopic()._refreshContact(info.what, this);\n break;\n case 'kp':\n // Do nothing.\n break;\n case 'call':\n // Do nothing here.\n break;\n default:\n this._tinode.logger(\"INFO: Ignored info update\", info.what);\n }\n\n if (this.onInfo) {\n this.onInfo(info);\n }\n }\n // Called by Tinode when meta.desc packet is received.\n // Called by 'me' topic on contact update (desc._noForwarding is true).\n _processMetaDesc(desc) {\n if (this.isP2PType()) {\n // Synthetic desc may include defacs for p2p topics which is useless.\n // Remove it.\n delete desc.defacs;\n\n // Update to p2p desc is the same as user update. Update cached user.\n this._tinode._db.updUser(this.name, desc.public);\n }\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n // Update persistent cache.\n this._tinode._db.updTopic(this);\n\n // Notify 'me' listener, if available:\n if (this.name !== Const.TOPIC_ME && !desc._noForwarding) {\n const me = this._tinode.getMeTopic();\n if (me.onMetaSub) {\n me.onMetaSub(this);\n }\n if (me.onSubsUpdated) {\n me.onSubsUpdated([this.name], 1);\n }\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n // Called by Tinode when meta.sub is recived or in response to received\n // {ctrl} after setMeta-sub.\n _processMetaSub(subs) {\n for (let idx in subs) {\n const sub = subs[idx];\n\n // Fill defaults.\n sub.online = !!sub.online;\n // Update timestamp of the most recent subscription update.\n this._lastSubsUpdate = new Date(Math.max(this._lastSubsUpdate, sub.updated));\n\n let user = null;\n if (!sub.deleted) {\n // If this is a change to user's own permissions, update them in topic too.\n // Desc will update 'me' topic.\n if (this._tinode.isMe(sub.user) && sub.acs) {\n this._processMetaDesc({\n updated: sub.updated,\n touched: sub.touched,\n acs: sub.acs\n });\n }\n user = this._updateCachedUser(sub.user, sub);\n } else {\n // Subscription is deleted, remove it from topic (but leave in Users cache)\n delete this._users[sub.user];\n user = sub;\n }\n\n if (this.onMetaSub) {\n this.onMetaSub(user);\n }\n }\n\n if (this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._users));\n }\n }\n // Called by Tinode when meta.tags is recived.\n _processMetaTags(tags) {\n if (tags.length == 1 && tags[0] == Const.DEL_CHAR) {\n tags = [];\n }\n this._tags = tags;\n if (this.onTagsUpdated) {\n this.onTagsUpdated(tags);\n }\n }\n // Do nothing for topics other than 'me'\n _processMetaCreds(creds) {}\n // Delete cached messages and update cached transaction IDs\n _processDelMessages(clear, delseq) {\n this._maxDel = Math.max(clear, this._maxDel);\n this.clear = Math.max(clear, this.clear);\n const topic = this;\n let count = 0;\n if (Array.isArray(delseq)) {\n delseq.forEach(function(range) {\n if (!range.hi) {\n count++;\n topic.flushMessage(range.low);\n } else {\n for (let i = range.low; i < range.hi; i++) {\n count++;\n topic.flushMessage(i);\n }\n }\n });\n }\n\n if (count > 0) {\n // this._updateDeletedRanges();\n\n if (this.onData) {\n this.onData();\n }\n }\n }\n // Topic is informed that the entire response to {get what=data} has been received.\n _allMessagesReceived(count) {\n\n if (this.onAllMessagesReceived) {\n this.onAllMessagesReceived(count);\n }\n }\n // Reset subscribed state\n _resetSub() {\n this._attached = false;\n }\n // This topic is either deleted or unsubscribed from.\n _gone() {\n this._messages.reset();\n this._tinode._db.remMessages(this.name);\n this._users = {};\n this.acs = new AccessMode(null);\n this.private = null;\n this.public = null;\n this.trusted = null;\n this._maxSeq = 0;\n this._minSeq = 0;\n this._attached = false;\n\n const me = this._tinode.getMeTopic();\n if (me) {\n me._routePres({\n _noForwarding: true,\n what: 'gone',\n topic: Const.TOPIC_ME,\n src: this.name\n });\n }\n if (this.onDeleteTopic) {\n this.onDeleteTopic();\n }\n }\n // Update global user cache and local subscribers cache.\n // Don't call this method for non-subscribers.\n _updateCachedUser(uid, obj) {\n // Fetch user object from the global cache.\n // This is a clone of the stored object\n let cached = this._cacheGetUser(uid);\n cached = mergeObj(cached || {}, obj);\n // Save to global cache\n this._cachePutUser(uid, cached);\n // Save to the list of topic subsribers.\n return mergeToCache(this._users, uid, cached);\n }\n // Get local seqId for a queued message.\n _getQueuedSeqId() {\n return this._queuedSeqId++;\n }\n\n // Load most recent messages from persistent cache.\n _loadMessages(db, params) {\n const {\n since,\n before,\n limit\n } = params || {};\n return db.readMessages(this.name, {\n since: since,\n before: before,\n limit: limit || Const.DEFAULT_MESSAGES_PAGE\n })\n .then(msgs => {\n msgs.forEach((data) => {\n if (data.seq > this._maxSeq) {\n this._maxSeq = data.seq;\n }\n if (data.seq < this._minSeq || this._minSeq == 0) {\n this._minSeq = data.seq;\n }\n this._messages.put(data);\n this._maybeUpdateMessageVersionsCache(data);\n });\n return msgs.length;\n });\n }\n // Push or {pres}: message received.\n _updateReceived(seq, act) {\n this.touched = new Date();\n this.seq = seq | 0;\n // Check if message is sent by the current user. If so it's been read already.\n if (!act || this._tinode.isMe(act)) {\n this.read = this.read ? Math.max(this.read, this.seq) : this.seq;\n this.recv = this.recv ? Math.max(this.read, this.recv) : this.read;\n }\n this.unread = this.seq - (this.read | 0);\n this._tinode._db.updTopic(this);\n }\n}\n\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\n/**\n * @class TopicMe - special case of {@link Tinode.Topic} for\n * managing data of the current user, including contact list.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicMe.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicMe extends Topic {\n onContactUpdate;\n\n constructor(callbacks) {\n super(Const.TOPIC_ME, callbacks);\n\n // me-specific callbacks\n if (callbacks) {\n this.onContactUpdate = callbacks.onContactUpdate;\n }\n }\n\n // Override the original Topic._processMetaDesc.\n _processMetaDesc(desc) {\n // Check if online contacts need to be turned off because P permission was removed.\n const turnOff = (desc.acs && !desc.acs.isPresencer()) && (this.acs && this.acs.isPresencer());\n\n // Copy parameters from desc object to this topic.\n mergeObj(this, desc);\n this._tinode._db.updTopic(this);\n // Update current user's record in the global cache.\n this._updateCachedUser(this._tinode._myUID, desc);\n\n // 'P' permission was removed. All topics are offline now.\n if (turnOff) {\n this._tinode.mapTopics((cont) => {\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n this._refreshContact('off', cont);\n }\n });\n }\n\n if (this.onMetaDesc) {\n this.onMetaDesc(this);\n }\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = 0;\n subs.forEach((sub) => {\n const topicName = sub.topic;\n // Don't show 'me' and 'fnd' topics in the list of contacts.\n if (topicName == Const.TOPIC_FND || topicName == Const.TOPIC_ME) {\n return;\n }\n sub.online = !!sub.online;\n\n let cont = null;\n if (sub.deleted) {\n cont = sub;\n this._tinode.cacheRemTopic(topicName);\n this._tinode._db.remTopic(topicName);\n } else {\n // Ensure the values are defined and are integers.\n if (typeof sub.seq != 'undefined') {\n sub.seq = sub.seq | 0;\n sub.recv = sub.recv | 0;\n sub.read = sub.read | 0;\n sub.unread = sub.seq - sub.read;\n }\n\n const topic = this._tinode.getTopic(topicName);\n if (topic._new) {\n delete topic._new;\n }\n\n cont = mergeObj(topic, sub);\n this._tinode._db.updTopic(cont);\n\n if (Topic.isP2PTopicName(topicName)) {\n this._cachePutUser(topicName, cont);\n this._tinode._db.updUser(topicName, cont.public);\n }\n // Notify topic of the update if it's an external update.\n if (!sub._noForwarding && topic) {\n sub._noForwarding = true;\n topic._processMetaDesc(sub);\n }\n }\n\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(cont);\n }\n });\n\n if (this.onSubsUpdated && updateCount > 0) {\n const keys = [];\n subs.forEach((s) => {\n keys.push(s.topic);\n });\n this.onSubsUpdated(keys, updateCount);\n }\n }\n\n // Called by Tinode when meta.sub is recived.\n _processMetaCreds(creds, upd) {\n if (creds.length == 1 && creds[0] == Const.DEL_CHAR) {\n creds = [];\n }\n if (upd) {\n creds.forEach((cr) => {\n if (cr.val) {\n // Adding a credential.\n let idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && el.val == cr.val;\n });\n if (idx < 0) {\n // Not found.\n if (!cr.done) {\n // Unconfirmed credential replaces previous unconfirmed credential of the same method.\n idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n // Remove previous unconfirmed credential.\n this._credentials.splice(idx, 1);\n }\n }\n this._credentials.push(cr);\n } else {\n // Found. Maybe change 'done' status.\n this._credentials[idx].done = cr.done;\n }\n } else if (cr.resp) {\n // Handle credential confirmation.\n const idx = this._credentials.findIndex((el) => {\n return el.meth == cr.meth && !el.done;\n });\n if (idx >= 0) {\n this._credentials[idx].done = true;\n }\n }\n });\n } else {\n this._credentials = creds;\n }\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n }\n\n // Process presence change message\n _routePres(pres) {\n if (pres.what == 'term') {\n // The 'me' topic itself is detached. Mark as unsubscribed.\n this._resetSub();\n return;\n }\n\n if (pres.what == 'upd' && pres.src == Const.TOPIC_ME) {\n // Update to me's description. Request updated value.\n this.getMeta(this.startMetaQuery().withDesc().build());\n return;\n }\n\n const cont = this._tinode.cacheGetTopic(pres.src);\n if (cont) {\n switch (pres.what) {\n case 'on': // topic came online\n cont.online = true;\n break;\n case 'off': // topic went offline\n if (cont.online) {\n cont.online = false;\n cont.seen = Object.assign(cont.seen || {}, {\n when: new Date()\n });\n }\n break;\n case 'msg': // new message received\n cont._updateReceived(pres.seq, pres.act);\n break;\n case 'upd': // desc updated\n // Request updated subscription.\n this.getMeta(this.startMetaQuery().withLaterOneSub(pres.src).build());\n break;\n case 'acs': // access mode changed\n if (cont.acs) {\n cont.acs.updateAll(pres.dacs);\n } else {\n cont.acs = new AccessMode().updateAll(pres.dacs);\n }\n cont.touched = new Date();\n break;\n case 'ua':\n // user agent changed.\n cont.seen = {\n when: new Date(),\n ua: pres.ua\n };\n break;\n case 'recv':\n // user's other session marked some messges as received.\n pres.seq = pres.seq | 0;\n cont.recv = cont.recv ? Math.max(cont.recv, pres.seq) : pres.seq;\n break;\n case 'read':\n // user's other session marked some messages as read.\n pres.seq = pres.seq | 0;\n cont.read = cont.read ? Math.max(cont.read, pres.seq) : pres.seq;\n cont.recv = cont.recv ? Math.max(cont.read, cont.recv) : cont.recv;\n cont.unread = cont.seq - cont.read;\n break;\n case 'gone':\n // topic deleted or unsubscribed from.\n if (!cont._deleted) {\n cont._deleted = true;\n cont._attached = false;\n this._tinode._db.markTopicAsDeleted(pres.src);\n } else {\n this._tinode._db.remTopic(pres.src);\n }\n break;\n case 'del':\n // Update topic.del value.\n break;\n default:\n this._tinode.logger(\"INFO: Unsupported presence update in 'me'\", pres.what);\n }\n\n this._refreshContact(pres.what, cont);\n } else {\n if (pres.what == 'acs') {\n // New subscriptions and deleted/banned subscriptions have full\n // access mode (no + or - in the dacs string). Changes to known subscriptions are sent as\n // deltas, but they should not happen here.\n const acs = new AccessMode(pres.dacs);\n if (!acs || acs.mode == AccessMode._INVALID) {\n this._tinode.logger(\"ERROR: Invalid access mode update\", pres.src, pres.dacs);\n return;\n } else if (acs.mode == AccessMode._NONE) {\n this._tinode.logger(\"WARNING: Removing non-existent subscription\", pres.src, pres.dacs);\n return;\n } else {\n // New subscription. Send request for the full description.\n // Using .withOneSub (not .withLaterOneSub) to make sure IfModifiedSince is not set.\n this.getMeta(this.startMetaQuery().withOneSub(undefined, pres.src).build());\n // Create a dummy entry to catch online status update.\n const dummy = this._tinode.getTopic(pres.src);\n dummy.topic = pres.src;\n dummy.online = false;\n dummy.acs = acs;\n this._tinode._db.updTopic(dummy);\n }\n } else if (pres.what == 'tags') {\n this.getMeta(this.startMetaQuery().withTags().build());\n }\n }\n\n if (this.onPres) {\n this.onPres(pres);\n }\n }\n\n // Contact is updated, execute callbacks.\n _refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }\n\n /**\n * Publishing to TopicMe is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicMe#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'me' is not supported\"));\n }\n\n /**\n * Delete validation credential.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} topic - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n if (!this._attached) {\n return Promise.reject(new Error(\"Cannot delete credential in inactive 'me' topic\"));\n }\n // Send {del} message, return promise\n return this._tinode.delCredential(method, value).then(ctrl => {\n // Remove deleted credential from the cache.\n const index = this._credentials.findIndex((el) => {\n return el.meth == method && el.val == value;\n });\n if (index > -1) {\n this._credentials.splice(index, 1);\n }\n // Notify listeners\n if (this.onCredsUpdated) {\n this.onCredsUpdated(this._credentials);\n }\n return ctrl;\n });\n }\n\n /**\n * @callback contactFilter\n * @param {Object} contact to check for inclusion.\n * @returns {boolean} true if contact should be processed, false to exclude it.\n */\n /**\n * Iterate over cached contacts.\n *\n * @function\n * @memberof Tinode.TopicMe#\n * @param {TopicMe.ContactCallback} callback - Callback to call for each contact.\n * @param {contactFilter=} filter - Optionally filter contacts; include all if filter is false-ish, otherwise\n * include those for which filter returns true-ish.\n * @param {Object=} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, filter, context) {\n this._tinode.mapTopics((c, idx) => {\n if (c.isCommType() && (!filter || filter(c))) {\n callback.call(context, c, idx);\n }\n });\n }\n\n /**\n * Get a contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get, either a UID (for p2p topics) or a topic name.\n * @returns {Tinode.Contact} - Contact or `undefined`.\n */\n getContact(name) {\n return this._tinode.cacheGetTopic(name);\n }\n\n /**\n * Get access mode of a given contact from cache.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to get access mode for, either a UID (for p2p topics)\n * or a topic name; if missing, access mode for the 'me' topic itself.\n * @returns {string} - access mode, such as `RWP`.\n */\n getAccessMode(name) {\n if (name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont ? cont.acs : null;\n }\n return this.acs;\n }\n\n /**\n * Check if contact is archived, i.e. contact.private.arch == true.\n * @memberof Tinode.TopicMe#\n *\n * @param {string} name - Name of the contact to check archived status, either a UID (for p2p topics) or a topic name.\n * @returns {boolean} - true if contact is archived, false otherwise.\n */\n isArchived(name) {\n const cont = this._tinode.cacheGetTopic(name);\n return cont && cont.private && !!cont.private.arch;\n }\n\n /**\n * @typedef Tinode.Credential\n * @memberof Tinode\n * @type Object\n * @property {string} meth - validation method such as 'email' or 'tel'.\n * @property {string} val - credential value, i.e. 'jdoe@example.com' or '+17025551234'\n * @property {boolean} done - true if credential is validated.\n */\n /**\n * Get the user's credentials: email, phone, etc.\n * @memberof Tinode.TopicMe#\n *\n * @returns {Tinode.Credential[]} - array of credentials.\n */\n getCredentials() {\n return this._credentials;\n }\n}\n\n/**\n * @class TopicFnd - special case of {@link Tinode.Topic} for searching for\n * contacts and group topics.\n * @extends Tinode.Topic\n * @memberof Tinode\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n constructor(callbacks) {\n super(Const.TOPIC_FND, callbacks);\n }\n\n // Override the original Topic._processMetaSub\n _processMetaSub(subs) {\n let updateCount = Object.getOwnPropertyNames(this._contacts).length;\n // Reset contact list.\n this._contacts = {};\n for (let idx in subs) {\n let sub = subs[idx];\n const indexBy = sub.topic ? sub.topic : sub.user;\n\n sub = mergeToCache(this._contacts, indexBy, sub);\n updateCount++;\n\n if (this.onMetaSub) {\n this.onMetaSub(sub);\n }\n }\n\n if (updateCount > 0 && this.onSubsUpdated) {\n this.onSubsUpdated(Object.keys(this._contacts));\n }\n }\n\n /**\n * Publishing to TopicFnd is not supported. {@link Topic#publish} is overriden and thows an {Error} if called.\n * @memberof Tinode.TopicFnd#\n * @throws {Error} Always throws an error.\n */\n publish() {\n return Promise.reject(new Error(\"Publishing to 'fnd' is not supported\"));\n }\n\n /**\n * setMeta to TopicFnd resets contact list in addition to sending the message.\n * @memberof Tinode.TopicFnd#\n * @param {Tinode.SetParams} params parameters to update.\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n setMeta(params) {\n return Object.getPrototypeOf(TopicFnd.prototype).setMeta.call(this, params).then(_ => {\n if (Object.keys(this._contacts).length > 0) {\n this._contacts = {};\n if (this.onSubsUpdated) {\n this.onSubsUpdated([]);\n }\n }\n });\n }\n\n /**\n * Iterate over found contacts. If callback is undefined, use {@link this.onMetaSub}.\n * @function\n * @memberof Tinode.TopicFnd#\n * @param {TopicFnd.ContactCallback} callback - Callback to call for each contact.\n * @param {Object} context - Context to use for calling the `callback`, i.e. the value of `this` inside the callback.\n */\n contacts(callback, context) {\n const cb = (callback || this.onMetaSub);\n if (cb) {\n for (let idx in this._contacts) {\n cb.call(context, this._contacts[idx], idx, this._contacts);\n }\n }\n }\n}\n","/**\n * @module tinode-sdk\n *\n * @copyright 2015-2022 Tinode LLC.\n * @summary Javascript bindings for Tinode.\n * @license Apache 2.0\n * @version 0.20\n *\n * See https://github.com/tinode/webapp for real-life usage.\n *\n * @example\n * \n * \n * \n *\n * \n * ...\n * \n * \n */\n'use strict';\n\n// NOTE TO DEVELOPERS:\n// Localizable strings should be double quoted \"строка на другом языке\",\n// non-localizable strings should be single quoted 'non-localized'.\n\nimport AccessMode from './access-mode.js';\nimport * as Const from './config.js';\nimport CommError from './comm-error.js';\nimport Connection from './connection.js';\nimport DBCache from './db.js';\nimport Drafty from './drafty.js';\nimport LargeFileHelper from './large-file.js';\nimport MetaGetBuilder from './meta-builder.js';\nimport {\n Topic,\n TopicMe,\n TopicFnd\n} from './topic.js';\n\nimport {\n isUrlRelative,\n jsonParseHelper,\n mergeObj,\n rfc3339DateString,\n simplify\n} from './utils.js';\n\n// Re-export AccessMode\nexport {\n AccessMode\n};\n\nlet WebSocketProvider;\nif (typeof WebSocket != 'undefined') {\n WebSocketProvider = WebSocket;\n}\n\nlet XHRProvider;\nif (typeof XMLHttpRequest != 'undefined') {\n XHRProvider = XMLHttpRequest;\n}\n\nlet IndexedDBProvider;\nif (typeof indexedDB != 'undefined') {\n IndexedDBProvider = indexedDB;\n}\n\n// Re-export Drafty.\nexport {\n Drafty\n}\n\ninitForNonBrowserApp();\n\n// Utility functions\n\n// Polyfill for non-browser context, e.g. NodeJs.\nfunction initForNonBrowserApp() {\n // Tinode requirement in native mode because react native doesn't provide Base64 method\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n if (typeof btoa == 'undefined') {\n global.btoa = function(input = '') {\n let str = input;\n let output = '';\n\n for (let block = 0, charCode, i = 0, map = chars; str.charAt(i | 0) || (map = '=', i % 1); output += map.charAt(63 & block >> 8 - i % 1 * 8)) {\n\n charCode = str.charCodeAt(i += 3 / 4);\n\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\");\n }\n block = block << 8 | charCode;\n }\n\n return output;\n };\n }\n\n if (typeof atob == 'undefined') {\n global.atob = function(input = '') {\n let str = input.replace(/=+$/, '');\n let output = '';\n\n if (str.length % 4 == 1) {\n throw new Error(\"'atob' failed: The string to be decoded is not correctly encoded.\");\n }\n for (let bc = 0, bs = 0, buffer, i = 0; buffer = str.charAt(i++);\n\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n buffer = chars.indexOf(buffer);\n }\n\n return output;\n };\n }\n\n if (typeof window == 'undefined') {\n global.window = {\n WebSocket: WebSocketProvider,\n XMLHttpRequest: XHRProvider,\n indexedDB: IndexedDBProvider,\n URL: {\n createObjectURL: function() {\n throw new Error(\"Unable to use URL.createObjectURL in a non-browser application\");\n }\n }\n }\n }\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n DBCache.setDatabaseProvider(IndexedDBProvider);\n}\n\n// Detect find most useful network transport.\nfunction detectTransport() {\n if (typeof window == 'object') {\n if (window['WebSocket']) {\n return 'ws';\n } else if (window['XMLHttpRequest']) {\n // The browser or node has no websockets, using long polling.\n return 'lp';\n }\n }\n return null;\n}\n\n// btoa replacement. Stock btoa fails on on non-Latin1 strings.\nfunction b64EncodeUnicode(str) {\n // The encodeURIComponent percent-encodes UTF-8 string,\n // then the percent encoding is converted into raw bytes which\n // can be fed into btoa.\n return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n function toSolidBytes(match, p1) {\n return String.fromCharCode('0x' + p1);\n }));\n}\n\n// JSON stringify helper - pre-processor for JSON.stringify\nfunction jsonBuildHelper(key, val) {\n if (val instanceof Date) {\n // Convert javascript Date objects to rfc3339 strings\n val = rfc3339DateString(val);\n } else if (val instanceof AccessMode) {\n val = val.jsonHelper();\n } else if (val === undefined || val === null || val === false ||\n (Array.isArray(val) && val.length == 0) ||\n ((typeof val == 'object') && (Object.keys(val).length == 0))) {\n // strip out empty elements while serializing objects to JSON\n return undefined;\n }\n\n return val;\n};\n\n// Trims very long strings (encoded images) to make logged packets more readable.\nfunction jsonLoggerHelper(key, val) {\n if (typeof val == 'string' && val.length > 128) {\n return '<' + val.length + ', bytes: ' + val.substring(0, 12) + '...' + val.substring(val.length - 12) + '>';\n }\n return jsonBuildHelper(key, val);\n};\n\n// Parse browser user agent to extract browser name and version.\nfunction getBrowserInfo(ua, product) {\n ua = ua || '';\n let reactnative = '';\n // Check if this is a ReactNative app.\n if (/reactnative/i.test(product)) {\n reactnative = 'ReactNative; ';\n }\n let result;\n // Remove useless string.\n ua = ua.replace(' (KHTML, like Gecko)', '');\n // Test for WebKit-based browser.\n let m = ua.match(/(AppleWebKit\\/[.\\d]+)/i);\n if (m) {\n // List of common strings, from more useful to less useful.\n // All unknown strings get the highest (-1) priority.\n const priority = ['edg', 'chrome', 'safari', 'mobile', 'version'];\n let tmp = ua.substr(m.index + m[0].length).split(' ');\n let tokens = [];\n let version; // 1.0 in Version/1.0 or undefined;\n // Split string like 'Name/0.0.0' into ['Name', '0.0.0', 3] where the last element is the priority.\n for (let i = 0; i < tmp.length; i++) {\n let m2 = /([\\w.]+)[\\/]([\\.\\d]+)/.exec(tmp[i]);\n if (m2) {\n // Unknown values are highest priority (-1).\n tokens.push([m2[1], m2[2], priority.findIndex((e) => {\n return m2[1].toLowerCase().startsWith(e);\n })]);\n if (m2[1] == 'Version') {\n version = m2[2];\n }\n }\n }\n // Sort by priority: more interesting is earlier than less interesting.\n tokens.sort((a, b) => {\n return a[2] - b[2];\n });\n if (tokens.length > 0) {\n // Return the least common browser string and version.\n if (tokens[0][0].toLowerCase().startsWith('edg')) {\n tokens[0][0] = 'Edge';\n } else if (tokens[0][0] == 'OPR') {\n tokens[0][0] = 'Opera';\n } else if (tokens[0][0] == 'Safari' && version) {\n tokens[0][1] = version;\n }\n result = tokens[0][0] + '/' + tokens[0][1];\n } else {\n // Failed to ID the browser. Return the webkit version.\n result = m[1];\n }\n } else if (/firefox/i.test(ua)) {\n m = /Firefox\\/([.\\d]+)/g.exec(ua);\n if (m) {\n result = 'Firefox/' + m[1];\n } else {\n result = 'Firefox/?';\n }\n } else {\n // Neither AppleWebKit nor Firefox. Try the last resort.\n m = /([\\w.]+)\\/([.\\d]+)/.exec(ua);\n if (m) {\n result = m[1] + '/' + m[2];\n } else {\n m = ua.split(' ');\n result = m[0];\n }\n }\n\n // Shorten the version to one dot 'a.bb.ccc.d -> a.bb' at most.\n m = result.split('/');\n if (m.length > 1) {\n const v = m[1].split('.');\n const minor = v[1] ? '.' + v[1].substr(0, 2) : '';\n result = `${m[0]}/${v[0]}${minor}`;\n }\n return reactnative + result;\n}\n\n/**\n * The main class for interacting with Tinode server.\n */\nexport class Tinode {\n _host;\n _secure;\n\n _appName;\n\n // API Key.\n _apiKey;\n\n // Name and version of the browser.\n _browser = '';\n _platform;\n // Hardware\n _hwos = 'undefined';\n _humanLanguage = 'xx';\n\n // Logging to console enabled\n _loggingEnabled = false;\n // When logging, trip long strings (base64-encoded images) for readability\n _trimLongStrings = false;\n // UID of the currently authenticated user.\n _myUID = null;\n // Status of connection: authenticated or not.\n _authenticated = false;\n // Login used in the last successful basic authentication\n _login = null;\n // Token which can be used for login instead of login/password.\n _authToken = null;\n // Counter of received packets\n _inPacketCount = 0;\n // Counter for generating unique message IDs\n _messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);\n // Information about the server, if connected\n _serverInfo = null;\n // Push notification token. Called deviceToken for consistency with the Android SDK.\n _deviceToken = null;\n\n // Cache of pending promises by message id.\n _pendingPromises = {};\n // The Timeout object returned by the reject expired promises setInterval.\n _expirePromises = null;\n\n // Websocket or long polling connection.\n _connection = null;\n\n // Use indexDB for caching topics and messages.\n _persist = false;\n // IndexedDB wrapper object.\n _db = null;\n\n // Tinode's cache of objects\n _cache = {};\n\n /**\n * Create Tinode object.\n *\n * @param {Object} config - configuration parameters.\n * @param {string} config.appName - Name of the calling application to be reported in the User Agent.\n * @param {string} config.host - Host name and optional port number to connect to.\n * @param {string} config.apiKey - API key generated by keygen.\n * @param {string} config.transport - See {@link Tinode.Connection#transport}.\n * @param {boolean} config.secure - Use Secure WebSocket if true.\n * @param {string} config.platform - Optional platform identifier, one of \"ios\", \"web\", \"android\".\n * @param {boolen} config.persist - Use IndexedDB persistent storage.\n * @param {function} onComplete - callback to call when initialization is completed.\n */\n constructor(config, onComplete) {\n this._host = config.host;\n this._secure = config.secure;\n\n // Client-provided application name, format /\n this._appName = config.appName || \"Undefined\";\n\n // API Key.\n this._apiKey = config.apiKey;\n\n // Name and version of the browser.\n this._platform = config.platform || 'web';\n // Underlying OS.\n if (typeof navigator != 'undefined') {\n this._browser = getBrowserInfo(navigator.userAgent, navigator.product);\n this._hwos = navigator.platform;\n // This is the default language. It could be changed by client.\n this._humanLanguage = navigator.language || 'en-US';\n }\n\n Connection.logger = this.logger;\n Drafty.logger = this.logger;\n\n // WebSocket or long polling network connection.\n if (config.transport != 'lp' && config.transport != 'ws') {\n config.transport = detectTransport();\n }\n this._connection = new Connection(config, Const.PROTOCOL_VERSION, /* autoreconnect */ true);\n this._connection.onMessage = (data) => {\n // Call the main message dispatcher.\n this.#dispatchMessage(data);\n }\n\n // Ready to start sending.\n this._connection.onOpen = _ => this.#connectionOpen();\n this._connection.onDisconnect = (err, code) => this.#disconnected(err, code);\n\n // Wrapper for the reconnect iterator callback.\n this._connection.onAutoreconnectIteration = (timeout, promise) => {\n if (this.onAutoreconnectIteration) {\n this.onAutoreconnectIteration(timeout, promise);\n }\n }\n\n this._persist = config.persist;\n // Initialize object regardless. It simplifies the code.\n this._db = new DBCache(err => {\n this.logger('DB', err);\n }, this.logger);\n\n if (this._persist) {\n // Create the persistent cache.\n // Store promises to be resolved when messages load into memory.\n const prom = [];\n this._db.initDatabase().then(_ => {\n // First load topics into memory.\n return this._db.mapTopics((data) => {\n let topic = this.#cacheGet('topic', data.name);\n if (topic) {\n return;\n }\n if (data.name == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (data.name == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(data.name);\n }\n this._db.deserializeTopic(topic, data);\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Topic loaded from DB is not new.\n delete topic._new;\n // Request to load messages and save the promise.\n prom.push(topic._loadMessages(this._db));\n });\n }).then(_ => {\n // Then load users.\n return this._db.mapUsers((data) => {\n this.#cachePut('user', data.uid, mergeObj({}, data.public));\n });\n }).then(_ => {\n // Now wait for all messages to finish loading.\n return Promise.all(prom);\n }).then(_ => {\n if (onComplete) {\n onComplete();\n }\n this.logger(\"Persistent cache initialized.\");\n }).catch(err => {\n if (onComplete) {\n onComplete(err);\n }\n this.logger(\"Failed to initialize persistent cache:\", err);\n });\n } else {\n this._db.deleteDatabase().then(_ => {\n if (onComplete) {\n onComplete();\n }\n });\n }\n }\n\n // Private methods.\n\n // Console logger. Babel somehow fails to parse '...rest' parameter.\n logger(str, ...args) {\n if (this._loggingEnabled) {\n const d = new Date();\n const dateString = ('0' + d.getUTCHours()).slice(-2) + ':' +\n ('0' + d.getUTCMinutes()).slice(-2) + ':' +\n ('0' + d.getUTCSeconds()).slice(-2) + '.' +\n ('00' + d.getUTCMilliseconds()).slice(-3);\n\n console.log('[' + dateString + ']', str, args.join(' '));\n }\n }\n\n // Generator of default promises for sent packets.\n #makePromise(id) {\n let promise = null;\n if (id) {\n promise = new Promise((resolve, reject) => {\n // Stored callbacks will be called when the response packet with this Id arrives\n this._pendingPromises[id] = {\n 'resolve': resolve,\n 'reject': reject,\n 'ts': new Date()\n };\n });\n }\n return promise;\n };\n\n // Resolve or reject a pending promise.\n // Unresolved promises are stored in _pendingPromises.\n #execPromise(id, code, onOK, errorText) {\n const callbacks = this._pendingPromises[id];\n if (callbacks) {\n delete this._pendingPromises[id];\n if (code >= 200 && code < 400) {\n if (callbacks.resolve) {\n callbacks.resolve(onOK);\n }\n } else if (callbacks.reject) {\n callbacks.reject(new CommError(errorText, code));\n }\n }\n }\n\n // Send a packet. If packet id is provided return a promise.\n #send(pkt, id) {\n let promise;\n if (id) {\n promise = this.#makePromise(id);\n }\n pkt = simplify(pkt);\n let msg = JSON.stringify(pkt);\n this.logger(\"out: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : msg));\n try {\n this._connection.sendText(msg);\n } catch (err) {\n // If sendText throws, wrap the error in a promise or rethrow.\n if (id) {\n this.#execPromise(id, Connection.NETWORK_ERROR, null, err.message);\n } else {\n throw err;\n }\n }\n return promise;\n }\n\n // The main message dispatcher.\n #dispatchMessage(data) {\n // Skip empty response. This happens when LP times out.\n if (!data)\n return;\n\n this._inPacketCount++;\n\n // Send raw message to listener\n if (this.onRawMessage) {\n this.onRawMessage(data);\n }\n\n if (data === '0') {\n // Server response to a network probe.\n if (this.onNetworkProbe) {\n this.onNetworkProbe();\n }\n // No processing is necessary.\n return;\n }\n\n let pkt = JSON.parse(data, jsonParseHelper);\n if (!pkt) {\n this.logger(\"in: \" + data);\n this.logger(\"ERROR: failed to parse data\");\n } else {\n this.logger(\"in: \" + (this._trimLongStrings ? JSON.stringify(pkt, jsonLoggerHelper) : data));\n\n // Send complete packet to listener\n if (this.onMessage) {\n this.onMessage(pkt);\n }\n\n if (pkt.ctrl) {\n // Handling {ctrl} message\n if (this.onCtrlMessage) {\n this.onCtrlMessage(pkt.ctrl);\n }\n\n // Resolve or reject a pending promise, if any\n if (pkt.ctrl.id) {\n this.#execPromise(pkt.ctrl.id, pkt.ctrl.code, pkt.ctrl, pkt.ctrl.text);\n }\n setTimeout(_ => {\n if (pkt.ctrl.code == 205 && pkt.ctrl.text == 'evicted') {\n // User evicted from topic.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._resetSub();\n if (pkt.ctrl.params && pkt.ctrl.params.unsub) {\n topic._gone();\n }\n }\n } else if (pkt.ctrl.code < 300 && pkt.ctrl.params) {\n if (pkt.ctrl.params.what == 'data') {\n // code=208, all messages received: \"params\":{\"count\":11,\"what\":\"data\"},\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n topic._allMessagesReceived(pkt.ctrl.params.count);\n }\n } else if (pkt.ctrl.params.what == 'sub') {\n // code=204, the topic has no (refreshed) subscriptions.\n const topic = this.#cacheGet('topic', pkt.ctrl.topic);\n if (topic) {\n // Trigger topic.onSubsUpdated.\n topic._processMetaSub([]);\n }\n }\n }\n }, 0);\n } else {\n setTimeout(_ => {\n if (pkt.meta) {\n // Handling a {meta} message.\n // Preferred API: Route meta to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.meta.topic);\n if (topic) {\n topic._routeMeta(pkt.meta);\n }\n\n if (pkt.meta.id) {\n this.#execPromise(pkt.meta.id, 200, pkt.meta, 'META');\n }\n\n // Secondary API: callback\n if (this.onMetaMessage) {\n this.onMetaMessage(pkt.meta);\n }\n } else if (pkt.data) {\n // Handling {data} message\n // Preferred API: Route data to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.data.topic);\n if (topic) {\n topic._routeData(pkt.data);\n }\n\n // Secondary API: Call callback\n if (this.onDataMessage) {\n this.onDataMessage(pkt.data);\n }\n } else if (pkt.pres) {\n // Handling {pres} message\n // Preferred API: Route presence to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.pres.topic);\n if (topic) {\n topic._routePres(pkt.pres);\n }\n\n // Secondary API - callback\n if (this.onPresMessage) {\n this.onPresMessage(pkt.pres);\n }\n } else if (pkt.info) {\n // {info} message - read/received notifications and key presses\n // Preferred API: Route {info}} to topic, if one is registered\n const topic = this.#cacheGet('topic', pkt.info.topic);\n if (topic) {\n topic._routeInfo(pkt.info);\n }\n\n // Secondary API - callback\n if (this.onInfoMessage) {\n this.onInfoMessage(pkt.info);\n }\n } else {\n this.logger(\"ERROR: Unknown packet received.\");\n }\n }, 0);\n }\n }\n }\n\n // Connection open, ready to start sending.\n #connectionOpen() {\n if (!this._expirePromises) {\n // Reject promises which have not been resolved for too long.\n this._expirePromises = setInterval(_ => {\n const err = new CommError(\"timeout\", 504);\n const expires = new Date(new Date().getTime() - Const.EXPIRE_PROMISES_TIMEOUT);\n for (let id in this._pendingPromises) {\n let callbacks = this._pendingPromises[id];\n if (callbacks && callbacks.ts < expires) {\n this.logger(\"Promise expired\", id);\n delete this._pendingPromises[id];\n if (callbacks.reject) {\n callbacks.reject(err);\n }\n }\n }\n }, Const.EXPIRE_PROMISES_PERIOD);\n }\n this.hello();\n }\n\n #disconnected(err, code) {\n this._inPacketCount = 0;\n this._serverInfo = null;\n this._authenticated = false;\n\n if (this._expirePromises) {\n clearInterval(this._expirePromises);\n this._expirePromises = null;\n }\n\n // Mark all topics as unsubscribed\n this.#cacheMap('topic', (topic, key) => {\n topic._resetSub();\n });\n\n // Reject all pending promises\n for (let key in this._pendingPromises) {\n const callbacks = this._pendingPromises[key];\n if (callbacks && callbacks.reject) {\n callbacks.reject(err);\n }\n }\n this._pendingPromises = {};\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n }\n\n // Get User Agent string\n #getUserAgent() {\n return this._appName + ' (' + (this._browser ? this._browser + '; ' : '') + this._hwos + '); ' + Const.LIBRARY;\n }\n\n // Generator of packets stubs\n #initPacket(type, topic) {\n switch (type) {\n case 'hi':\n return {\n 'hi': {\n 'id': this.getNextUniqueId(),\n 'ver': Const.VERSION,\n 'ua': this.#getUserAgent(),\n 'dev': this._deviceToken,\n 'lang': this._humanLanguage,\n 'platf': this._platform\n }\n };\n\n case 'acc':\n return {\n 'acc': {\n 'id': this.getNextUniqueId(),\n 'user': null,\n 'scheme': null,\n 'secret': null,\n 'tmpscheme': null,\n 'tmpsecret': null,\n 'login': false,\n 'tags': null,\n 'desc': {},\n 'cred': {}\n }\n };\n\n case 'login':\n return {\n 'login': {\n 'id': this.getNextUniqueId(),\n 'scheme': null,\n 'secret': null\n }\n };\n\n case 'sub':\n return {\n 'sub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'set': {},\n 'get': {}\n }\n };\n\n case 'leave':\n return {\n 'leave': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'unsub': false\n }\n };\n\n case 'pub':\n return {\n 'pub': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'noecho': false,\n 'head': null,\n 'content': {}\n }\n };\n\n case 'get':\n return {\n 'get': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'desc': {},\n 'sub': {},\n 'data': {}\n }\n };\n\n case 'set':\n return {\n 'set': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'desc': {},\n 'sub': {},\n 'tags': [],\n 'ephemeral': {}\n }\n };\n\n case 'del':\n return {\n 'del': {\n 'id': this.getNextUniqueId(),\n 'topic': topic,\n 'what': null,\n 'delseq': null,\n 'user': null,\n 'hard': false\n }\n };\n\n case 'note':\n return {\n 'note': {\n // no id by design (except calls).\n 'topic': topic,\n 'what': null, // one of \"recv\", \"read\", \"kp\", \"call\"\n 'seq': undefined // the server-side message id acknowledged as received or read.\n }\n };\n\n default:\n throw new Error(`Unknown packet type requested: ${type}`);\n }\n }\n\n // Cache management\n #cachePut(type, name, obj) {\n this._cache[type + ':' + name] = obj;\n }\n #cacheGet(type, name) {\n return this._cache[type + ':' + name];\n }\n #cacheDel(type, name) {\n delete this._cache[type + ':' + name];\n }\n\n // Enumerate all items in cache, call func for each item.\n // Enumeration stops if func returns true.\n #cacheMap(type, func, context) {\n const key = type ? type + ':' : undefined;\n for (let idx in this._cache) {\n if (!key || idx.indexOf(key) == 0) {\n if (func.call(context, this._cache[idx], idx)) {\n break;\n }\n }\n }\n }\n\n // Make limited cache management available to topic.\n // Caching user.public only. Everything else is per-topic.\n #attachCacheToTopic(topic) {\n topic._tinode = this;\n\n topic._cacheGetUser = (uid) => {\n const pub = this.#cacheGet('user', uid);\n if (pub) {\n return {\n user: uid,\n public: mergeObj({}, pub)\n };\n }\n return undefined;\n };\n topic._cachePutUser = (uid, user) => {\n this.#cachePut('user', uid, mergeObj({}, user.public));\n };\n topic._cacheDelUser = (uid) => {\n this.#cacheDel('user', uid);\n };\n topic._cachePutSelf = _ => {\n this.#cachePut('topic', topic.name, topic);\n };\n topic._cacheDelSelf = _ => {\n this.#cacheDel('topic', topic.name);\n };\n }\n\n // On successful login save server-provided data.\n #loginSuccessful(ctrl) {\n if (!ctrl.params || !ctrl.params.user) {\n return ctrl;\n }\n // This is a response to a successful login,\n // extract UID and security token, save it in Tinode module\n this._myUID = ctrl.params.user;\n this._authenticated = (ctrl && ctrl.code >= 200 && ctrl.code < 300);\n if (ctrl.params && ctrl.params.token && ctrl.params.expires) {\n this._authToken = {\n token: ctrl.params.token,\n expires: ctrl.params.expires\n };\n } else {\n this._authToken = null;\n }\n\n if (this.onLogin) {\n this.onLogin(ctrl.code, ctrl.text);\n }\n\n return ctrl;\n }\n\n // Static methods.\n /**\n * Helper method to package account credential.\n *\n * @param {string | Credential} meth - validation method or object with validation data.\n * @param {string=} val - validation value (e.g. email or phone number).\n * @param {Object=} params - validation parameters.\n * @param {string=} resp - validation response.\n *\n * @returns {Array.} array with a single credential or null if no valid credentials were given.\n */\n static credential(meth, val, params, resp) {\n if (typeof meth == 'object') {\n ({\n val,\n params,\n resp,\n meth\n } = meth);\n }\n if (meth && (val || resp)) {\n return [{\n 'meth': meth,\n 'val': val,\n 'resp': resp,\n 'params': params\n }];\n }\n return null;\n }\n\n /**\n * Determine topic type from topic's name: grp, p2p, me, fnd, sys.\n * @param {string} name - Name of the topic to test.\n * @returns {string} One of \"me\", \"fnd\", \"sys\", \"grp\",\n * \"p2p\" or undefined.\n */\n static topicType(name) {\n return Topic.topicType(name);\n }\n\n /**\n * Check if the given topic name is a name of a 'me' topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a 'me' topic, false otherwise.\n */\n static isMeTopicName(name) {\n return Topic.isMeTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a group topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a group topic, false otherwise.\n */\n static isGroupTopicName(name) {\n return Topic.isGroupTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a p2p topic.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p topic, false otherwise.\n */\n static isP2PTopicName(name) {\n return Topic.isP2PTopicName(name);\n }\n /**\n * Check if the given topic name is a name of a communication topic, i.e. P2P or group.\n * @param {string} name - Name of the topic to test.\n * @returns {boolean} true if the name is a name of a p2p or group topic, false otherwise.\n */\n static isCommTopicName(name) {\n return Topic.isCommTopicName(name);\n }\n /**\n * Check if the topic name is a name of a new topic.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a new topic, false otherwise.\n */\n static isNewGroupTopicName(name) {\n return Topic.isNewGroupTopicName(name);\n }\n /**\n * Check if the topic name is a name of a channel.\n * @param {string} name - topic name to check.\n * @returns {boolean} true if the name is a name of a channel, false otherwise.\n */\n static isChannelTopicName(name) {\n return Topic.isChannelTopicName(name);\n }\n /**\n * Get information about the current version of this Tinode client library.\n * @returns {string} semantic version of the library, e.g. \"0.15.5-rc1\".\n */\n static getVersion() {\n return Const.VERSION;\n }\n /**\n * To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.\n * @static\n *\n * @param wsProvider WebSocket provider, e.g. for nodeJS , require('ws').\n * @param xhrProvider XMLHttpRequest provider, e.g. for node require('xhr').\n */\n static setNetworkProviders(wsProvider, xhrProvider) {\n WebSocketProvider = wsProvider;\n XHRProvider = xhrProvider;\n\n Connection.setNetworkProviders(WebSocketProvider, XHRProvider);\n LargeFileHelper.setNetworkProvider(XHRProvider);\n }\n /**\n * To use Tinode in a non browser context, supply indexedDB provider.\n * @static\n *\n * @param idbProvider indexedDB provider, e.g. for nodeJS , require('fake-indexeddb').\n */\n static setDatabaseProvider(idbProvider) {\n IndexedDBProvider = idbProvider;\n\n DBCache.setDatabaseProvider(IndexedDBProvider);\n }\n /**\n * Return information about the current name and version of this Tinode library.\n * @static\n *\n * @returns {string} the name of the library and it's version.\n */\n static getLibrary() {\n return Const.LIBRARY;\n }\n /**\n * Check if the given string represents NULL value as defined by Tinode ('\\u2421').\n * @param {string} str - string to check for NULL value.\n * @returns {boolean} true if string represents NULL value, false otherwise.\n */\n static isNullValue(str) {\n return str === Const.DEL_CHAR;\n }\n\n // Instance methods.\n\n // Generates unique message IDs\n getNextUniqueId() {\n return (this._messageId != 0) ? '' + this._messageId++ : undefined;\n };\n\n /**\n * Connect to the server.\n *\n * @param {string} host_ - name of the host to connect to.\n * @return {Promise} Promise resolved/rejected when the connection call completes:\n * resolve() is called without parameters, reject() receives the\n * Error as a single parameter.\n */\n connect(host_) {\n return this._connection.connect(host_);\n }\n\n /**\n * Attempt to reconnect to the server immediately.\n *\n * @param {string} force - if true, reconnect even if there is a connection already.\n */\n reconnect(force) {\n this._connection.reconnect(force);\n }\n\n /**\n * Disconnect from the server.\n */\n disconnect() {\n this._connection.disconnect();\n }\n\n /**\n * Clear persistent cache: remove IndexedDB.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n clearStorage() {\n if (this._db.isReady()) {\n return this._db.deleteDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Initialize persistent cache: create IndexedDB cache.\n *\n * @return {Promise} Promise resolved/rejected when the operation is completed.\n */\n initStorage() {\n if (!this._db.isReady()) {\n return this._db.initDatabase();\n }\n return Promise.resolve();\n }\n\n /**\n * Send a network probe message to make sure the connection is alive.\n */\n networkProbe() {\n this._connection.probe();\n }\n\n /**\n * Check for live connection to server.\n *\n * @returns {boolean} true if there is a live connection, false otherwise.\n */\n isConnected() {\n return this._connection.isConnected();\n }\n\n /**\n * Check if connection is authenticated (last login was successful).\n *\n * @returns {boolean} true if authenticated, false otherwise.\n */\n isAuthenticated() {\n return this._authenticated;\n }\n\n /**\n * Add API key and auth token to the relative URL making it usable for getting data\n * from the server in a simple HTTP GET request.\n *\n * @param {string} URL - URL to wrap.\n * @returns {string} URL with appended API key and token, if valid token is present.\n */\n authorizeURL(url) {\n if (typeof url != 'string') {\n return url;\n }\n\n if (isUrlRelative(url)) {\n // Fake base to make the relative URL parseable.\n const base = 'scheme://host/';\n const parsed = new URL(url, base);\n if (this._apiKey) {\n parsed.searchParams.append('apikey', this._apiKey);\n }\n if (this._authToken && this._authToken.token) {\n parsed.searchParams.append('auth', 'token');\n parsed.searchParams.append('secret', this._authToken.token);\n }\n // Convert back to string and strip fake base URL except for the root slash.\n url = parsed.toString().substring(base.length - 1);\n }\n return url;\n }\n\n /**\n * @typedef AccountParams\n * @type {Object}\n * @property {DefAcs=} defacs - Default access parameters for user's me topic.\n * @property {Object=} public - Public application-defined data exposed on me topic.\n * @property {Object=} private - Private application-defined data accessible on me topic.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n * @property {Array.} tags - array of string tags for user discovery.\n * @property {string} scheme - Temporary authentication scheme for password reset.\n * @property {string} secret - Temporary authentication secret for password reset.\n * @property {Array.=} attachments - Array of references to out of band attachments used in account description.\n */\n /**\n * @typedef DefAcs\n * @type {Object}\n * @property {string=} auth - Access mode for me for authenticated users.\n * @property {string=} anon - Access mode for me for anonymous users.\n */\n\n /**\n * Create or update an account.\n *\n * @param {string} uid - User id to update\n * @param {string} scheme - Authentication scheme; \"basic\" and \"anonymous\" are the currently supported schemes.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n account(uid, scheme, secret, login, params) {\n const pkt = this.#initPacket('acc');\n pkt.acc.user = uid;\n pkt.acc.scheme = scheme;\n pkt.acc.secret = secret;\n // Log in to the new account using selected scheme\n pkt.acc.login = login;\n\n if (params) {\n pkt.acc.desc.defacs = params.defacs;\n pkt.acc.desc.public = params.public;\n pkt.acc.desc.private = params.private;\n pkt.acc.desc.trusted = params.trusted;\n\n pkt.acc.tags = params.tags;\n pkt.acc.cred = params.cred;\n\n pkt.acc.tmpscheme = params.scheme;\n pkt.acc.tmpsecret = params.secret;\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n return this.#send(pkt, pkt.acc.id);\n }\n\n /**\n * Create a new user. Wrapper for {@link Tinode#account}.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication.\n * @param {boolean=} login - Use new account to authenticate current session\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccount(scheme, secret, login, params) {\n let promise = this.account(Const.USER_NEW, scheme, secret, login, params);\n if (login) {\n promise = promise.then(ctrl => this.#loginSuccessful(ctrl));\n }\n return promise;\n }\n\n /**\n * Create user with 'basic' authentication scheme and immediately\n * use it for authentication. Wrapper for {@link Tinode#account}.\n *\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - User data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n createAccountBasic(username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.createAccount('basic',\n b64EncodeUnicode(username + ':' + password), true, params);\n }\n\n /**\n * Update user's credentials for 'basic' authentication scheme. Wrapper for {@link Tinode#account}.\n *\n * @param {string} uid - User ID to update.\n * @param {string} username - Login to use for the new account.\n * @param {string} password - User's password.\n * @param {AccountParams=} params - data to pass to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n updateAccountBasic(uid, username, password, params) {\n // Make sure we are not using 'null' or 'undefined';\n username = username || '';\n password = password || '';\n return this.account(uid, 'basic',\n b64EncodeUnicode(username + ':' + password), false, params);\n }\n\n /**\n * Send handshake to the server.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n hello() {\n const pkt = this.#initPacket('hi');\n\n return this.#send(pkt, pkt.hi.id)\n .then(ctrl => {\n // Reset backoff counter on successful connection.\n this._connection.backoffReset();\n\n // Server response contains server protocol version, build, constraints,\n // session ID for long polling. Save them.\n if (ctrl.params) {\n this._serverInfo = ctrl.params;\n }\n\n if (this.onConnect) {\n this.onConnect();\n }\n\n return ctrl;\n }).catch(err => {\n this._connection.reconnect(true);\n\n if (this.onDisconnect) {\n this.onDisconnect(err);\n }\n });\n }\n\n /**\n * Set or refresh the push notifications/device token. If the client is connected,\n * the deviceToken can be sent to the server.\n *\n * @param {string} dt - token obtained from the provider or false,\n * null or undefined to clear the token.\n *\n * @returns true if attempt was made to send the update to the server.\n */\n setDeviceToken(dt) {\n let sent = false;\n // Convert any falsish value to null.\n dt = dt || null;\n if (dt != this._deviceToken) {\n this._deviceToken = dt;\n if (this.isConnected() && this.isAuthenticated()) {\n this.#send({\n 'hi': {\n 'dev': dt || Tinode.DEL_CHAR\n }\n });\n sent = true;\n }\n }\n return sent;\n }\n\n /**\n * @typedef Credential\n * @type {Object}\n * @property {string} meth - validation method.\n * @property {string} val - value to validate (e.g. email or phone number).\n * @property {string} resp - validation response.\n * @property {Object} params - validation parameters.\n */\n /**\n * Authenticate current session.\n *\n * @param {string} scheme - Authentication scheme; \"basic\" is the only currently supported scheme.\n * @param {string} secret - Authentication secret, assumed to be already base64 encoded.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected when server reply is received.\n */\n login(scheme, secret, cred) {\n const pkt = this.#initPacket('login');\n pkt.login.scheme = scheme;\n pkt.login.secret = secret;\n pkt.login.cred = cred;\n\n return this.#send(pkt, pkt.login.id)\n .then(ctrl => this.#loginSuccessful(ctrl));\n }\n\n /**\n * Wrapper for {@link Tinode#login} with basic authentication\n *\n * @param {string} uname - User name.\n * @param {string} password - Password.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginBasic(uname, password, cred) {\n return this.login('basic', b64EncodeUnicode(uname + ':' + password), cred)\n .then(ctrl => {\n this._login = uname;\n return ctrl;\n });\n }\n\n /**\n * Wrapper for {@link Tinode#login} with token authentication\n *\n * @param {string} token - Token received in response to earlier login.\n * @param {Credential=} cred - credential confirmation, if required.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n loginToken(token, cred) {\n return this.login('token', token, cred);\n }\n\n /**\n * Send a request for resetting an authentication secret.\n *\n * @param {string} scheme - authentication scheme to reset.\n * @param {string} method - method to use for resetting the secret, such as \"email\" or \"tel\".\n * @param {string} value - value of the credential to use, a specific email address or a phone number.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving the server reply.\n */\n requestResetAuthSecret(scheme, method, value) {\n return this.login('reset', b64EncodeUnicode(scheme + ':' + method + ':' + value));\n }\n\n /**\n * @typedef AuthToken\n * @type {Object}\n * @property {string} token - Token value.\n * @property {Date} expires - Token expiration time.\n */\n /**\n * Get stored authentication token.\n *\n * @returns {AuthToken} authentication token.\n */\n getAuthToken() {\n if (this._authToken && (this._authToken.expires.getTime() > Date.now())) {\n return this._authToken;\n } else {\n this._authToken = null;\n }\n return null;\n }\n\n /**\n * Application may provide a saved authentication token.\n *\n * @param {AuthToken} token - authentication token.\n */\n setAuthToken(token) {\n this._authToken = token;\n }\n\n /**\n * @typedef SetParams\n * @type {Object}\n * @property {SetDesc=} desc - Topic initialization parameters when creating a new topic or a new subscription.\n * @property {SetSub=} sub - Subscription initialization parameters.\n * @property {Array.=} attachments - URLs of out of band attachments used in parameters.\n */\n /**\n * @typedef SetDesc\n * @type {Object}\n * @property {DefAcs=} defacs - Default access mode.\n * @property {Object=} public - Free-form topic description, publically accessible.\n * @property {Object=} private - Free-form topic description accessible only to the owner.\n * @property {Object=} trusted - Trusted user data which can be set by a root user only.\n */\n /**\n * @typedef SetSub\n * @type {Object}\n * @property {string=} user - UID of the user affected by the request. Default (empty) - current user.\n * @property {string=} mode - User access mode, either requested or assigned dependent on context.\n */\n /**\n * Send a topic subscription request.\n *\n * @param {string} topic - Name of the topic to subscribe to.\n * @param {GetQuery=} getParams - Optional subscription metadata query\n * @param {SetParams=} setParams - Optional initialization parameters\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n subscribe(topicName, getParams, setParams) {\n const pkt = this.#initPacket('sub', topicName)\n if (!topicName) {\n topicName = Const.TOPIC_NEW;\n }\n\n pkt.sub.get = getParams;\n\n if (setParams) {\n if (setParams.sub) {\n pkt.sub.set.sub = setParams.sub;\n }\n\n if (setParams.desc) {\n const desc = setParams.desc;\n if (Tinode.isNewGroupTopicName(topicName)) {\n // Full set.desc params are used for new topics only\n pkt.sub.set.desc = desc;\n } else if (Tinode.isP2PTopicName(topicName) && desc.defacs) {\n // Use optional default permissions only.\n pkt.sub.set.desc = {\n defacs: desc.defacs\n };\n }\n }\n\n // See if external objects were used in topic description.\n if (Array.isArray(setParams.attachments) && setParams.attachments.length > 0) {\n pkt.extra = {\n attachments: setParams.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n\n if (setParams.tags) {\n pkt.sub.set.tags = setParams.tags;\n }\n }\n return this.#send(pkt, pkt.sub.id);\n }\n\n /**\n * Detach and optionally unsubscribe from the topic\n *\n * @param {string} topic - Topic to detach from.\n * @param {boolean} unsub - If true, detach and unsubscribe, otherwise just detach.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n leave(topic, unsub) {\n const pkt = this.#initPacket('leave', topic);\n pkt.leave.unsub = unsub;\n\n return this.#send(pkt, pkt.leave.id);\n }\n\n /**\n * Create message draft without sending it to the server.\n *\n * @param {string} topic - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Object} new message which can be sent to the server or otherwise used.\n */\n createMessage(topic, content, noEcho) {\n const pkt = this.#initPacket('pub', topic);\n\n let dft = typeof content == 'string' ? Drafty.parse(content) : content;\n if (dft && !Drafty.isPlainText(dft)) {\n pkt.pub.head = {\n mime: Drafty.getContentType()\n };\n content = dft;\n }\n pkt.pub.noecho = noEcho;\n pkt.pub.content = content;\n\n return pkt.pub;\n }\n\n /**\n * Publish {data} message to topic.\n *\n * @param {string} topicName - Name of the topic to publish to.\n * @param {Object} content - Payload to publish.\n * @param {boolean=} noEcho - If true, tell the server not to echo the message to the original session.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publish(topicName, content, noEcho) {\n return this.publishMessage(\n this.createMessage(topicName, content, noEcho)\n );\n }\n\n /**\n * Publish message to topic. The message should be created by {@link Tinode#createMessage}.\n *\n * @param {Object} pub - Message to publish.\n * @param {Array.=} attachments - array of URLs with attachments.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n publishMessage(pub, attachments) {\n // Make a shallow copy. Needed in order to clear locally-assigned temp values;\n pub = Object.assign({}, pub);\n pub.seq = undefined;\n pub.from = undefined;\n pub.ts = undefined;\n const msg = {\n pub: pub,\n };\n if (attachments) {\n msg.extra = {\n attachments: attachments.filter(ref => isUrlRelative(ref))\n };\n }\n return this.#send(msg, pub.id);\n }\n\n /**\n * Out of band notification: notify topic that an external (push) notification was recived by the client.\n *\n * @param {object} data - notification payload.\n * @param {string} data.what - notification type, 'msg', 'read', 'sub'.\n * @param {string} data.topic - name of the updated topic.\n * @param {number=} data.seq - seq ID of the affected message.\n * @param {string=} data.xfrom - UID of the sender.\n * @param {object=} data.given - new subscription 'given', e.g. 'ASWP...'.\n * @param {object=} data.want - new subscription 'want', e.g. 'RWJ...'.\n */\n oobNotification(data) {\n this.logger('oob: ' + (this._trimLongStrings ? JSON.stringify(data, jsonLoggerHelper) : data));\n\n switch (data.what) {\n case 'msg':\n if (!data.seq || data.seq < 1 || !data.topic) {\n // Server sent invalid data.\n break;\n }\n\n if (!this.isConnected()) {\n // Let's ignore the message if there is no connection: no connection means there are no open\n // tabs with Tinode.\n break;\n }\n\n const topic = this.#cacheGet('topic', data.topic);\n if (!topic) {\n // TODO: check if there is a case when a message can arrive from an unknown topic.\n break;\n }\n\n if (topic.isSubscribed()) {\n // No need to fetch: topic is already subscribed and got data through normal channel.\n break;\n }\n\n if (topic.maxMsgSeq() < data.seq) {\n if (topic.isChannelType()) {\n topic._updateReceived(data.seq, 'fake-uid');\n }\n\n // New message.\n if (data.xfrom && !this.#cacheGet('user', data.xfrom)) {\n // Message from unknown sender, fetch description from the server.\n // Sending asynchronously without a subscription.\n this.getMeta(data.xfrom, new MetaGetBuilder().withDesc().build()).catch(err => {\n this.logger(\"Failed to get the name of a new sender\", err);\n });\n }\n\n topic.subscribe(null).then(_ => {\n return topic.getMeta(new MetaGetBuilder(topic).withLaterData(24).withLaterDel(24).build());\n }).then(_ => {\n // Allow data fetch to complete and get processed successfully.\n topic.leaveDelayed(false, 1000);\n }).catch(err => {\n this.logger(\"On push data fetch failed\", err);\n }).finally(_ => {\n this.getMeTopic()._refreshContact('msg', topic);\n });\n }\n break;\n\n case 'read':\n this.getMeTopic()._routePres({\n what: 'read',\n seq: data.seq\n });\n break;\n\n case 'sub':\n if (!this.isMe(data.xfrom)) {\n // TODO: handle updates from other users.\n break;\n }\n\n const mode = {\n given: data.modeGiven,\n want: data.modeWant\n };\n const acs = new AccessMode(mode);\n const pres = (!acs.mode || acs.mode == AccessMode._NONE) ?\n // Subscription deleted.\n {\n what: 'gone',\n src: data.topic\n } :\n // New subscription or subscription updated.\n {\n what: 'acs',\n src: data.topic,\n dacs: mode\n };\n this.getMeTopic()._routePres(pres);\n break;\n\n default:\n this.logger(\"Unknown push type ignored\", data.what);\n }\n }\n\n /**\n * @typedef GetQuery\n * @type {Object}\n * @property {GetOptsType=} desc - If provided (even if empty), fetch topic description.\n * @property {GetOptsType=} sub - If provided (even if empty), fetch topic subscriptions.\n * @property {GetDataType=} data - If provided (even if empty), get messages.\n */\n\n /**\n * @typedef GetOptsType\n * @type {Object}\n * @property {Date=} ims - \"If modified since\", fetch data only it was was modified since stated date.\n * @property {number=} limit - Maximum number of results to return. Ignored when querying topic description.\n */\n\n /**\n * @typedef GetDataType\n * @type {Object}\n * @property {number=} since - Load messages with seq id equal or greater than this value.\n * @property {number=} before - Load messages with seq id lower than this number.\n * @property {number=} limit - Maximum number of results to return.\n */\n\n /**\n * Request topic metadata\n *\n * @param {string} topic - Name of the topic to query.\n * @param {GetQuery} params - Parameters of the query. Use {@link Tinode.MetaGetBuilder} to generate.\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n getMeta(topic, params) {\n const pkt = this.#initPacket('get', topic);\n\n pkt.get = mergeObj(pkt.get, params);\n\n return this.#send(pkt, pkt.get.id);\n }\n\n /**\n * Update topic's metadata: description, subscribtions.\n *\n * @param {string} topic - Topic to update.\n * @param {SetParams} params - topic metadata to update.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n setMeta(topic, params) {\n const pkt = this.#initPacket('set', topic);\n const what = [];\n\n if (params) {\n ['desc', 'sub', 'tags', 'cred', 'ephemeral'].forEach(function(key) {\n if (params.hasOwnProperty(key)) {\n what.push(key);\n pkt.set[key] = params[key];\n }\n });\n\n if (Array.isArray(params.attachments) && params.attachments.length > 0) {\n pkt.extra = {\n attachments: params.attachments.filter(ref => isUrlRelative(ref))\n };\n }\n }\n\n if (what.length == 0) {\n return Promise.reject(new Error(\"Invalid {set} parameters\"));\n }\n\n return this.#send(pkt, pkt.set.id);\n }\n\n /**\n * Range of message IDs to delete.\n *\n * @typedef DelRange\n * @type {Object}\n * @property {number} low - low end of the range, inclusive (closed).\n * @property {number=} hi - high end of the range, exclusive (open).\n */\n /**\n * Delete some or all messages in a topic.\n *\n * @param {string} topic - Topic name to delete messages from.\n * @param {DelRange[]} list - Ranges of message IDs to delete.\n * @param {boolean=} hard - Hard or soft delete\n *\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delMessages(topic, ranges, hard) {\n const pkt = this.#initPacket('del', topic);\n\n pkt.del.what = 'msg';\n pkt.del.delseq = ranges;\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete the topic alltogether. Requires Owner permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {boolean} hard - hard-delete topic.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delTopic(topicName, hard) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'topic';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete subscription. Requires Share permission.\n *\n * @param {string} topicName - Name of the topic to delete\n * @param {string} user - User ID to remove.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delSubscription(topicName, user) {\n const pkt = this.#initPacket('del', topicName);\n pkt.del.what = 'sub';\n pkt.del.user = user;\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Delete credential. Always sent on 'me' topic.\n *\n * @param {string} method - validation method such as 'email' or 'tel'.\n * @param {string} value - validation value, i.e. 'alice@example.com'.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCredential(method, value) {\n const pkt = this.#initPacket('del', Const.TOPIC_ME);\n pkt.del.what = 'cred';\n pkt.del.cred = {\n meth: method,\n val: value\n };\n\n return this.#send(pkt, pkt.del.id);\n }\n\n /**\n * Request to delete account of the current user.\n *\n * @param {boolean} hard - hard-delete user.\n * @returns {Promise} Promise which will be resolved/rejected on receiving server reply.\n */\n delCurrentUser(hard) {\n const pkt = this.#initPacket('del', null);\n pkt.del.what = 'user';\n pkt.del.hard = hard;\n\n return this.#send(pkt, pkt.del.id).then(_ => {\n this._myUID = null;\n });\n }\n\n /**\n * Notify server that a message or messages were read or received. Does NOT return promise.\n *\n * @param {string} topicName - Name of the topic where the mesage is being aknowledged.\n * @param {string} what - Action being aknowledged, either \"read\" or \"recv\".\n * @param {number} seq - Maximum id of the message being acknowledged.\n */\n note(topicName, what, seq) {\n if (seq <= 0 || seq >= Const.LOCAL_SEQID) {\n throw new Error(`Invalid message id ${seq}`);\n }\n\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = what;\n pkt.note.seq = seq;\n this.#send(pkt);\n }\n\n /**\n * Broadcast a key-press notification to topic subscribers. Used to show\n * typing notifications \"user X is typing...\".\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {string=} type - notification to send, default is 'kp'.\n */\n noteKeyPress(topicName, type) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.what = type || 'kp';\n this.#send(pkt);\n }\n\n /**\n * Send a video call notification to topic subscribers (including dialing,\n * hangup, etc.).\n *\n * @param {string} topicName - Name of the topic to broadcast to.\n * @param {int} seq - ID of the call message the event pertains to.\n * @param {string} evt - Call event.\n * @param {string} payload - Payload associated with this event (e.g. SDP string).\n *\n * @returns {Promise} Promise (for some call events) which will\n * be resolved/rejected on receiving server reply\n */\n videoCall(topicName, seq, evt, payload) {\n const pkt = this.#initPacket('note', topicName);\n pkt.note.seq = seq;\n pkt.note.what = 'call';\n pkt.note.event = evt;\n pkt.note.payload = payload;\n this.#send(pkt, pkt.note.id);\n }\n\n /**\n * Get a named topic, either pull it from cache or create a new instance.\n * There is a single instance of topic for each name.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested or newly created topic or undefined if topic name is invalid.\n */\n getTopic(topicName) {\n let topic = this.#cacheGet('topic', topicName);\n if (!topic && topicName) {\n if (topicName == Const.TOPIC_ME) {\n topic = new TopicMe();\n } else if (topicName == Const.TOPIC_FND) {\n topic = new TopicFnd();\n } else {\n topic = new Topic(topicName);\n }\n // Cache management.\n this.#attachCacheToTopic(topic);\n topic._cachePutSelf();\n // Don't save to DB here: a record will be added when the topic is subscribed.\n }\n return topic;\n }\n\n /**\n * Get a named topic from cache.\n *\n * @param {string} topicName - Name of the topic to get.\n *\n * @returns {Topic} Requested topic or undefined if topic is not found in cache.\n */\n cacheGetTopic(topicName) {\n return this.#cacheGet('topic', topicName);\n }\n\n /**\n * Remove named topic from cache.\n *\n * @param {string} topicName - Name of the topic to remove from cache.\n */\n cacheRemTopic(topicName) {\n this.#cacheDel('topic', topicName);\n }\n\n /**\n * Iterate over cached topics.\n *\n * @param {Function} func - callback to call for each topic.\n * @param {Object} context - 'this' inside the 'func'.\n */\n mapTopics(func, context) {\n this.#cacheMap('topic', func, context);\n }\n\n /**\n * Check if named topic is already present in cache.\n *\n * @param {string} topicName - Name of the topic to check.\n * @returns {boolean} true if topic is found in cache, false otherwise.\n */\n isTopicCached(topicName) {\n return !!this.#cacheGet('topic', topicName);\n }\n\n /**\n * Generate unique name like 'new123456' suitable for creating a new group topic.\n *\n * @param {boolean} isChan - if the topic is channel-enabled.\n * @returns {string} name which can be used for creating a new group topic.\n */\n newGroupTopicName(isChan) {\n return (isChan ? Const.TOPIC_NEW_CHAN : Const.TOPIC_NEW) + this.getNextUniqueId();\n }\n\n /**\n * Instantiate 'me' topic or get it from cache.\n *\n * @returns {TopicMe} Instance of 'me' topic.\n */\n getMeTopic() {\n return this.getTopic(Const.TOPIC_ME);\n }\n\n /**\n * Instantiate 'fnd' (find) topic or get it from cache.\n *\n * @returns {Topic} Instance of 'fnd' topic.\n */\n getFndTopic() {\n return this.getTopic(Const.TOPIC_FND);\n }\n\n /**\n * Create a new {@link LargeFileHelper} instance\n *\n * @returns {LargeFileHelper} instance of a {@link Tinode.LargeFileHelper}.\n */\n getLargeFileHelper() {\n return new LargeFileHelper(this, Const.PROTOCOL_VERSION);\n }\n\n /**\n * Get the UID of the the current authenticated user.\n *\n * @returns {string} UID of the current user or undefined if the session is not yet\n * authenticated or if there is no session.\n */\n getCurrentUserID() {\n return this._myUID;\n }\n\n /**\n * Check if the given user ID is equal to the current user's UID.\n *\n * @param {string} uid - UID to check.\n *\n * @returns {boolean} true if the given UID belongs to the current logged in user.\n */\n isMe(uid) {\n return this._myUID === uid;\n }\n\n /**\n * Get login used for last successful authentication.\n *\n * @returns {string} login last used successfully or undefined.\n */\n getCurrentLogin() {\n return this._login;\n }\n\n /**\n * Return information about the server: protocol version and build timestamp.\n *\n * @returns {Object} build and version of the server or null if there is no connection or\n * if the first server response has not been received yet.\n */\n getServerInfo() {\n return this._serverInfo;\n }\n\n /**\n * Report a topic for abuse. Wrapper for {@link Tinode#publish}.\n *\n * @param {string} action - the only supported action is 'report'.\n * @param {string} target - name of the topic being reported.\n *\n * @returns {Promise} Promise to be resolved/rejected when the server responds to request.\n */\n report(action, target) {\n return this.publish(Const.TOPIC_SYS, Drafty.attachJSON(null, {\n 'action': action,\n 'target': target\n }));\n }\n\n /**\n * Return server-provided configuration value.\n *\n * @param {string} name of the value to return.\n * @param {Object} defaultValue to return in case the parameter is not set or not found.\n *\n * @returns {Object} named value.\n */\n getServerParam(name, defaultValue) {\n return this._serverInfo && this._serverInfo[name] || defaultValue;\n }\n\n /**\n * Toggle console logging. Logging is off by default.\n *\n * @param {boolean} enabled - Set to true to enable logging to console.\n * @param {boolean} trimLongStrings - Set to true to trim long strings.\n */\n enableLogging(enabled, trimLongStrings) {\n this._loggingEnabled = enabled;\n this._trimLongStrings = enabled && trimLongStrings;\n }\n\n /**\n * Set UI language to report to the server. Must be called before 'hi' is sent, otherwise it will not be used.\n *\n * @param {string} hl - human (UI) language, like \"en_US\" or \"zh-Hans\".\n */\n setHumanLanguage(hl) {\n if (hl) {\n this._humanLanguage = hl;\n }\n }\n\n /**\n * Check if given topic is online.\n *\n * @param {string} name of the topic to test.\n * @returns {boolean} true if topic is online, false otherwise.\n */\n isTopicOnline(name) {\n const topic = this.#cacheGet('topic', name);\n return topic && topic.online;\n }\n\n /**\n * Get access mode for the given contact.\n *\n * @param {string} name of the topic to query.\n * @returns {AccessMode} access mode if topic is found, null otherwise.\n */\n getTopicAccessMode(name) {\n const topic = this.#cacheGet('topic', name);\n return topic ? topic.acs : null;\n }\n\n /**\n * Include message ID into all subsequest messages to server instructin it to send aknowledgemens.\n * Required for promises to function. Default is \"on\".\n *\n * @param {boolean} status - Turn aknowledgemens on or off.\n * @deprecated\n */\n wantAkn(status) {\n if (status) {\n this._messageId = Math.floor((Math.random() * 0xFFFFFF) + 0xFFFFFF);\n } else {\n this._messageId = 0;\n }\n }\n\n // Callbacks:\n /**\n * Callback to report when the websocket is opened. The callback has no parameters.\n *\n * @type {onWebsocketOpen}\n */\n onWebsocketOpen = undefined;\n\n /**\n * @typedef ServerParams\n *\n * @type {Object}\n * @property {string} ver - Server version\n * @property {string} build - Server build\n * @property {string=} sid - Session ID, long polling connections only.\n */\n\n /**\n * @callback onConnect\n * @param {number} code - Result code\n * @param {string} text - Text epxplaining the completion, i.e \"OK\" or an error message.\n * @param {ServerParams} params - Parameters returned by the server.\n */\n /**\n * Callback to report when connection with Tinode server is established.\n * @type {onConnect}\n */\n onConnect = undefined;\n\n /**\n * Callback to report when connection is lost. The callback has no parameters.\n * @type {onDisconnect}\n */\n onDisconnect = undefined;\n\n /**\n * @callback onLogin\n * @param {number} code - NUmeric completion code, same as HTTP status codes.\n * @param {string} text - Explanation of the completion code.\n */\n /**\n * Callback to report login completion.\n * @type {onLogin}\n */\n onLogin = undefined;\n\n /**\n * Callback to receive {ctrl} (control) messages.\n * @type {onCtrlMessage}\n */\n onCtrlMessage = undefined;\n\n /**\n * Callback to recieve {data} (content) messages.\n * @type {onDataMessage}\n */\n onDataMessage = undefined;\n\n /**\n * Callback to receive {pres} (presence) messages.\n * @type {onPresMessage}\n */\n onPresMessage = undefined;\n\n /**\n * Callback to receive all messages as objects.\n * @type {onMessage}\n */\n onMessage = undefined;\n\n /**\n * Callback to receive all messages as unparsed text.\n * @type {onRawMessage}\n */\n onRawMessage = undefined;\n\n /**\n * Callback to receive server responses to network probes. See {@link Tinode#networkProbe}\n * @type {onNetworkProbe}\n */\n onNetworkProbe = undefined;\n\n /**\n * Callback to be notified when exponential backoff is iterating.\n * @type {onAutoreconnectIteration}\n */\n onAutoreconnectIteration = undefined;\n};\n\n// Exported constants\nTinode.MESSAGE_STATUS_NONE = Const.MESSAGE_STATUS_NONE;\nTinode.MESSAGE_STATUS_QUEUED = Const.MESSAGE_STATUS_QUEUED;\nTinode.MESSAGE_STATUS_SENDING = Const.MESSAGE_STATUS_SENDING;\nTinode.MESSAGE_STATUS_FAILED = Const.MESSAGE_STATUS_FAILED;\nTinode.MESSAGE_STATUS_FATAL = Const.MESSAGE_STATUS_FATAL;\nTinode.MESSAGE_STATUS_SENT = Const.MESSAGE_STATUS_SENT;\nTinode.MESSAGE_STATUS_RECEIVED = Const.MESSAGE_STATUS_RECEIVED;\nTinode.MESSAGE_STATUS_READ = Const.MESSAGE_STATUS_READ;\nTinode.MESSAGE_STATUS_TO_ME = Const.MESSAGE_STATUS_TO_ME;\n\n// Unicode [del] symbol.\nTinode.DEL_CHAR = Const.DEL_CHAR;\n\n// Names of keys to server-provided configuration limits.\nTinode.MAX_MESSAGE_SIZE = 'maxMessageSize';\nTinode.MAX_SUBSCRIBER_COUNT = 'maxSubscriberCount';\nTinode.MAX_TAG_COUNT = 'maxTagCount';\nTinode.MAX_FILE_UPLOAD_SIZE = 'maxFileUploadSize';\nTinode.REQ_CRED_VALIDATORS = 'reqCred';\n"],"names":["root","factory","exports","module","define","amd","this","MAX_PREVIEW_DATA_SIZE","JSON_MIME_TYPE","ALLOWED_ENT_FIELDS","INLINE_STYLES","name","start","end","FMT_WEIGHT","ENTITY_TYPES","dataName","pack","val","test","url","re","slice","FORMAT_TAGS","AU","html_tag","md_tag","undefined","isVoid","BN","BR","CO","DL","EM","EX","FM","HD","HL","HT","IM","LN","MN","RW","QQ","ST","VC","VD","base64toObjectUrl","b64","contentType","logger","bin","atob","length","buf","ArrayBuffer","arr","Uint8Array","i","charCodeAt","URL","createObjectURL","Blob","type","err","message","base64toDataUrl","DECORATORS","open","_","close","data","props","href","target","id","act","ref","mime","Drafty","src","duration","size","tmpPreviewUrl","_tempPreview","previewUrl","downloadUrl","width","height","title","alt","state","preview","premime","poster","preref","txt","fmt","ent","chunkify","line","spans","chunks","span","at","push","chunk","tp","chld","children","toSpanTree","tree","last","draftyToTree","doc","Array","isArray","text","len","key","attachments","forEach","includes","sort","a","b","diff","indexOf","spansToTree","treeTopDown","node","child","parent","addNode","n","substring","att","subspans","inner","tag","treeToDrafty","keymap","c","Object","keys","newKey","transformer","context","dst","call","treeBottomUp","formatter","index","stack","values","pop","shortenTree","limit","tail","lightEntity","allow","copyEntData","lTrim","trimStart","shift","attachmentsToEnd","concat","draftify","startAt","plain","ranges","drafty","light","entries","dc","init","plainText","parse","content","lines","split","entityMap","entityIndex","blx","entities","block","original","re_start","re_end","result","exec","start_offset","lastIndexOf","end_offset","spannify","match","extracted","entity","offset","unique","idx","filter","el","extractEntities","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","params","assign","quote","header","uid","body","appendLineBreak","mention","appendLink","linkData","appendImage","appendAudio","attachFile","attachmentDesc","wrapInto","style","wrapAsForm","insertButton","actionType","actionValue","refUrl","appendButton","attachJSON","UNSAFE_toHTML","join","format","shorten","forwardedContent","replyContent","startsWith","forwarding","toPlainText","isPlainText","toMarkdown","def","isValid","txt_type","hasAttachments","callback","count","hasEntities","styles","sanitizeEntities","getDownloadUrl","entData","isProcessing","getPreviewUrl","getEntitySize","getEntityMimeType","tagName","attrValue","getContentType","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getter","__esModule","d","definition","o","defineProperty","enumerable","get","g","globalThis","Function","e","window","obj","prop","prototype","hasOwnProperty","r","Symbol","toStringTag","value","AccessMode","constructor","acs","given","decode","want","mode","static","str","_BITMASK","_NONE","bitmask","_JOIN","_READ","_WRITE","_PRES","_APPROVE","_SHARE","_DELETE","_OWNER","m0","bit","charAt","toUpperCase","_INVALID","res","upd","action","val0","parts","a1","a2","toString","encode","jsonHelper","setMode","m","updateMode","u","update","getMode","setGiven","updateGiven","getGiven","setWant","w","updateWant","getWant","getMissing","getExcessive","updateAll","isOwner","side","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","flag","Error","VERSION","LIBRARY","TOPIC_NEW","TOPIC_NEW_CHAN","TOPIC_ME","TOPIC_FND","TOPIC_GRP","LOCAL_SEQID","EXPIRE_PROMISES_TIMEOUT","EXPIRE_PROMISES_PERIOD","DEL_CHAR","CommError","code","super","jsonParseHelper","date","Date","isNaN","isUrlRelative","isValidDate","getTime","mergeObj","ignore","mergeToCache","cache","newval","simplify","getOwnPropertyNames","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","initialized","wsProvider","xhrProvider","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","_lpURL","_poller","_sender","lp_poller","url_","resolve","poller","promiseCompleted","onreadystatechange","evt","readyState","status","pkt","JSON","responseText","ctrl","sid","send","onOpen","onMessage","onDisconnect","abort","sender","lp_sender","OPEN","conn","onerror","onopen","onclose","onmessage","DB_NAME","IDBProvider","DB","onError","initDatabase","req","onsuccess","event","db","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","put","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","Number","MAX_SAFE_INTEGER","mapTopics","deserializeTopic","updUser","pub","arguments","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","mapSubscriptions","getAll","addMessage","add","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","since","before","openCursor","cursor","continue","idbProvider","source","f","tags","_tags","setAccessMode","read","unread","max","getAccessMode","LargeFileHelper","tinode","_tinode","_version","_apiKey","_authToken","getAuthToken","xhr","uploadWithBaseUrl","baseUrl","avatarFor","onProgress","onSuccess","onFailure","base","endsWith","instance","setRequestHeader","token","toResolve","toReject","upload","onprogress","lengthComputable","loaded","total","onload","response","statusText","onabort","form","FormData","set","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","withTags","withCred","withDel","withLaterDel","_maxDel","extract","build","updated","isP2PType","CBuffer","compare_","unique_","getAt","buffer","getLast","insert","delAt","splice","delRange","reset","startIdx","beforeIdx","find","elem","nearest","isEmpty","exact","pivot","found","Topic","callbacks","created","touched","private","trusted","_users","_queuedSeqId","Const","_noEarlierMsgs","_recvNotificationTimer","_credentials","_messageVersions","_messages","_attached","_new","_delayedLeaveTimer","onData","onMeta","onPres","onInfo","onMetaDesc","onMetaSub","onSubsUpdated","onTagsUpdated","onCredsUpdated","onDeleteTopic","onAllMessagesReceived","topicType","isP2PTopicName","isGroupTopicName","isSubscribed","subscribe","getParams","setParams","_cacheDelSelf","_cachePutSelf","ts","me","getMeTopic","desc","_noForwarding","_processMetaDesc","createMessage","noEcho","publish","publishMessage","_sending","_failed","swapMessageId","_maybeUpdateMessageVersionsCache","_routeData","publishDraft","_getQueuedSeqId","getCurrentUserID","noecho","_db","_cancelled","_fatal","leave","unsub","_resetSub","_gone","leaveDelayed","delay","getMeta","getMessagesPage","forward","startMetaQuery","_loadMessages","promise","setMeta","out","t","trim","toLowerCase","item","pos","ary","normalizeArray","_processMetaSub","_processMetaTags","cred","_processMetaCreds","subscriber","am","invite","archive","arch","delMessages","hard","r1","r2","low","hi","tosend","reduce","del","flushMessageRange","flushMessage","delMessagesAll","hardDel","_all","delMessagesList","list","prev","delMessagesEdits","messageVersions","delTopic","delSubscription","note","_updateReadRecv","_refreshContact","noteRecv","noteRead","noteKeyPress","noteRecording","payload","oldVal","doUpdate","recv","userDesc","_cacheGetUser","p2pPeerDesc","subscribers","cb","origSeq","versions","messages","sinceId","beforeId","msgs","unused1","unused2","_isReplacementMsg","latest","latestMsgVersion","_origTs","_origSeq","findMessage","latestMessage","maxMsgSeq","maxClearId","messageCount","queuedMessages","msgReceiptCount","msgReadCount","msgRecvCount","msgHasMoreMessages","newer","isNewMessage","seqId","fromId","untilId","newSeqId","numMessages","cancelSend","msgStatus","getDefaultAccess","defacs","isArchived","isMeType","isMeTopicName","isChannelType","isChannelTopicName","isGroupType","isCommType","isCommTopicName","isMe","head","replace","targetSeq","parseInt","targetMsg","outgoing","webrtc","incoming","_routeMeta","meta","_processDelMessages","clear","delseq","_routePres","pres","online","isTopicCached","dacs","_routeInfo","info","subs","deleted","_updateCachedUser","creds","_allMessagesReceived","cached","_cachePutUser","_updateReceived","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","updateCount","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","method","contacts","getContact","getCredentials","TopicFnd","_contacts","indexBy","getPrototypeOf","IndexedDBProvider","b64EncodeUnicode","btoa","encodeURIComponent","p1","String","fromCharCode","jsonBuildHelper","pad","sp","repeat","millis","getUTCMilliseconds","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","rfc3339DateString","jsonLoggerHelper","WebSocket","XMLHttpRequest","indexedDB","chars","global","output","charCode","bc","bs","setNetworkProviders","setNetworkProvider","DBCache","initForNonBrowserApp","Tinode","onComplete","floor","_appName","appName","_platform","platform","navigator","_browser","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","getBrowserInfo","userAgent","_hwos","_humanLanguage","language","detectTransport","_connection","_persist","persist","all","_loggingEnabled","dateString","args","console","log","isNewGroupTopicName","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","searchParams","account","scheme","secret","login","acc","tmpscheme","tmpsecret","extra","createAccount","createAccountBasic","username","password","updateAccountBasic","hello","_serverInfo","onConnect","setDeviceToken","dt","sent","_deviceToken","loginBasic","uname","_login","loginToken","requestResetAuthSecret","expires","now","setAuthToken","dft","oobNotification","_trimLongStrings","stringify","xfrom","finally","modeGiven","modeWant","delCurrentUser","func","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_pendingPromises","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_cache","_cacheDelUser","onLogin","MESSAGE_STATUS_NONE","MESSAGE_STATUS_QUEUED","MESSAGE_STATUS_SENDING","MESSAGE_STATUS_FAILED","MESSAGE_STATUS_FATAL","MESSAGE_STATUS_SENT","MESSAGE_STATUS_RECEIVED","MESSAGE_STATUS_READ","MESSAGE_STATUS_TO_ME","MAX_MESSAGE_SIZE","MAX_SUBSCRIBER_COUNT","MAX_TAG_COUNT","MAX_FILE_UPLOAD_SIZE","REQ_CRED_VALIDATORS"],"sourceRoot":""}
\ No newline at end of file