From 01f5f9a44b1588231ff2471141bde2034ade57c0 Mon Sep 17 00:00:00 2001 From: or-else Date: Fri, 14 Apr 2023 19:15:25 -0700 Subject: [PATCH] Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header --- package.json | 2 +- src/large-file.js | 9 +++++++++ umd/tinode.dev.js | 8 +++++++- umd/tinode.dev.js.map | 2 +- umd/tinode.prod.js | 2 +- umd/tinode.prod.js.map | 2 +- version.js | 2 +- 7 files changed, 21 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 516e213..8a57db9 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tinode-sdk", "description": "Tinode SDK", - "version": "0.22.2", + "version": "0.22.3", "scripts": { "format": "js-beautify -r src/*.js", "build": "npm run format && npm run vers && npm run build:prod && npm run build:dev", diff --git a/src/large-file.js b/src/large-file.js index 0a07ac0..e592903 100644 --- a/src/large-file.js +++ b/src/large-file.js @@ -13,6 +13,12 @@ import { let XHRProvider; +function addURLParam(relUrl, key, value) { + const url = new URL(relUrl, window.location.origin); + url.searchParams.append(key, value); + return url.toString().substring(window.location.origin.length); +} + /** * @class LargeFileHelper - utilities for uploading and downloading files out of band. * Don't instantiate this class directly. Use {Tinode.getLargeFileHelper} instead. @@ -207,6 +213,9 @@ export default class LargeFileHelper { const xhr = new XHRProvider(); this.xhr.push(xhr); + // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header. + relativeUrl = addURLParam(relativeUrl, 'asatt', '1'); + // Get data as blob (stored by the browser as a temporary file). xhr.open('GET', relativeUrl, true); xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey); diff --git a/umd/tinode.dev.js b/umd/tinode.dev.js index 7a12b0b..1b784e8 100644 --- a/umd/tinode.dev.js +++ b/umd/tinode.dev.js @@ -3028,6 +3028,11 @@ __webpack_require__.r(__webpack_exports__); let XHRProvider; +function addURLParam(relUrl, key, value) { + const url = new URL(relUrl, window.location.origin); + url.searchParams.append(key, value); + return url.toString().substring(window.location.origin.length); +} class LargeFileHelper { constructor(tinode, version) { this._tinode = tinode; @@ -3158,6 +3163,7 @@ class LargeFileHelper { const instance = this; const xhr = new XHRProvider(); this.xhr.push(xhr); + relativeUrl = addURLParam(relativeUrl, 'asatt', '1'); xhr.open('GET', relativeUrl, true); xhr.setRequestHeader('X-Tinode-APIKey', this._apiKey); xhr.setRequestHeader('X-Tinode-Auth', 'Token ' + this._authToken.token); @@ -4944,7 +4950,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "PACKAGE_VERSION": () => (/* binding */ PACKAGE_VERSION) /* harmony export */ }); -const PACKAGE_VERSION = "0.22.2"; +const PACKAGE_VERSION = "0.22.3"; /***/ }) diff --git a/umd/tinode.dev.js.map b/umd/tinode.dev.js.map index 34f5eb2..fff8a68 100644 --- a/umd/tinode.dev.js.map +++ b/umd/tinode.dev.js.map @@ -1 +1 @@ -{"version":3,"file":"tinode.dev.js","mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;;;;;;;;;;;;;;ACLa;AAAA,SAAAA,6BAAAC,QAAA,EAAAC,gBAAA,EAAAC,MAAA,IAAAC,8BAAA,CAAAH,QAAA,EAAAC,gBAAA,UAAAC,MAAA;AAAA,SAAAC,+BAAAH,QAAA,EAAAC,gBAAA,QAAAD,QAAA,KAAAC,gBAAA,cAAAG,SAAA;AAcE,MAAMC,UAAU,CAAC;EAC9BC,WAAWA,CAACC,GAAG,EAAE;IACf,IAAIA,GAAG,EAAE;MACP,IAAI,CAACC,KAAK,GAAG,OAAOD,GAAG,CAACC,KAAK,IAAI,QAAQ,GAAGD,GAAG,CAACC,KAAK,GAAGH,UAAU,CAACI,MAAM,CAACF,GAAG,CAACC,KAAK,CAAC;MACpF,IAAI,CAACE,IAAI,GAAG,OAAOH,GAAG,CAACG,IAAI,IAAI,QAAQ,GAAGH,GAAG,CAACG,IAAI,GAAGL,UAAU,CAACI,MA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S,MAAM,CAACp0B,oBAAoB,GAAG2hB,4DAA0B;AACxDyS,MAAM,CAACn0B,mBAAmB,GAAG0hB,2DAAyB;AACtDyS,MAAM,CAACl0B,uBAAuB,GAAGyhB,+DAA6B;AAC9DyS,MAAM,CAACj0B,mBAAmB,GAAGwhB,2DAAyB;AACtDyS,MAAM,CAACh0B,oBAAoB,GAAGuhB,4DAA0B;AAGxDyS,MAAM,CAAC3zB,QAAQ,GAAGkhB,gDAAc;AAGhCyS,MAAM,CAAC2H,gBAAgB,GAAG,gBAAgB;AAC1C3H,MAAM,CAAC4H,oBAAoB,GAAG,oBAAoB;AAClD5H,MAAM,CAAC6H,aAAa,GAAG,aAAa;AACpC7H,MAAM,CAAC8H,oBAAoB,GAAG,mBAAmB;AACjD9H,MAAM,CAAC+H,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 * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {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 * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {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 * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {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 * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {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\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {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 *\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 *\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 * @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 * @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 * @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 * @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 * @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 * @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 *\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 minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\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 */\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 * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\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.22.2\";\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":["_classStaticPrivateMethodGet","receiver","classConstructor","method","_classCheckPrivateStaticAccess","TypeError","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","_checkFlag","call","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","flag","includes","Error","_classPrivateMethodInitSpec","obj","privateSet","_checkPrivateRedeclaration","add","_defineProperty","key","value","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","arg","_toPrimitive","String","input","hint","prim","Symbol","toPrimitive","undefined","Number","_classPrivateFieldInitSpec","privateMap","set","privateCollection","has","_classPrivateMethodGet","fn","_classPrivateFieldGet","descriptor","_classExtractFieldDescriptor","_classApplyDescriptorGet","get","_classPrivateFieldSet","_classApplyDescriptorSet","_comparator","WeakMap","_unique","_findNearest","WeakSet","_insertSorted","CBuffer","compare_","unique_","a","b","getAt","at","buffer","getLast","put","insert","arguments","Array","isArray","idx","_insertSorted2","delAt","r","splice","delRange","since","before","reset","forEach","callback","startIdx","beforeIdx","context","find","elem","nearest","_findNearest2","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","_classStaticPrivateFieldSpecSet","_classCheckPrivateStaticFieldDescriptor","_classStaticPrivateFieldSpecGet","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","_boffTimer","_boffIteration","_boffClosed","_socket","_boffReconnect","_boffStop","_boffReset","_init_lp","_init_ws","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","_init_lp2","initialized","_init_ws2","_log","setNetworkProviders","wsProvider","xhrProvider","logger","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","_boffReset2","_boffReconnect2","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","_","prom","catch","_boffStop2","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","_onError","_logger","_mapObjects","DB","onError","initDatabase","req","onsuccess","event","db","target","result","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","_serializeTopic","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","MAX_SAFE_INTEGER","mapTopics","_mapObjects2","deserializeTopic","src","_deserializeTopic","updUser","uid","pub","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","_serializeSubscription","mapSubscriptions","getAll","addMessage","_serializeMessage","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","limit","openCursor","cursor","push","continue","setDatabaseProvider","idbProvider","source","_topic_fields","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","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","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","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","window","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","setNetworkProvider","_get_desc_ims","_get_subs_ims","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","_get_desc_ims2","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","_get_subs_ims2","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","minMsgSeq","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","cached","_cachePutUser","_updateReceived","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","updateCount","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","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","output","charCode","bc","bs","fromCharCode","detectTransport","b64EncodeUnicode","encodeURIComponent","toSolidBytes","p1","jsonBuildHelper","jsonLoggerHelper","getBrowserInfo","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","_makePromise","_execPromise","_send","_dispatchMessage","_connectionOpen","_disconnected","_getUserAgent","_initPacket","_cachePut","_cacheGet","_cacheDel","_cacheMap","_attachCacheToTopic","_loginSuccessful","Tinode","onComplete","floor","_appName","appName","_platform","platform","navigator","_browser","userAgent","_hwos","_humanLanguage","language","_connection","_dispatchMessage2","_connectionOpen2","_disconnected2","_persist","persist","_cacheGet2","_attachCacheToTopic2","_cachePut2","all","_loggingEnabled","dateString","_len","args","_key","console","log","credential","getVersion","getLibrary","isNullValue","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","searchParams","account","scheme","secret","login","_initPacket2","acc","tmpscheme","tmpsecret","extra","_send2","createAccount","_loginSuccessful2","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","_cacheDel2","func","_cacheMap2","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_makePromise2","_pendingPromises","_execPromise2","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_getUserAgent2","_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,SAAAA,6BAAAC,QAAA,EAAAC,gBAAA,EAAAC,MAAA,IAAAC,8BAAA,CAAAH,QAAA,EAAAC,gBAAA,UAAAC,MAAA;AAAA,SAAAC,+BAAAH,QAAA,EAAAC,gBAAA,QAAAD,QAAA,KAAAC,gBAAA,cAAAG,SAAA;AAcE,MAAMC,UAAU,CAAC;EAC9BC,WAAWA,CAACC,GAAG,EAAE;IACf,IAAIA,GAAG,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AE;QACLA,CAAC,GAAGA,CAAC,CAACC,IAAI,EAAE,CAACC,WAAW,EAAE;QAC1B,IAAIF,CAAC,CAACp7B,MAAM,GAAG,CAAC,EAAE;UAChBgyB,GAAG,CAACjc,IAAI,CAACqlB,CAAC,CAAC;QACb;MACF;IACF;IACApJ,GAAG,CAACrV,IAAI,EAAE,CAAC5U,MAAM,CAAC,UAASwzB,IAAI,EAAEC,GAAG,EAAEC,GAAG,EAAE;MACzC,OAAO,CAACD,GAAG,IAAID,IAAI,IAAIE,GAAG,CAACD,GAAG,GAAG,CAAC,CAAC;IACrC,CAAC,CAAC;EACJ;EACA,IAAIxJ,GAAG,CAAChyB,MAAM,IAAI,CAAC,EAAE;IAGnBgyB,GAAG,CAACjc,IAAI,CAACxL,gDAAQ,CAAC;EACpB;EACA,OAAOynB,GAAG;AACZ;;;;;;;;;;;;;;AC3KO,MAAMppB,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,SAAAzF,4BAAAC,GAAA,EAA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IAAID,IAAI,CAACC,MAAM,CAACoX,KAAK,IAAIrX,IAAI,CAACC,MAAM,CAACuyB,OAAO,EAAE;IAC3D,IAAI,CAAChc,UAAU,GAAG;MAChBa,KAAK,EAAErX,IAAI,CAACC,MAAM,CAACoX,KAAK;MACxBmb,OAAO,EAAExyB,IAAI,CAACC,MAAM,CAACuyB;IACvB,CAAC;EACH,CAAC,MAAM;IACL,IAAI,CAAChc,UAAU,GAAG,IAAI;EACxB;EAEA,IAAI,IAAI,CAACmf,OAAO,EAAE;IAChB,IAAI,CAACA,OAAO,CAAC31B,IAAI,CAAC3H,IAAI,EAAE2H,IAAI,CAACO,IAAI,CAAC;EACpC;EAEA,OAAOP,IAAI;AACb;AA8xCD;AAGDkuB,MAAM,CAAC70B,mBAAmB,GAAGoiB,2DAAyB;AACtDyS,MAAM,CAAC50B,qBAAqB,GAAGmiB,6DAA2B;AAC1DyS,MAAM,CAAC30B,sBAAsB,GAAGkiB,8DAA4B;AAC5DyS,MAAM,CAAC10B,qBAAqB,GAAGiiB,6DAA2B;AAC1DyS,MAAM,CAACz0B,oBAAoB,GAAGgiB,4DAA0B;AACxDyS,MAAM,CAACx0B,mBAAmB,GAAG+hB,2DAAyB;AACtDyS,MAAM,CAACv0B,uBAAuB,GAAG8hB,+DAA6B;AAC9DyS,MAAM,CAACt0B,mBAAmB,GAAG6hB,2DAAyB;AACtDyS,MAAM,CAACr0B,oBAAoB,GAAG4hB,4DAA0B;AAGxDyS,MAAM,CAACh0B,QAAQ,GAAGuhB,gDAAc;AAGhCyS,MAAM,CAAC0H,gBAAgB,GAAG,gBAAgB;AAC1C1H,MAAM,CAAC2H,oBAAoB,GAAG,oBAAoB;AAClD3H,MAAM,CAAC4H,aAAa,GAAG,aAAa;AACpC5H,MAAM,CAAC6H,oBAAoB,GAAG,mBAAmB;AACjD7H,MAAM,CAAC8H,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 * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {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 * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {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 * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {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 * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {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\nfunction addURLParam(relUrl, key, value) {\n const url = new URL(relUrl, window.location.origin);\n url.searchParams.append(key, value);\n return url.toString().substring(window.location.origin.length);\n}\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 // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header.\n relativeUrl = addURLParam(relativeUrl, 'asatt', '1');\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\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {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 *\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 *\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 * @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 * @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 * @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 * @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 * @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 * @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 *\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 minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\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 */\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 * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\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.22.3\";\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":["_classStaticPrivateMethodGet","receiver","classConstructor","method","_classCheckPrivateStaticAccess","TypeError","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","_checkFlag","call","isPresencer","isMuted","isJoiner","isReader","isWriter","isApprover","isAdmin","isSharer","isDeleter","flag","includes","Error","_classPrivateMethodInitSpec","obj","privateSet","_checkPrivateRedeclaration","add","_defineProperty","key","value","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","arg","_toPrimitive","String","input","hint","prim","Symbol","toPrimitive","undefined","Number","_classPrivateFieldInitSpec","privateMap","set","privateCollection","has","_classPrivateMethodGet","fn","_classPrivateFieldGet","descriptor","_classExtractFieldDescriptor","_classApplyDescriptorGet","get","_classPrivateFieldSet","_classApplyDescriptorSet","_comparator","WeakMap","_unique","_findNearest","WeakSet","_insertSorted","CBuffer","compare_","unique_","a","b","getAt","at","buffer","getLast","put","insert","arguments","Array","isArray","idx","_insertSorted2","delAt","r","splice","delRange","since","before","reset","forEach","callback","startIdx","beforeIdx","context","find","elem","nearest","_findNearest2","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","_classStaticPrivateFieldSpecSet","_classCheckPrivateStaticFieldDescriptor","_classStaticPrivateFieldSpecGet","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","_boffTimer","_boffIteration","_boffClosed","_socket","_boffReconnect","_boffStop","_boffReset","_init_lp","_init_ws","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","_init_lp2","initialized","_init_ws2","_log","setNetworkProviders","wsProvider","xhrProvider","logger","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","_boffReset2","_boffReconnect2","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","_","prom","catch","_boffStop2","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","_onError","_logger","_mapObjects","DB","onError","initDatabase","req","onsuccess","event","db","target","result","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","_serializeTopic","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","MAX_SAFE_INTEGER","mapTopics","_mapObjects2","deserializeTopic","src","_deserializeTopic","updUser","uid","pub","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","_serializeSubscription","mapSubscriptions","getAll","addMessage","_serializeMessage","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","limit","openCursor","cursor","push","continue","setDatabaseProvider","idbProvider","source","_topic_fields","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","map","s","append","first","second","insertImage","imageDesc","ex","refurl","bits","filename","urlPromise","_processing","then","insertVideo","videoDesc","urls","insertAudio","audioDesc","videoCall","audioOnly","aonly","updateVideoCall","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","addURLParam","relUrl","window","location","origin","searchParams","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","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","setNetworkProvider","_get_desc_ims","_get_subs_ims","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","_get_desc_ims2","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","_get_subs_ims2","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","minMsgSeq","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","cached","_cachePutUser","_updateReceived","TopicMe","onContactUpdate","turnOff","_myUID","cont","seen","when","updateCount","cacheRemTopic","getTopic","cr","findIndex","meth","done","resp","cacheGetTopic","ua","dummy","delCredential","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","output","charCode","bc","bs","fromCharCode","detectTransport","b64EncodeUnicode","encodeURIComponent","toSolidBytes","p1","jsonBuildHelper","jsonLoggerHelper","getBrowserInfo","product","reactnative","priority","tmp","substr","tokens","m2","v","minor","_makePromise","_execPromise","_send","_dispatchMessage","_connectionOpen","_disconnected","_getUserAgent","_initPacket","_cachePut","_cacheGet","_cacheDel","_cacheMap","_attachCacheToTopic","_loginSuccessful","Tinode","onComplete","floor","_appName","appName","_platform","platform","navigator","_browser","userAgent","_hwos","_humanLanguage","language","_connection","_dispatchMessage2","_connectionOpen2","_disconnected2","_persist","persist","_cacheGet2","_attachCacheToTopic2","_cachePut2","all","_loggingEnabled","dateString","_len","args","_key","console","log","credential","getVersion","getLibrary","isNullValue","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","account","scheme","secret","login","_initPacket2","acc","tmpscheme","tmpsecret","extra","_send2","createAccount","_loginSuccessful2","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","_cacheDel2","func","_cacheMap2","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_makePromise2","_pendingPromises","_execPromise2","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_getUserAgent2","_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 9cc97d4..68496e2 100644 --- a/umd/tinode.prod.js +++ b/umd/tinode.prod.js @@ -1,2 +1,2 @@ -!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){if(!e)return null;s&&(t-=s.length);return 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}))}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,[])},d.preview=function(e,t,s){let i=g(e);i=S(i,3);if(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:()=>Re(),Tinode:()=>Dt});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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 N(e,t,s){return C(e,t),R(s,"get"),q(e,s)}function R(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 N(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),R(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(N(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);N(te,te,oe).call(te,"LP connecting to:",n),t=i(n,e,s),t.send(null)})).catch((e=>{N(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);N(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 "+t+" private static field before its declaration")}(s,"get"),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,i;le(s=this,i=Se),i.add(s),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"]},Ne=s(577),Re=s.n(Ne);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){Fe(e,t),t.add(e)}function Ge(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 Be(e,t,s){Fe(e,t),t.set(e,s)}function Fe(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Ke(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function He(e,t){return function(e,t){if(t.get)return t.get.call(e);return t.value}(e,Xe(e,t,"get"))}function Qe(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,Xe(e,t,"set"),s),s}function Xe(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}var $e=new WeakMap,Je=new WeakMap,Ze=new WeakSet,Ye=new WeakSet;class et{constructor(e,t){ze(this,Ye),ze(this,Ze),Be(this,$e,{writable:!0,value:void 0}),Be(this,Je,{writable:!0,value:!1}),Ge(this,"buffer",[]),Qe(this,$e,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)Ke(this,Ye,st).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 st(e,t){const s=Ke(this,Ze,tt).call(this,e,t,!1),i=s.exact&&He(this,Je)?1:0;return t.splice(s.idx,i,e),t}function it(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 nt{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 et(((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 nt.topicType(e)==h}static isGroupTopicName(e){return nt.topicType(e)==d}static isP2PTopicName(e){return"p2p"==nt.topicType(e)}static isCommTopicName(e){return nt.isP2PTopicName(e)||nt.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 Re().hasEntities(e.content)&&(t=[],Re().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;if(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}minMsgSeq(){return this._minSeq}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 nt.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 nt.isMeTopicName(this.name)}isChannelType(){return nt.isChannelTopicName(this.name)}isGroupType(){return nt.isGroupTopicName(this.name)}isP2PType(){return nt.isP2PTopicName(this.name)}isCommType(){return nt.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 et(((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),nt.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 at extends nt{constructor(e){super(l,e),it(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(at.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 ot(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 ct(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 ht(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let lt,dt,ut;function pt(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function gt(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 ft(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":gt(0,t)}"undefined"!=typeof WebSocket&&(lt=WebSocket),"undefined"!=typeof XMLHttpRequest&&(dt=XMLHttpRequest),"undefined"!=typeof indexedDB&&(ut=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:lt,XMLHttpRequest:dt,indexedDB:ut,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}});te.setNetworkProviders(lt,dt),qe.setNetworkProvider(dt),Te.setDatabaseProvider(ut)}();var 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,At=new WeakSet;class Dt{constructor(e,t){if(ot(this,At),ot(this,kt),ot(this,Et),ot(this,xt),ot(this,Pt),ot(this,Tt),ot(this,St),ot(this,Mt),ot(this,yt),ot(this,vt),ot(this,wt),ot(this,bt),ot(this,_t),ot(this,mt),ct(this,"_host",void 0),ct(this,"_secure",void 0),ct(this,"_appName",void 0),ct(this,"_apiKey",void 0),ct(this,"_browser",""),ct(this,"_platform",void 0),ct(this,"_hwos","undefined"),ct(this,"_humanLanguage","xx"),ct(this,"_loggingEnabled",!1),ct(this,"_trimLongStrings",!1),ct(this,"_myUID",null),ct(this,"_authenticated",!1),ct(this,"_login",null),ct(this,"_authToken",null),ct(this,"_inPacketCount",0),ct(this,"_messageId",Math.floor(65535*Math.random()+65535)),ct(this,"_serverInfo",null),ct(this,"_deviceToken",null),ct(this,"_pendingPromises",{}),ct(this,"_expirePromises",null),ct(this,"_connection",null),ct(this,"_persist",!1),ct(this,"_db",null),ct(this,"_cache",{}),ct(this,"onWebsocketOpen",void 0),ct(this,"onConnect",void 0),ct(this,"onDisconnect",void 0),ct(this,"onLogin",void 0),ct(this,"onCtrlMessage",void 0),ct(this,"onDataMessage",void 0),ct(this,"onPresMessage",void 0),ct(this,"onMessage",void 0),ct(this,"onRawMessage",void 0),ct(this,"onNetworkProbe",void 0),ct(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,Re().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=>{ht(this,wt,qt).call(this,e)},this._connection.onOpen=e=>ht(this,vt,Ut).call(this),this._connection.onDisconnect=(e,t)=>ht(this,yt,It).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=ht(this,Pt,Wt).call(this,"topic",t.name);s||(s=t.name==h?new rt:t.name==l?new at:new nt(t.name),this._db.deserializeTopic(s,t),ht(this,kt,Gt).call(this,s),s._cachePutSelf(),delete s._new,e.push(s._loadMessages(this._db)))})))).then((e=>this._db.mapUsers((e=>{ht(this,Tt,Lt).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)))})),ht(this,bt,Ct).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=>ht(this,At,Bt).call(this,e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",pt(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",pt(t+":"+s),!1,i)}hello(){const e=ht(this,St,jt).call(this,"hi");return ht(this,bt,Ct).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()&&(ht(this,bt,Ct).call(this,{hi:{dev:e||Dt.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=ht(this,St,jt).call(this,"login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,ht(this,bt,Ct).call(this,i,i.login.id).then((e=>ht(this,At,Bt).call(this,e)))}loginBasic(e,t,s){return this.login("basic",pt(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",pt(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=ht(this,St,jt).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;Dt.isNewGroupTopicName(e)?i.sub.set.desc=t:Dt.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 ht(this,bt,Ct).call(this,i,i.sub.id)}leave(e,t){const s=ht(this,St,jt).call(this,"leave",e);return s.leave.unsub=t,ht(this,bt,Ct).call(this,s,s.leave.id)}createMessage(e,t,s){const i=ht(this,St,jt).call(this,"pub",e);let n="string"==typeof t?Re().parse(t):t;return n&&!Re().isPlainText(n)&&(i.pub.head={mime:Re().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)))}),ht(this,bt,Ct).call(this,s,e.id)}oobNotification(e){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(e,ft):e)),e.what){case"msg":if(!e.seq||e.seq<1||!e.topic)break;if(!this.isConnected())break;const s=ht(this,Pt,Wt).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=ht(this,St,jt).call(this,"get",e);return s.get=v(s.get,t),ht(this,bt,Ct).call(this,s,s.get.id)}setMeta(e,t){const s=ht(this,St,jt).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")):ht(this,bt,Ct).call(this,s,s.set.id)}delMessages(e,t,s){const i=ht(this,St,jt).call(this,"del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,ht(this,bt,Ct).call(this,i,i.del.id)}delTopic(e,t){const s=ht(this,St,jt).call(this,"del",e);return s.del.what="topic",s.del.hard=t,ht(this,bt,Ct).call(this,s,s.del.id)}delSubscription(e,t){const s=ht(this,St,jt).call(this,"del",e);return s.del.what="sub",s.del.user=t,ht(this,bt,Ct).call(this,s,s.del.id)}delCredential(e,t){const s=ht(this,St,jt).call(this,"del",h);return s.del.what="cred",s.del.cred={meth:e,val:t},ht(this,bt,Ct).call(this,s,s.del.id)}delCurrentUser(e){const t=ht(this,St,jt).call(this,"del",null);return t.del.what="user",t.del.hard=e,ht(this,bt,Ct).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=ht(this,St,jt).call(this,"note",e);i.note.what=t,i.note.seq=s,ht(this,bt,Ct).call(this,i)}noteKeyPress(e,t){const s=ht(this,St,jt).call(this,"note",e);s.note.what=t||"kp",ht(this,bt,Ct).call(this,s)}videoCall(e,t,s,i){const n=ht(this,St,jt).call(this,"note",e);n.note.seq=t,n.note.what="call",n.note.event=s,n.note.payload=i,ht(this,bt,Ct).call(this,n,n.note.id)}getTopic(e){let t=ht(this,Pt,Wt).call(this,"topic",e);return!t&&e&&(t=e==h?new rt:e==l?new at:new nt(e),ht(this,kt,Gt).call(this,t),t._cachePutSelf()),t}cacheGetTopic(e){return ht(this,Pt,Wt).call(this,"topic",e)}cacheRemTopic(e){ht(this,xt,Vt).call(this,"topic",e)}mapTopics(e,t){ht(this,Et,zt).call(this,"topic",e,t)}isTopicCached(e){return!!ht(this,Pt,Wt).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",Re().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=ht(this,Pt,Wt).call(this,"topic",e);return t&&t.online}getTopicAccessMode(e){const t=ht(this,Pt,Wt).call(this,"topic",e);return t?t.acs:null}wantAkn(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0}}function Nt(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 Ct(e,t){let s;t&&(s=ht(this,mt,Nt).call(this,t)),e=M(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,ft):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;ht(this,_t,Rt).call(this,t,te.NETWORK_ERROR,null,e.message)}return s}function qt(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,ft):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&ht(this,_t,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=ht(this,Pt,Wt).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=ht(this,Pt,Wt).call(this,"topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=ht(this,Pt,Wt).call(this,"topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((e=>{if(t.meta){const e=ht(this,Pt,Wt).call(this,"topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&ht(this,_t,Rt).call(this,t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=ht(this,Pt,Wt).call(this,"topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=ht(this,Pt,Wt).call(this,"topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=ht(this,Pt,Wt).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 Ut(){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 Ot(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+a}function jt(e,t){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:r,ua:ht(this,Mt,Ot).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 Lt(e,t,s){this._cache[e+":"+t]=s}function Wt(e,t){return this._cache[e+":"+t]}function Vt(e,t){delete this._cache[e+":"+t]}function zt(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 Gt(e){e._tinode=this,e._cacheGetUser=e=>{const t=ht(this,Pt,Wt).call(this,"user",e);if(t)return{user:e,public:v({},t)}},e._cachePutUser=(e,t)=>{ht(this,Tt,Lt).call(this,"user",e,v({},t.public))},e._cacheDelUser=e=>{ht(this,xt,Vt).call(this,"user",e)},e._cachePutSelf=t=>{ht(this,Tt,Lt).call(this,"topic",e.name,e)},e._cacheDelSelf=t=>{ht(this,xt,Vt).call(this,"topic",e.name)}}function Bt(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}Dt.MESSAGE_STATUS_NONE=0,Dt.MESSAGE_STATUS_QUEUED=10,Dt.MESSAGE_STATUS_SENDING=20,Dt.MESSAGE_STATUS_FAILED=30,Dt.MESSAGE_STATUS_FATAL=40,Dt.MESSAGE_STATUS_SENT=50,Dt.MESSAGE_STATUS_RECEIVED=60,Dt.MESSAGE_STATUS_READ=70,Dt.MESSAGE_STATUS_TO_ME=80,Dt.DEL_CHAR=f,Dt.MAX_MESSAGE_SIZE="maxMessageSize",Dt.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",Dt.MAX_TAG_COUNT="maxTagCount",Dt.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",Dt.REQ_CRED_VALIDATORS="reqCred"})(),i})())); +!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){if(!e)return null;s&&(t-=s.length);return 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}))}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,[])},d.preview=function(e,t,s){let i=g(e);i=S(i,3);if(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:()=>Re(),Tinode:()=>Dt});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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 N(e,t,s){return C(e,t),R(s,"get"),q(e,s)}function R(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 N(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),R(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(N(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);N(te,te,oe).call(te,"LP connecting to:",n),t=i(n,e,s),t.send(null)})).catch((e=>{N(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);N(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 "+t+" private static field before its declaration")}(s,"get"),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,i;le(s=this,i=Se),i.add(s),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"]},Ne=s(577),Re=s.n(Ne);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),e=function(e,t,s){const i=new URL(e,window.location.origin);return i.searchParams.append(t,s),i.toString().substring(window.location.origin.length)}(e,"asatt","1"),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){Fe(e,t),t.add(e)}function Ge(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 Be(e,t,s){Fe(e,t),t.set(e,s)}function Fe(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Ke(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function He(e,t){return function(e,t){if(t.get)return t.get.call(e);return t.value}(e,Xe(e,t,"get"))}function Qe(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,Xe(e,t,"set"),s),s}function Xe(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}var $e=new WeakMap,Je=new WeakMap,Ze=new WeakSet,Ye=new WeakSet;class et{constructor(e,t){ze(this,Ye),ze(this,Ze),Be(this,$e,{writable:!0,value:void 0}),Be(this,Je,{writable:!0,value:!1}),Ge(this,"buffer",[]),Qe(this,$e,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)Ke(this,Ye,st).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 st(e,t){const s=Ke(this,Ze,tt).call(this,e,t,!1),i=s.exact&&He(this,Je)?1:0;return t.splice(s.idx,i,e),t}function it(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 nt{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 et(((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 nt.topicType(e)==h}static isGroupTopicName(e){return nt.topicType(e)==d}static isP2PTopicName(e){return"p2p"==nt.topicType(e)}static isCommTopicName(e){return nt.isP2PTopicName(e)||nt.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 Re().hasEntities(e.content)&&(t=[],Re().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;if(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}minMsgSeq(){return this._minSeq}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 nt.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 nt.isMeTopicName(this.name)}isChannelType(){return nt.isChannelTopicName(this.name)}isGroupType(){return nt.isGroupTopicName(this.name)}isP2PType(){return nt.isP2PTopicName(this.name)}isCommType(){return nt.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 et(((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),nt.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 at extends nt{constructor(e){super(l,e),it(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(at.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 ot(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 ct(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,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");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 ht(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let lt,dt,ut;function pt(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function gt(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 ft(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":gt(0,t)}"undefined"!=typeof WebSocket&&(lt=WebSocket),"undefined"!=typeof XMLHttpRequest&&(dt=XMLHttpRequest),"undefined"!=typeof indexedDB&&(ut=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:lt,XMLHttpRequest:dt,indexedDB:ut,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}});te.setNetworkProviders(lt,dt),qe.setNetworkProvider(dt),Te.setDatabaseProvider(ut)}();var 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,At=new WeakSet;class Dt{constructor(e,t){if(ot(this,At),ot(this,kt),ot(this,Et),ot(this,xt),ot(this,Pt),ot(this,Tt),ot(this,St),ot(this,Mt),ot(this,yt),ot(this,vt),ot(this,wt),ot(this,bt),ot(this,_t),ot(this,mt),ct(this,"_host",void 0),ct(this,"_secure",void 0),ct(this,"_appName",void 0),ct(this,"_apiKey",void 0),ct(this,"_browser",""),ct(this,"_platform",void 0),ct(this,"_hwos","undefined"),ct(this,"_humanLanguage","xx"),ct(this,"_loggingEnabled",!1),ct(this,"_trimLongStrings",!1),ct(this,"_myUID",null),ct(this,"_authenticated",!1),ct(this,"_login",null),ct(this,"_authToken",null),ct(this,"_inPacketCount",0),ct(this,"_messageId",Math.floor(65535*Math.random()+65535)),ct(this,"_serverInfo",null),ct(this,"_deviceToken",null),ct(this,"_pendingPromises",{}),ct(this,"_expirePromises",null),ct(this,"_connection",null),ct(this,"_persist",!1),ct(this,"_db",null),ct(this,"_cache",{}),ct(this,"onWebsocketOpen",void 0),ct(this,"onConnect",void 0),ct(this,"onDisconnect",void 0),ct(this,"onLogin",void 0),ct(this,"onCtrlMessage",void 0),ct(this,"onDataMessage",void 0),ct(this,"onPresMessage",void 0),ct(this,"onMessage",void 0),ct(this,"onRawMessage",void 0),ct(this,"onNetworkProbe",void 0),ct(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,Re().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=>{ht(this,wt,qt).call(this,e)},this._connection.onOpen=e=>ht(this,vt,Ut).call(this),this._connection.onDisconnect=(e,t)=>ht(this,yt,It).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=ht(this,Pt,Wt).call(this,"topic",t.name);s||(s=t.name==h?new rt:t.name==l?new at:new nt(t.name),this._db.deserializeTopic(s,t),ht(this,kt,Gt).call(this,s),s._cachePutSelf(),delete s._new,e.push(s._loadMessages(this._db)))})))).then((e=>this._db.mapUsers((e=>{ht(this,Tt,Lt).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)))})),ht(this,bt,Ct).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=>ht(this,At,Bt).call(this,e)))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",pt(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",pt(t+":"+s),!1,i)}hello(){const e=ht(this,St,jt).call(this,"hi");return ht(this,bt,Ct).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()&&(ht(this,bt,Ct).call(this,{hi:{dev:e||Dt.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=ht(this,St,jt).call(this,"login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,ht(this,bt,Ct).call(this,i,i.login.id).then((e=>ht(this,At,Bt).call(this,e)))}loginBasic(e,t,s){return this.login("basic",pt(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",pt(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=ht(this,St,jt).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;Dt.isNewGroupTopicName(e)?i.sub.set.desc=t:Dt.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 ht(this,bt,Ct).call(this,i,i.sub.id)}leave(e,t){const s=ht(this,St,jt).call(this,"leave",e);return s.leave.unsub=t,ht(this,bt,Ct).call(this,s,s.leave.id)}createMessage(e,t,s){const i=ht(this,St,jt).call(this,"pub",e);let n="string"==typeof t?Re().parse(t):t;return n&&!Re().isPlainText(n)&&(i.pub.head={mime:Re().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)))}),ht(this,bt,Ct).call(this,s,e.id)}oobNotification(e){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(e,ft):e)),e.what){case"msg":if(!e.seq||e.seq<1||!e.topic)break;if(!this.isConnected())break;const s=ht(this,Pt,Wt).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=ht(this,St,jt).call(this,"get",e);return s.get=v(s.get,t),ht(this,bt,Ct).call(this,s,s.get.id)}setMeta(e,t){const s=ht(this,St,jt).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")):ht(this,bt,Ct).call(this,s,s.set.id)}delMessages(e,t,s){const i=ht(this,St,jt).call(this,"del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,ht(this,bt,Ct).call(this,i,i.del.id)}delTopic(e,t){const s=ht(this,St,jt).call(this,"del",e);return s.del.what="topic",s.del.hard=t,ht(this,bt,Ct).call(this,s,s.del.id)}delSubscription(e,t){const s=ht(this,St,jt).call(this,"del",e);return s.del.what="sub",s.del.user=t,ht(this,bt,Ct).call(this,s,s.del.id)}delCredential(e,t){const s=ht(this,St,jt).call(this,"del",h);return s.del.what="cred",s.del.cred={meth:e,val:t},ht(this,bt,Ct).call(this,s,s.del.id)}delCurrentUser(e){const t=ht(this,St,jt).call(this,"del",null);return t.del.what="user",t.del.hard=e,ht(this,bt,Ct).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=ht(this,St,jt).call(this,"note",e);i.note.what=t,i.note.seq=s,ht(this,bt,Ct).call(this,i)}noteKeyPress(e,t){const s=ht(this,St,jt).call(this,"note",e);s.note.what=t||"kp",ht(this,bt,Ct).call(this,s)}videoCall(e,t,s,i){const n=ht(this,St,jt).call(this,"note",e);n.note.seq=t,n.note.what="call",n.note.event=s,n.note.payload=i,ht(this,bt,Ct).call(this,n,n.note.id)}getTopic(e){let t=ht(this,Pt,Wt).call(this,"topic",e);return!t&&e&&(t=e==h?new rt:e==l?new at:new nt(e),ht(this,kt,Gt).call(this,t),t._cachePutSelf()),t}cacheGetTopic(e){return ht(this,Pt,Wt).call(this,"topic",e)}cacheRemTopic(e){ht(this,xt,Vt).call(this,"topic",e)}mapTopics(e,t){ht(this,Et,zt).call(this,"topic",e,t)}isTopicCached(e){return!!ht(this,Pt,Wt).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",Re().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=ht(this,Pt,Wt).call(this,"topic",e);return t&&t.online}getTopicAccessMode(e){const t=ht(this,Pt,Wt).call(this,"topic",e);return t?t.acs:null}wantAkn(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0}}function Nt(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 Ct(e,t){let s;t&&(s=ht(this,mt,Nt).call(this,t)),e=M(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,ft):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;ht(this,_t,Rt).call(this,t,te.NETWORK_ERROR,null,e.message)}return s}function qt(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,ft):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&ht(this,_t,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=ht(this,Pt,Wt).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=ht(this,Pt,Wt).call(this,"topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=ht(this,Pt,Wt).call(this,"topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((e=>{if(t.meta){const e=ht(this,Pt,Wt).call(this,"topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&ht(this,_t,Rt).call(this,t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=ht(this,Pt,Wt).call(this,"topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=ht(this,Pt,Wt).call(this,"topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=ht(this,Pt,Wt).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 Ut(){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 Ot(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+a}function jt(e,t){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:r,ua:ht(this,Mt,Ot).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 Lt(e,t,s){this._cache[e+":"+t]=s}function Wt(e,t){return this._cache[e+":"+t]}function Vt(e,t){delete this._cache[e+":"+t]}function zt(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 Gt(e){e._tinode=this,e._cacheGetUser=e=>{const t=ht(this,Pt,Wt).call(this,"user",e);if(t)return{user:e,public:v({},t)}},e._cachePutUser=(e,t)=>{ht(this,Tt,Lt).call(this,"user",e,v({},t.public))},e._cacheDelUser=e=>{ht(this,xt,Vt).call(this,"user",e)},e._cachePutSelf=t=>{ht(this,Tt,Lt).call(this,"topic",e.name,e)},e._cacheDelSelf=t=>{ht(this,xt,Vt).call(this,"topic",e.name)}}function Bt(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}Dt.MESSAGE_STATUS_NONE=0,Dt.MESSAGE_STATUS_QUEUED=10,Dt.MESSAGE_STATUS_SENDING=20,Dt.MESSAGE_STATUS_FAILED=30,Dt.MESSAGE_STATUS_FATAL=40,Dt.MESSAGE_STATUS_SENT=50,Dt.MESSAGE_STATUS_RECEIVED=60,Dt.MESSAGE_STATUS_READ=70,Dt.MESSAGE_STATUS_TO_ME=80,Dt.DEL_CHAR=f,Dt.MAX_MESSAGE_SIZE="maxMessageSize",Dt.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",Dt.MAX_TAG_COUNT="maxTagCount",Dt.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",Dt.REQ_CRED_VALIDATORS="reqCred"})(),i})())); //# sourceMappingURL=tinode.prod.js.map \ No newline at end of file diff --git a/umd/tinode.prod.js.map b/umd/tinode.prod.js.map index b13cf42..dab1264 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,CACLE,IAAKF,EAET,EACAG,GAAI,wFAGN,CACEV,KAAM,KACNK,SAAU,MACVC,KAAM,SAASC,GACb,MAAO,CACLA,IAAKA,EAAII,MAAM,GAEnB,EACAD,GAAI,kDAGN,CACEV,KAAM,KACNK,SAAU,MACVC,KAAM,SAASC,GACb,MAAO,CACLA,IAAKA,EAAII,MAAM,GAEnB,EACAD,GAAI,mDAKFE,EAAc,CAClBC,GAAI,CACFC,SAAU,QACVC,YAAQC,EACRC,QAAQ,GAEVC,GAAI,CACFJ,SAAU,SACVC,YA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iB,EAAK9R,OAAO00B,SAGvBviC,KAAKimB,WAAa,KAGhBjmB,KAAK0lC,SACP1lC,KAAK0lC,QAAQ/lB,EAAK7H,KAAM6H,EAAK5Y,MAGxB4Y,GAnBEA,CAoBX,CAiyCF6d,GAAOmI,oBTzpE4B,ES0pEnCnI,GAAOoI,sBTzpE8B,GS0pErCpI,GAAOqI,uBTzpE+B,GS0pEtCrI,GAAOsI,sBTzpE8B,GS0pErCtI,GAAOuI,qBTzpE6B,GS0pEpCvI,GAAOwI,oBTzpE4B,GS0pEnCxI,GAAOyI,wBTzpEgC,GS0pEvCzI,GAAO0I,oBTzpE4B,GS0pEnC1I,GAAO2I,qBTzpE6B,GS4pEpC3I,GAAO5lB,SAAWqV,EAGlBuQ,GAAO4I,iBAAmB,iBAC1B5I,GAAO6I,qBAAuB,qBAC9B7I,GAAO8I,cAAgB,cACvB9I,GAAO+I,qBAAuB,oBAC9B/I,GAAOgJ,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 * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {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 * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {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 * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {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 * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {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.22.2\";\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\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {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 *\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 *\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 * @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 * @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 * @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 * @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 * @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 * @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 *\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 minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\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 */\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 * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\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","_classStaticPrivateMethodGet","receiver","classConstructor","method","TypeError","_classCheckPrivateStaticAccess","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","_checkFlag","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","_classPrivateMethodInitSpec","privateSet","_checkPrivateRedeclaration","add","_defineProperty","arg","input","hint","prim","toPrimitive","String","Number","_toPrimitive","_toPropertyKey","configurable","writable","_classPrivateFieldInitSpec","privateMap","set","privateCollection","has","_classPrivateFieldSet","_classApplyDescriptorSet","_classExtractFieldDescriptor","_classPrivateFieldGet","_classApplyDescriptorGet","descriptor","_classStaticPrivateFieldSpecGet","_classCheckPrivateStaticFieldDescriptor","_classPrivateMethodGet","fn","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","_boffTimer","WeakMap","_boffIteration","_boffClosed","_socket","_boffReconnect","WeakSet","_boffStop","_boffReset","_init_lp","_init_ws","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","_init_lp2","initialized","_init_ws2","_log","wsProvider","xhrProvider","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","_boffReset2","_boffReconnect2","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","_boffStop2","_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","_onError","_logger","_mapObjects","DB","onError","initDatabase","req","onsuccess","event","db","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","put","_serializeTopic","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","MAX_SAFE_INTEGER","mapTopics","_mapObjects2","deserializeTopic","_deserializeTopic","updUser","pub","arguments","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","_serializeSubscription","mapSubscriptions","getAll","addMessage","_serializeMessage","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","since","before","openCursor","cursor","continue","idbProvider","source","_topic_fields","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","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","_get_desc_ims","_get_subs_ims","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","_get_desc_ims2","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","_get_subs_ims2","withTags","withCred","withDel","withLaterDel","_maxDel","extract","build","updated","isP2PType","_comparator","_unique","_findNearest","_insertSorted","CBuffer","compare_","unique_","getAt","buffer","getLast","insert","_insertSorted2","delAt","splice","delRange","reset","startIdx","beforeIdx","find","elem","nearest","_findNearest2","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","minMsgSeq","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","contacts","getContact","getCredentials","TopicFnd","_contacts","indexBy","getPrototypeOf","IndexedDBProvider","b64EncodeUnicode","btoa","encodeURIComponent","p1","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","_makePromise","_execPromise","_send","_dispatchMessage","_connectionOpen","_disconnected","_getUserAgent","_initPacket","_cachePut","_cacheGet","_cacheDel","_cacheMap","_attachCacheToTopic","_loginSuccessful","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","_dispatchMessage2","_connectionOpen2","_disconnected2","_persist","persist","_cacheGet2","_attachCacheToTopic2","_cachePut2","all","_loggingEnabled","dateString","_len","args","_key","console","log","isNewGroupTopicName","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","searchParams","account","scheme","secret","login","_initPacket2","acc","tmpscheme","tmpsecret","extra","_send2","createAccount","_loginSuccessful2","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","_cacheDel2","func","_cacheMap2","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_makePromise2","_pendingPromises","_execPromise2","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_getUserAgent2","_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,E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AO2I,iBAAmB,iBAC1B3I,GAAO4I,qBAAuB,qBAC9B5I,GAAO6I,cAAgB,cACvB7I,GAAO8I,qBAAuB,oBAC9B9I,GAAO+I,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 * Description of an image to attach.\n * @typedef {Object} ImageDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the image, e.g. \"image/png\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded image content. Could be null/undefined.\n * @property {string} preview - base64-encoded thumbnail of the image.\n * @property {integer} width - width of the image.\n * @property {integer} height - height of the image.\n * @property {string} filename - file name suggestion for downloading the image.\n * @property {integer} size - size of the image in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded image preview used during upload process; not serializable.\n * @property {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 * Description of a video to attach.\n * @typedef {Object} VideoDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the video, e.g. \"video/mpeg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - in-band base64-encoded image data. Could be null/undefined.\n * @property {string} preview - base64-encoded screencapture from the video. Could be null/undefined.\n * @property {string} preref - reference to screencapture from the video. Could be null/undefined.\n * @property {integer} width - width of the video.\n * @property {integer} height - height of the video.\n * @property {integer} duration - duration of the video.\n * @property {string} filename - file name suggestion for downloading the video.\n * @property {integer} size - size of the video in bytes. Treat is as an untrusted hint.\n * @property {string} _tempPreview - base64-encoded screencapture used during upload process; not serializable.\n * @property {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 * Description of an audio recording to attach.\n * @typedef {Object} AudioDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the audio, e.g. \"audio/ogg\".\n * @property {string} refurl - reference to the content. Could be null/undefined.\n * @property {string} bits - base64-encoded audio content. Could be null/undefined.\n * @property {integer} duration - duration of the record in milliseconds.\n * @property {string} preview - base64 encoded short array of amplitude values 0..100.\n * @property {string} filename - file name suggestion for downloading the audio.\n * @property {integer} size - size of the recording in bytes. Treat is as an untrusted hint.\n * @property {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 * Description of a file to attach.\n * @typedef {Object} AttachmentDesc\n * @memberof Drafty\n *\n * @property {string} mime - mime-type of the attachment, e.g. \"application/octet-stream\"\n * @property {string} data - base64-encoded in-band content of small attachments. Could be null/undefined.\n * @property {string} filename - file name suggestion for downloading the attachment.\n * @property {integer} size - size of the file in bytes. Treat is as an untrusted hint.\n * @property {string} refurl - reference to the out-of-band content. Could be null/undefined.\n * @property {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.22.3\";\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\nfunction addURLParam(relUrl, key, value) {\n const url = new URL(relUrl, window.location.origin);\n url.searchParams.append(key, value);\n return url.toString().substring(window.location.origin.length);\n}\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 // Add '&asatt=1' to URL to request 'Content-Disposition: attachment' response header.\n relativeUrl = addURLParam(relativeUrl, 'asatt', '1');\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\n/**\n * Topic is a class representing a logical communication channel.\n */\nexport class Topic {\n /**\n * @callback onData\n * @param {Data} data - Data packet\n */\n\n /**\n * Create topic.\n * @param {string} name - Name of the topic to create.\n * @param {Object=} callbacks - Object with various event callbacks.\n * @param {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 *\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 *\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 * @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 * @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 * @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 * @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 * @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 * @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 *\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 minimum cached seq ID.\n * @memberof Tinode.Topic#\n *\n * @returns {number} the smallest seq ID in cache or 0.\n */\n minMsgSeq() {\n return this._minSeq;\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 */\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 * Special case of {@link Tinode.Topic} for searching for contacts and group topics\n * @extends Tinode.Topic\n *\n */\nexport class TopicFnd extends Topic {\n // List of users and topics uid or topic_name -> Contact object)\n _contacts = {};\n\n /**\n * Create TopicFnd.\n *\n * @param {TopicFnd.Callbacks} callbacks - Callbacks to receive various events.\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","_classStaticPrivateMethodGet","receiver","classConstructor","method","TypeError","_classCheckPrivateStaticAccess","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","_checkFlag","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","_classPrivateMethodInitSpec","privateSet","_checkPrivateRedeclaration","add","_defineProperty","arg","input","hint","prim","toPrimitive","String","Number","_toPrimitive","_toPropertyKey","configurable","writable","_classPrivateFieldInitSpec","privateMap","set","privateCollection","has","_classPrivateFieldSet","_classApplyDescriptorSet","_classExtractFieldDescriptor","_classPrivateFieldGet","_classApplyDescriptorGet","descriptor","_classStaticPrivateFieldSpecGet","_classCheckPrivateStaticFieldDescriptor","_classPrivateMethodGet","fn","WebSocketProvider","XHRProvider","NETWORK_ERROR","NETWORK_ERROR_TEXT","NETWORK_USER","NETWORK_USER_TEXT","_BOFF_BASE","_BOFF_MAX_ITER","_BOFF_JITTER","makeBaseUrl","host","protocol","version","apiKey","_boffTimer","WeakMap","_boffIteration","_boffClosed","_socket","_boffReconnect","WeakSet","_boffStop","_boffReset","_init_lp","_init_ws","Connection","config","version_","autoreconnect_","secure","autoreconnect","transport","_init_lp2","initialized","_init_ws2","_log","wsProvider","xhrProvider","l","connect","host_","force","Promise","reject","reconnect","disconnect","sendText","msg","isConnected","probe","backoffReset","_boffReset2","_boffReconnect2","clearTimeout","timeout","Math","pow","random","onAutoreconnectIteration","setTimeout","prom","catch","_boffStop2","_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","_onError","_logger","_mapObjects","DB","onError","initDatabase","req","onsuccess","event","db","disabled","error","onupgradeneeded","createObjectStore","keyPath","deleteDatabase","onblocked","isReady","updTopic","topic","trx","transaction","oncomplete","objectStore","put","_serializeTopic","commit","markTopicAsDeleted","_deleted","remTopic","delete","IDBKeyRange","only","bound","MAX_SAFE_INTEGER","mapTopics","_mapObjects2","deserializeTopic","_deserializeTopic","updUser","pub","arguments","public","remUser","mapUsers","getUser","user","updSubscription","topicName","sub","_serializeSubscription","mapSubscriptions","getAll","addMessage","_serializeMessage","updMessageStatus","seq","_status","remMessages","from","to","range","readMessages","query","since","before","openCursor","cursor","continue","idbProvider","source","_topic_fields","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","getNextUniqueId","_secure","_host","download","relativeUrl","mimetype","relUrl","location","origin","searchParams","addURLParam","responseType","link","document","createElement","display","setAttribute","appendChild","click","removeChild","revokeObjectURL","reader","FileReader","readAsText","cancel","_get_desc_ims","_get_subs_ims","MetaGetBuilder","what","withData","withLaterData","_maxSeq","withEarlierData","_minSeq","withDesc","ims","withLaterDesc","_get_desc_ims2","withSub","userOrTopic","opts","getType","withOneSub","withLaterOneSub","_lastSubsUpdate","withLaterSub","_get_subs_ims2","withTags","withCred","withDel","withLaterDel","_maxDel","extract","build","updated","isP2PType","_comparator","_unique","_findNearest","_insertSorted","CBuffer","compare_","unique_","getAt","buffer","getLast","insert","_insertSorted2","delAt","splice","delRange","reset","startIdx","beforeIdx","find","elem","nearest","_findNearest2","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","minMsgSeq","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","contacts","getContact","getCredentials","TopicFnd","_contacts","indexBy","getPrototypeOf","IndexedDBProvider","b64EncodeUnicode","btoa","encodeURIComponent","p1","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","_makePromise","_execPromise","_send","_dispatchMessage","_connectionOpen","_disconnected","_getUserAgent","_initPacket","_cachePut","_cacheGet","_cacheDel","_cacheMap","_attachCacheToTopic","_loginSuccessful","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","_dispatchMessage2","_connectionOpen2","_disconnected2","_persist","persist","_cacheGet2","_attachCacheToTopic2","_cachePut2","all","_loggingEnabled","dateString","_len","args","_key","console","log","isNewGroupTopicName","_messageId","clearStorage","initStorage","networkProbe","isAuthenticated","_authenticated","authorizeURL","parsed","account","scheme","secret","login","_initPacket2","acc","tmpscheme","tmpsecret","extra","_send2","createAccount","_loginSuccessful2","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","_cacheDel2","func","_cacheMap2","newGroupTopicName","isChan","getFndTopic","getLargeFileHelper","getCurrentLogin","getServerInfo","report","getServerParam","defaultValue","enableLogging","enabled","trimLongStrings","setHumanLanguage","hl","isTopicOnline","getTopicAccessMode","wantAkn","_makePromise2","_pendingPromises","_execPromise2","onOK","errorText","_inPacketCount","onRawMessage","onNetworkProbe","onCtrlMessage","onMetaMessage","onDataMessage","onPresMessage","onInfoMessage","_expirePromises","setInterval","clearInterval","_getUserAgent2","_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 diff --git a/version.js b/version.js index 383ff2b..8e6372e 100644 --- a/version.js +++ b/version.js @@ -1 +1 @@ -export const PACKAGE_VERSION = "0.22.2"; +export const PACKAGE_VERSION = "0.22.3";