Files
im_webapp/umd/tinode.prod.js
T

1 line
81 KiB
JavaScript

!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Tinode=e()}((function(){var e={};function t(e,t,s){return function(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}(e,t),s}Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;class s{constructor(e){e&&(this.given="number"==typeof e.given?e.given:s.decode(e.given),this.want="number"==typeof e.want?e.want:s.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:s.decode(e.mode):this.given&this.want)}static decode(e){if(!e)return null;if("number"==typeof e)return e&s._BITMASK;if("N"===e||"n"===e)return s._NONE;const t={J:s._JOIN,R:s._READ,W:s._WRITE,P:s._PRES,A:s._APPROVE,S:s._SHARE,D:s._DELETE,O:s._OWNER};let n=s._NONE;for(let s=0;s<e.length;s++){const i=t[e.charAt(s).toUpperCase()];i&&(n|=i)}return n}static encode(e){if(null===e||e===s._INVALID)return null;if(e===s._NONE)return"N";const t=["J","R","W","P","A","S","D","O"];let n="";for(let s=0;s<t.length;s++)0!=(e&1<<s)&&(n+=t[s]);return n}static update(e,t){if(!t||"string"!=typeof t)return e;let n=t.charAt(0);if("+"==n||"-"==n){let i=e;const r=t.split(/([-+])/);for(let t=1;t<r.length-1;t+=2){n=r[t];const o=s.decode(r[t+1]);if(o==s._INVALID)return e;null!=o&&("+"===n?i|=o:"-"===n&&(i&=~o))}e=i}else{const n=s.decode(t);n!=s._INVALID&&(e=n)}return e}static diff(e,t){return e=s.decode(e),t=s.decode(t),e==s._INVALID||t==s._INVALID?s._INVALID:e&~t}toString(){return'{"mode": "'+s.encode(this.mode)+'", "given": "'+s.encode(this.given)+'", "want": "'+s.encode(this.want)+'"}'}jsonHelper(){return{mode:s.encode(this.mode),given:s.encode(this.given),want:s.encode(this.want)}}setMode(e){return this.mode=s.decode(e),this}updateMode(e){return this.mode=s.update(this.mode,e),this}getMode(){return s.encode(this.mode)}setGiven(e){return this.given=s.decode(e),this}updateGiven(e){return this.given=s.update(this.given,e),this}getGiven(){return s.encode(this.given)}setWant(e){return this.want=s.decode(e),this}updateWant(e){return this.want=s.update(this.want,e),this}getWant(){return s.encode(this.want)}getMissing(){return s.encode(this.want&~this.given)}getExcessive(){return s.encode(this.given&~this.want)}updateAll(e){return e&&(this.updateGiven(e.given),this.updateWant(e.want),this.mode=this.given&this.want),this}isOwner(e){return t(s,s,n).call(s,this,e,s._OWNER)}isPresencer(e){return t(s,s,n).call(s,this,e,s._PRES)}isMuted(e){return!this.isPresencer(e)}isJoiner(e){return t(s,s,n).call(s,this,e,s._JOIN)}isReader(e){return t(s,s,n).call(s,this,e,s._READ)}isWriter(e){return t(s,s,n).call(s,this,e,s._WRITE)}isApprover(e){return t(s,s,n).call(s,this,e,s._APPROVE)}isAdmin(e){return this.isOwner(e)||this.isApprover(e)}isSharer(e){return this.isAdmin(e)||t(s,s,n).call(s,this,e,s._SHARE)}isDeleter(e){return t(s,s,n).call(s,this,e,s._DELETE)}}function n(e,t,s){if(["given","want","mode"].includes(t=t||"mode"))return 0!=(e[t]&s);throw new Error("Invalid AccessMode component '".concat(t,"'"))}e.default=s,s._NONE=0,s._JOIN=1,s._READ=2,s._WRITE=4,s._PRES=8,s._APPROVE=16,s._SHARE=32,s._DELETE=64,s._OWNER=128,s._BITMASK=s._JOIN|s._READ|s._WRITE|s._PRES|s._APPROVE|s._SHARE|s._DELETE|s._OWNER,s._INVALID=1048576;var i={};Object.defineProperty(i,"__esModule",{value:!0}),i.VERSION=i.USER_NEW=i.TOPIC_SYS=i.TOPIC_P2P=i.TOPIC_NEW_CHAN=i.TOPIC_NEW=i.TOPIC_ME=i.TOPIC_GRP=i.TOPIC_FND=i.TOPIC_CHAN=i.PROTOCOL_VERSION=i.MESSAGE_STATUS_TO_ME=i.MESSAGE_STATUS_SENT=i.MESSAGE_STATUS_SENDING=i.MESSAGE_STATUS_RECEIVED=i.MESSAGE_STATUS_READ=i.MESSAGE_STATUS_QUEUED=i.MESSAGE_STATUS_NONE=i.MESSAGE_STATUS_FAILED=i.MESSAGE_STATUS_DEL_RANGE=i.LOCAL_SEQID=i.LIBRARY=i.EXPIRE_PROMISES_TIMEOUT=i.EXPIRE_PROMISES_PERIOD=i.DEL_CHAR=i.DEFAULT_MESSAGES_PAGE=void 0,i.PROTOCOL_VERSION="0",i.VERSION="0.18.2-beta1",i.LIBRARY="tinodejs/0.18.2-beta1",i.TOPIC_NEW="new",i.TOPIC_NEW_CHAN="nch",i.TOPIC_ME="me",i.TOPIC_FND="fnd",i.TOPIC_SYS="sys",i.TOPIC_CHAN="chn",i.TOPIC_GRP="grp;",i.TOPIC_P2P="p2p",i.USER_NEW="new",i.LOCAL_SEQID=268435455,i.MESSAGE_STATUS_NONE=0,i.MESSAGE_STATUS_QUEUED=1,i.MESSAGE_STATUS_SENDING=2,i.MESSAGE_STATUS_FAILED=3,i.MESSAGE_STATUS_SENT=4,i.MESSAGE_STATUS_RECEIVED=5,i.MESSAGE_STATUS_READ=6,i.MESSAGE_STATUS_TO_ME=7,i.MESSAGE_STATUS_DEL_RANGE=8,i.EXPIRE_PROMISES_TIMEOUT=5e3,i.EXPIRE_PROMISES_PERIOD=1e3,i.DEFAULT_MESSAGES_PAGE=24,i.DEL_CHAR="␡";var r={};Object.defineProperty(r,"__esModule",{value:!0}),r.jsonParseHelper=function(e,t){if("string"==typeof t&&t.length>=20&&t.length<=24&&["ts","touched","updated","created","when","deleted","expires"].includes(e)){const e=new Date(t);if(!isNaN(e))return e}else if("acs"===e&&"object"==typeof t)return new a.default(t);return t},r.mergeObj=h,r.mergeToCache=function(e,t,s,n){return e[t]=h(e[t],s,n),e[t]},r.normalizeArray=function(e){let t=[];if(Array.isArray(e)){for(let s=0,n=e.length;s<n;s++){let n=e[s];n&&(n=n.trim().toLowerCase()).length>1&&t.push(n)}t.sort().filter((function(e,t,s){return!t||e!=s[t-1]}))}return 0==t.length&&t.push(Tinode.DEL_CHAR),t},r.rfc3339DateString=function(e){if(!c(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"},r.simplify=function e(t){return Object.keys(t).forEach((s=>{"_"==s[0]?delete t[s]:t[s]?Array.isArray(t[s])&&0==t[s].length?delete t[s]:t[s]?t[s]instanceof Date?c(t[s])||delete t[s]:"object"==typeof t[s]&&(e(t[s]),0==Object.getOwnPropertyNames(t[s]).length&&delete t[s]):delete t[s]:delete t[s]})),t};var o,a=(o=e)&&o.__esModule?o:{default:o};function c(e){return e instanceof Date&&!isNaN(e)&&0!=e.getTime()}function h(e,t,s){if("object"!=typeof t){if(t===Tinode.DEL_CHAR)return;return void 0===t?e:t}if(null===t)return t;if(t instanceof Date&&!isNaN(t))return!e||!(e instanceof Date)||isNaN(e)||e<t?t:e;if(t instanceof a.default)return new a.default(t);if(t instanceof Array)return t;e&&e!==Tinode.DEL_CHAR||(e=t.constructor());for(let n in t)!t.hasOwnProperty(n)||s&&s[n]||"_noForwarding"==n||(e[n]=h(e[n],t[n]));return e}var u={};function l(e,t){f(e,t),t.add(e)}function d(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function p(e,t,s){f(e,t),t.set(e,s)}function f(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function g(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,m(e,t,"set"),s),s}function _(e,t){return function(e,t){return t.get?t.get.call(e):t.value}(e,m(e,t,"get"))}function m(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}function b(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}let S,E;function w(e,t,s,n){let i=null;return["http","https","ws","wss"].includes(t)&&("/"!==(i="".concat(t,"://").concat(e)).charAt(i.length-1)&&(i+="/"),i+="v"+s+"/channels",["http","https"].includes(t)&&(i+="/lp"),i+="?apikey="+n),i}Object.defineProperty(u,"__esModule",{value:!0}),u.default=void 0;var T=new WeakMap,v=new WeakMap,M=new WeakMap,P=new WeakSet,y=new WeakSet,A=new WeakSet,R=new WeakSet,D=new WeakSet,O=new WeakSet;class x{constructor(e,t,s){l(this,O),l(this,D),l(this,R),l(this,A),l(this,y),l(this,P),p(this,T,{writable:!0,value:null}),p(this,v,{writable:!0,value:0}),p(this,M,{writable:!0,value:!1}),d(this,"host",void 0),d(this,"secure",void 0),d(this,"apiKey",void 0),d(this,"version",void 0),d(this,"autoreconnect",void 0),d(this,"onMessage",void 0),d(this,"onDisconnect",void 0),d(this,"onOpen",void 0),d(this,"onAutoreconnectIteration",void 0),d(this,"logger",void 0),this.host=e.host,this.secure=e.secure,this.apiKey=e.apiKey,this.version=t,this.autoreconnect=s;let n=!1;if("lp"===e.transport?(b(this,O,j).call(this),n=!0):"ws"===e.transport&&(b(this,D,k).call(this),n=!0),!n)throw b(this,P,C).call(this,"Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.")}probe(){this.sendText("1")}backoffReset(){b(this,R,U).call(this)}static setNetworkProviders(e,t){S=e,E=t}}function C(e){if(x.logger){for(var t=arguments.length,s=new Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];x.logger(e,...s)}}function I(){clearTimeout(_(this,T));const e=Math.pow(2,_(this,v))*(1+.3*Math.random())*2e3;g(this,v,_(this,v)>=10?_(this,v):_(this,v)+1),this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),g(this,T,setTimeout((()=>{if(b(this,P,C).call(this,"Reconnecting, iter=".concat(_(this,v),", timeout=").concat(e)),_(this,M))this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch((()=>{}))}}),e))}function N(){clearTimeout(_(this,T)),g(this,T,null)}function U(){g(this,v,0)}function k(){let e=null;this.connect=(t,s)=>{if(g(this,M,!1),e){if(!s&&e.readyState==e.OPEN)return Promise.resolve();e.close(),e=null}return t&&(this.host=t),new Promise(((t,s)=>{const n=w(this.host,this.secure?"wss":"ws",this.version,this.apiKey);b(this,P,C).call(this,"Connecting to: ",n);const i=new S(n);i.onerror=e=>{s(e)},i.onopen=e=>{this.autoreconnect&&b(this,A,N).call(this),this.onOpen&&this.onOpen(),t()},i.onclose=t=>{if(e=null,this.onDisconnect){const e=_(this,M)?418:503;this.onDisconnect(new Error(_(this,M)?"Disconnected by client":"Connection failed ("+e+")"),e)}!_(this,M)&&this.autoreconnect&&b(this,y,I).call(instance)},i.onmessage=e=>{this.onMessage&&this.onMessage(e.data)},e=i}))},this.reconnect=e=>{b(this,A,N).call(this),this.connect(null,e)},this.disconnect=()=>{g(this,M,!0),b(this,A,N).call(this),e&&(e.close(),e=null)},this.sendText=t=>{if(!e||e.readyState!=e.OPEN)throw new Error("Websocket is not connected");e.send(t)},this.isConnected=()=>e&&e.readyState==e.OPEN,this.transport=()=>"ws"}function j(){let e=null,t=null,s=null;this.connect=(s,n)=>{if(g(this,M,!1),t){if(!n)return Promise.resolve();t.onreadystatechange=void 0,t.abort(),t=null}return s&&(this.host=s),new Promise(((s,n)=>{const i=w(this.host,this.secure?"https":"http",this.version,this.apiKey);b(this,P,C).call(this,"Connecting to:",i),(t=function t(s,n,i){let o=new E,a=!1;return o.onreadystatechange=c=>{if(4==o.readyState)if(201==o.status){let i=JSON.parse(o.responseText,r.jsonParseHelper);e=s+"&sid="+i.ctrl.params.sid,(o=t(e)).send(null),this.onOpen&&this.onOpen(),n&&(a=!0,n()),this.autoreconnect&&b(this,A,N).call(this)}else if(o.status<400)this.onMessage&&this.onMessage(o.responseText),(o=t(e)).send(null);else{if(i&&!a&&(a=!0,i(o.responseText)),this.onMessage&&o.responseText&&this.onMessage(o.responseText),this.onDisconnect){const e=o.status||(_(this,M)?418:503),t=o.responseText||(_(this,M)?"Disconnected by client":"Connection failed");this.onDisconnect(new Error(t+" ("+e+")"),e)}o=null,!_(this,M)&&this.autoreconnect&&b(this,y,I).call(this)}},o.open("GET",s,!0),o}(i,s,n)).send(null)})).catch((e=>{b(this,P,C).call(this,"LP connection failed:",e)}))},this.reconnect=e=>{b(this,A,N).call(this),this.connect(null,e)},this.disconnect=()=>{g(this,M,!0),b(this,A,N).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 Error("Disconnected by client (418)"),418),e=null},this.sendText=t=>{if(!(s=function(e){const t=new E;return t.onreadystatechange=e=>{if(4==t.readyState&&t.status>=400)throw new Error("LP sender failed, ".concat(t.status))},t.open("POST",e,!0),t}(e))||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(t)},this.isConnected=()=>t&&!0,this.transport=()=>"lp"}u.default=x,x.NETWORK_ERROR=503,x.NETWORK_ERROR_TEXT="Connection failed",x.NETWORK_USER=418,x.NETWORK_USER_TEXT="Disconnected by client";var L={};let q;Object.defineProperty(L,"__esModule",{value:!0}),L.default=void 0,L.default=class{constructor(e,t){e=e||function(){},t=t||function(){};let s=null,n=!1;const i=["created","updated","deleted","read","recv","seq","clear","defacs","creds","public","trusted","private","touched"];function r(e,t){const s=e||{name:t.name};return i.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 o(e,t){const s=e||{};return["topic","seq","ts","_status","from","head","content"].forEach((e=>{t.hasOwnProperty(e)&&(s[e]=t[e])})),s}function a(e,i,r){return s?new Promise(((n,o)=>{const a=s.transaction([e]);a.onerror=s=>{t("PCache","mapObjects",e,s.target.error),o(s.target.error)},a.objectStore(e).getAll().onsuccess=e=>{i&&e.target.result.forEach((e=>{i.call(r,e)})),n(e.target.result)}})):n?Promise.resolve([]):Promise.reject(new Error("not initialized"))}return{initDatabase:function(){return new Promise(((i,r)=>{const o=q.open("tinode-web",1);o.onsuccess=e=>{s=e.target.result,n=!1,i(s)},o.onerror=s=>{t("PCache","failed to initialize",s),r(s.target.error),e(s.target.error)},o.onupgradeneeded=function(n){(s=n.target.result).onerror=function(s){t("PCache","failed to create storage",s),e(s.target.error)},s.createObjectStore("topic",{keyPath:"name"}),s.createObjectStore("user",{keyPath:"uid"}),s.createObjectStore("subscription",{keyPath:["topic","uid"]}),s.createObjectStore("message",{keyPath:["topic","seq"]})}}))},deleteDatabase:function(){return new Promise(((e,i)=>{const r=q.deleteDatabase("tinode-web");r.onblocked=function(e){s&&s.close()},r.onsuccess=t=>{s=null,n=!0,e(!0)},r.onerror=e=>{t("PCache","deleteDatabase",e.target.error),i(e.target.error)}}))},isReady:function(){return!!s},updTopic:function(e){return this.isReady()?new Promise(((n,i)=>{const o=s.transaction(["topic"],"readwrite");o.oncomplete=e=>{n(e.target.result)},o.onerror=e=>{t("PCache","updTopic",e.target.error),i(e.target.error)};const a=o.objectStore("topic").get(e.name);a.onsuccess=t=>{o.objectStore("topic").put(r(a.result,e)),o.commit()}})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},markTopicAsDeleted:function(e,i){return this.isReady()?new Promise(((n,o)=>{const a=s.transaction(["topic"],"readwrite");a.oncomplete=e=>{n(e.target.result)},a.onerror=e=>{t("PCache","markTopicAsDeleted",e.target.error),o(e.target.error)};const c=a.objectStore("topic").get(e);c.onsuccess=e=>{const t=e.target.result;t._deleted!=i&&(t._deleted=!0,a.objectStore("topic").put(r(c.result,t))),a.commit()}})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},remTopic:function(e){return this.isReady()?new Promise(((n,i)=>{const r=s.transaction(["topic","subscription","message"],"readwrite");r.oncomplete=e=>{n(e.target.result)},r.onerror=e=>{t("PCache","remTopic",e.target.error),i(e.target.error)},r.objectStore("topic").delete(IDBKeyRange.only(e)),r.objectStore("subscription").delete(IDBKeyRange.bound([e,"-"],[e,"~"])),r.objectStore("message").delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),r.commit()})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},mapTopics:function(e,t){return a("topic",e,t)},deserializeTopic:function(e,t){!function(e,t){i.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)}(e,t)},updUser:function(e,i){if(!(arguments.length<2||void 0===i))return this.isReady()?new Promise(((n,r)=>{const o=s.transaction(["user"],"readwrite");o.oncomplete=e=>{n(e.target.result)},o.onerror=e=>{t("PCache","updUser",e.target.error),r(e.target.error)},o.objectStore("user").put({uid:e,public:i}),o.commit()})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},remUser:function(e){return this.isReady()?new Promise(((n,i)=>{const r=s.transaction(["user"],"readwrite");r.oncomplete=e=>{n(e.target.result)},r.onerror=e=>{t("PCache","remUser",e.target.error),i(e.target.error)},r.objectStore("user").delete(IDBKeyRange.only(e)),r.commit()})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},mapUsers:function(e,t){return a("user",e,t)},getUser:function(e){return this.isReady()?new Promise(((n,i)=>{const r=s.transaction(["user"]);r.oncomplete=e=>{const t=e.target.result;n({user:t.uid,public:t.public})},r.onerror=e=>{t("PCache","getUser",e.target.error),i(e.target.error)},r.objectStore("user").get(e)})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},updSubscription:function(e,i,r){return this.isReady()?new Promise(((n,o)=>{const a=s.transaction(["subscription"],"readwrite");a.oncomplete=e=>{n(e.target.result)},a.onerror=e=>{t("PCache","updSubscription",e.target.error),o(e.target.error)},a.objectStore("subscription").get([e,i]).onsuccess=t=>{a.objectStore("subscription").put(function(e,t,s,n){const i=e||{topic:t,uid:s};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach((e=>{n.hasOwnProperty(e)&&(i[e]=n[e])})),i}(t.target.result,e,i,r)),a.commit()}})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},mapSubscriptions:function(e,i,r){return this.isReady()?new Promise(((n,o)=>{const a=s.transaction(["subscription"]);a.onerror=e=>{t("PCache","mapSubscriptions",e.target.error),o(e.target.error)},a.objectStore("subscription").getAll(IDBKeyRange.bound([e,"-"],[e,"~"])).onsuccess=e=>{i&&e.target.result.forEach((e=>{i.call(r,e)})),n(e.target.result)}})):n?Promise.resolve([]):Promise.reject(new Error("not initialized"))},addMessage:function(e){return this.isReady()?new Promise(((n,i)=>{const r=s.transaction(["message"],"readwrite");r.onsuccess=e=>{n(e.target.result)},r.onerror=e=>{t("PCache","addMessage",e.target.error),i(e.target.error)},r.objectStore("message").add(o(null,e)),r.commit()})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},updMessageStatus:function(e,i,r){return this.isReady()?new Promise(((n,a)=>{const c=s.transaction(["message"],"readwrite");c.onsuccess=e=>{n(e.target.result)},c.onerror=e=>{t("PCache","updMessageStatus",e.target.error),a(e.target.error)};const h=c.objectStore("message").get(IDBKeyRange.only([e,i]));h.onsuccess=t=>{const s=h.result||t.target.result;s&&s._status!=r?(c.objectStore("message").put(o(s,{topic:e,seq:i,_status:r})),c.commit()):c.commit()}})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},remMessages:function(e,i,r){return this.isReady()?new Promise(((n,o)=>{i||r||(i=0,r=Number.MAX_SAFE_INTEGER);const a=r>0?IDBKeyRange.bound([e,i],[e,r],!1,!0):IDBKeyRange.only([e,i]),c=s.transaction(["message"],"readwrite");c.onsuccess=e=>{n(e.target.result)},c.onerror=e=>{t("PCache","remMessages",e.target.error),o(e.target.error)},c.objectStore("message").delete(a),c.commit()})):n?Promise.resolve():Promise.reject(new Error("not initialized"))},readMessages:function(e,i,r,o){return this.isReady()?new Promise(((n,a)=>{const c=(i=i||{}).since>0?i.since:0,h=i.before>0?i.before:Number.MAX_SAFE_INTEGER,u=0|i.limit,l=[],d=IDBKeyRange.bound([e,c],[e,h],!1,!0),p=s.transaction(["message"]);p.onerror=e=>{t("PCache","readMessages",e.target.error),a(e.target.error)},p.objectStore("message").openCursor(d,"prev").onsuccess=e=>{const t=e.target.result;t?(r&&r.call(o,t.value),l.push(t.value),u<=0||l.length<u?t.continue():n(l)):n(l)}})):n?Promise.resolve([]):Promise.reject(new Error("not initialized"))}}}static setDatabaseProvider(e){q=e}};var G={exports:{}};const W=["act","height","mime","name","ref","size","url","val","width"],F=[{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)/}],H=["QQ"],B=[{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}],V={BN:{name:"button",isVoid:!1},BR:{name:"br",isVoid:!0},CO:{name:"tt",isVoid:!1},DL:{name:"del",isVoid:!1},EM:{name:"i",isVoid:!1},EX:{name:"",isVoid:!0},FM:{name:"div",isVoid:!1},HD:{name:"",isVoid:!1},HL:{name:"span",isVoid:!1},HT:{name:"a",isVoid:!1},IM:{name:"img",isVoid:!1},LN:{name:"a",isVoid:!1},MN:{name:"a",isVoid:!1},RW:{name:"div",isVoid:!1},QQ:{name:"div",isVoid:!1},ST:{name:"b",isVoid:!1}};function Q(e,t,s){if(!e)return null;try{const s=atob(e),n=s.length,i=new ArrayBuffer(n),r=new Uint8Array(i);for(let e=0;e<n;e++)r[e]=s.charCodeAt(e);return URL.createObjectURL(new Blob([i],{type:t}))}catch(e){s&&s("Drafty: failed to convert object.",e.message)}return null}function z(e,t){return e?"data:"+(t=t||"image/jpeg")+";base64,"+e:null}const K={ST:{open:function(){return"<b>"},close:function(){return"</b>"}},EM:{open:function(){return"<i>"},close:function(){return"</i>"}},DL:{open:function(){return"<del>"},close:function(){return"</del>"}},CO:{open:function(){return"<tt>"},close:function(){return"</tt>"}},BR:{open:function(){return"<br/>"},close:function(){return""}},HD:{open:function(){return""},close:function(){return""}},HL:{open:function(){return'<span style="color:teal">'},close:function(){return"</span>"}},LN:{open:function(e){return'<a href="'+e.url+'">'},close:function(e){return"</a>"},props:function(e){return e?{href:e.url,target:"_blank"}:null}},MN:{open:function(e){return'<a href="#'+e.val+'">'},close:function(e){return"</a>"},props:function(e){return e?{id:e.val}:null}},HT:{open:function(e){return'<a href="#'+e.val+'">'},close:function(e){return"</a>"},props:function(e){return e?{id:e.val}:null}},BN:{open:function(e){return"<button>"},close:function(e){return"</button>"},props:function(e){return e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null}},IM:{open:function(e){const t=z(e._tempPreview,e.mime),s=Q(e.val,e.mime,X.logger),n=e.ref||s;return(e.name?'<a href="'+n+'" download="'+e.name+'">':"")+'<img src="'+(t||s)+'"'+(e.width?' width="'+e.width+'"':"")+(e.height?' height="'+e.height+'"':"")+' border="0" />'},close:function(e){return e.name?"</a>":""},props:function(e){return e?{src:z(e._tempPreview,e.mime)||e.ref||Q(e.val,e.mime,X.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:function(e){return"<div>"},close:function(e){return"</div>"}},RW:{open:function(e){return"<div>"},close:function(e){return"</div>"}},QQ:{open:function(e){return"<div>"},close:function(e){return"</div>"},props:function(e){return e?{}:null}}},X=function(){this.txt="",this.fmt=[],this.ent=[]};function J(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:n}=e;if(t=t||"",Array.isArray(n)||(n=[]),!Array.isArray(s)||0==s.length){if(0==n.length)return{text:t};s=[{at:0,len:0,key:0}]}const i=[],r=[];s.forEach((e=>{if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,o=0|e.len;if(o<0)return;let a=e.key||0;n.length>0&&("number"!=typeof a||a<0||a>=n.length)||(s<=-1?r.push({start:-1,end:0,key:a}):s+o>t.length||(e.tp?i.push({type:e.tp,start:s,end:s+o}):n.length>0&&"object"==typeof n[a]&&i.push({start:s,end:s+o,key:a})))})),i.sort(((e,t)=>{let s=e.start-t.start;return 0!=s||0!=(s=t.end-e.end)?s:H.indexOf(t.type)-H.indexOf(e.type)})),r.length>0&&i.push(...r),i.forEach((e=>{n.length>0&&!e.type&&(e.type=n[e.key].tp,e.data=n[e.key].data),e.type||(e.type="HD")}));let o=function e(t,s,n,i,r){if(!r||0==r.length)return n<i&&Y(t,{text:s.substring(n,i)}),t;for(let i=0;i<r.length;i++){const o=r[i];if(o.start<0&&"EX"==o.type){Y(t,{type:o.type,data:o.data,key:o.key,att:!0});continue}n<o.start&&(Y(t,{text:s.substring(n,o.start)}),n=o.start);const a=[];for(;i<r.length-1;){const e=r[i+1];if(e.start<0)break;if(!(e.start<o.end))break;if(e.end<=o.end){const t=V[e.tp]||{};(e.start<e.end||t.isVoid)&&a.push(e)}i++}Y(t,e({type:o.type,data:o.data,key:o.key},s,n,o.end,a)),n=o.end}return n<i&&Y(t,{text:s.substring(n,i)}),t}({},t,0,t.length,i);return Z(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}))}function Y(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 $(e,t,s){if(!t)return e;e.txt=e.txt||"";const n=e.txt.length;if(t.text?e.txt+=t.text:Array.isArray(t.children)&&t.children.forEach((t=>{$(e,t,s)})),t.type){const i=e.txt.length-n;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:n,len:i,key:r})}else e.fmt.push({tp:t.type,at:n,len:i})}return e}function Z(e,t,s){if(!e)return null;let n=t.call(s,e);if(!n||!n.children)return n;const i=[];for(let e in n.children){let r=n.children[e];r&&(r=Z(r,t,s))&&i.push(r)}return 0==i.length?n.children=null:n.children=i,n}function ee(e,t,s,n,i){if(!e)return null;n&&e.type&&n.push(e.type);let r=[];for(let s in e.children){const o=ee(e.children[s],t,s,n,i);o&&r.push(o)}return 0==r.length&&(r=e.text?[e.text]:null),n&&e.type&&n.pop(),t.call(i,e.type,e.data,r,s,n)}function te(e,t,s){return e?(s&&(t-=s.length),Z(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 n=e.text.length;n>t?(e.text=e.text.substring(0,t)+s,t=-1):t-=n}return e}))):null}function se(e){return Z(e,(function(e){const t=ie(e.data,!0);return t?e.data=t:delete e.data,e}))}function ne(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const s=[],n=[];for(let i in e.children){const r=e.children[i];if(r.att){if(s.length==t)continue;if("application/json"==r.data.mime)continue;delete r.att,delete r.children,r.text=" ",s.push(r)}else n.push(r)}e.children=n.concat(s)}return e}function ie(e,t,s){if(e&&Object.entries(e).length>0){s=s||[];const n={};if(W.forEach((i=>{if(e[i]){if(t&&!s.includes(i)&&("string"==typeof e[i]||Array.isArray(e[i]))&&e[i].length>64)return;if("object"==typeof e[i])return;n[i]=e[i]}})),0!=Object.entries(n).length)return n}return null}X.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},X.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],n={},i=[];t.forEach((e=>{let t,r,o=[];if(F.forEach((t=>{o=o.concat(function(e,t,s,n){const i=[];let r=0,o=e.slice(0);for(;o.length>0;){const a=t.exec(o);if(null==a)break;let c=a.index+a[0].lastIndexOf(a[1]);o=o.slice(c+1),r=(c+=r)+1;const h=s?s.exec(o):null;if(null==h)break;let u=h.index+h[0].indexOf(h[1]);o=o.slice(u+1),r=(u+=r)+1,i.push({txt:e.slice(c+1,u),children:[],at:c,end:u,tp:n})}return i}(e,t.start,t.end,t.name))})),0==o.length)r={txt:e};else{o.sort(((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end})),o=function e(t){if(0==t.length)return[];const s=[t[0]];let n=t[0];for(let e=1;e<t.length;e++)t[e].at>n.end?(s.push(t[e]),n=t[e]):t[e].end<=n.end&&n.children.push(t[e]);for(let t in s)s[t].children=e(s[t].children);return s}(o);const t=function e(t,s){let n="",i=[];for(let r in t){const o=t[r];if(!o.txt){const t=e(o.children,n.length+s);o.txt=t.txt,i=i.concat(t.fmt)}o.tp&&i.push({at:n.length+s,len:o.txt.length,tp:o.tp}),n+=o.txt}return{txt:n,fmt:i}}(function e(t,s,n,i){const r=[];if(0==i.length)return[];for(let n in i){const o=i[n];o.at>s&&r.push({txt:t.slice(s,o.at)});const a={tp:o.tp},c=e(t,o.at+1,o.end,o.children);c.length>0?a.children=c:a.txt=o.txt,r.push(a),s=o.end+1}return s<n&&r.push({txt:t.slice(s,n)}),r}(e,0,e.length,o),0);r={txt:t.txt,fmt:t.fmt}}if((t=function(e){let t,s=[];if(B.forEach((n=>{for(;null!==(t=n.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:n.pack(t[0]),type:n.name})})),0==s.length)return s;s.sort(((e,t)=>e.offset-t.offset));let n=-1;return s=s.filter((e=>{const t=e.offset>n;return n=e.offset+e.len,t}))}(r.txt)).length>0){const e=[];for(let i in t){const r=t[i];let o=n[r.unique];o||(o=s.length,n[r.unique]=o,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:o})}r.ent=e}i.push(r)}));const r={txt:""};if(i.length>0){r.txt=i[0].txt,r.fmt=(i[0].fmt||[]).concat(i[0].ent||[]);for(let e=1;e<i.length;e++){const t=i[e],s=r.txt.length+1;r.fmt.push({tp:"BR",len:1,at:s-1}),r.txt+=" "+t.txt,t.fmt&&(r.fmt=r.fmt.concat(t.fmt.map((e=>(e.at+=s,e))))),t.ent&&(r.fmt=r.fmt.concat(t.ent.map((e=>(e.at+=s,e)))))}0==r.fmt.length&&delete r.fmt,s.length>0&&(r.ent=s)}return r},X.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((n=>{const i={at:(0|n.at)+s,len:0|n.len};-1==n.at&&(i.at=-1,i.len=0),n.tp?i.tp=n.tp:(i.key=e.ent.length,e.ent.push(t.ent[n.key||0])),e.fmt.push(i)}))),e},X.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 n={tp:"IM",data:{mime:s.mime,val:s.preview,width:s.width,height:s.height,name:s.filename,size:0|s.size,ref:s.refurl}};return s.urlPromise&&(n.data._tempPreview=s._tempPreview,n.data._processing=!0,s.urlPromise.then((e=>{n.data.ref=e,n.data._tempPreview=void 0,n.data._processing=void 0}),(e=>{n.data._processing=void 0}))),e.ent.push(n),e},X.quote=function(e,t,s){const n=X.append(X.appendLineBreak(X.mention(e,t)),s);return n.fmt.push({at:0,len:n.txt.length,tp:"QQ"}),n},X.mention=function(e,t){return{txt:e||"",fmt:[{at:0,len:(e||"").length,key:0}],ent:[{tp:"MN",data:{val:t}}]}},X.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},X.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",X.insertImage(e,e.txt.length-1,t)},X.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},X.wrapInto=function(e,t,s,n){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:s||0,len:n||e.txt.length,tp:t}),e},X.wrapAsForm=function(e,t,s){return X.wrapInto(e,"FM",t,s)},X.insertButton=function(e,t,s,n,i,r,o){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length<t+s||s<=0||-1==["url","pub"].indexOf(i)?null:"url"!=i||o?(o=""+o,e.ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:s,key:e.ent.length}),e.ent.push({tp:"BN",data:{act:i,val:r,ref:o,name:n}}),e):null},X.appendButton=function(e,t,s,n,i,r){const o=(e=e||{txt:""}).txt.length;return e.txt+=t,X.insertButton(e,o,t.length,s,n,i,r)},X.attachJSON=function(e,t){return(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length}),e.ent.push({tp:"EX",data:{mime:"application/json",val:t}}),e},X.appendLineBreak=function(e){return(e=e||{txt:""}).fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:1,tp:"BR"}),e.txt+=" ",e},X.UNSAFE_toHTML=function(e){return ee(J(e),(function(e,t,s){const n=K[e];let i=s?s.join(""):"";return n&&(i=n.open(t)+i+n.close(t)),i}),0)},X.format=function(e,t,s){return ee(J(e),t,0,[],s)},X.shorten=function(e,t,s){let n=J(e);return(n=te(n,t,"…"))&&s&&(n=se(n)),$({},n,[])},X.forwardedContent=function(e){let t=J(e);return $({},t=function e(t){if("BR"==t.type)t=null;else if(t.text)t.type||(t.text=t.text.trimStart(),t.text||(t=null));else if(t.children&&t.children.length>0){const s=e(t.children[0]);s?t.children[0]=s:(t.children.shift(),t.type||0!=t.children.length||(t=null))}return t}(t=Z(t,(function(e){return"MN"!=e.type||e.parent&&e.parent.type?e:null}))),[])},X.replyContent=function(e,t){let s=J(e);return s?(s=Z(s,(function(e){return"QQ"==e.type?null:("MN"==e.type?e.parent&&e.parent.type||!(e.text||"").startsWith("➦")||(e.text="➦",delete e.children,delete e.data):"BR"==e.type&&(e.text=" ",delete e.type,delete e.children),e)})),$({},s=Z(s=te(s=ne(s,3),t,"…"),(e=>{const t=ie(e.data,!0,"IM"==e.type?["val"]:null);return t?e.data=t:delete e.data,e})),[])):e},X.preview=function(e,t){let s=J(e);return $({},s=se(s=te(s=Z(s=ne(s,3),(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})),t,"…")),[])},X.toPlainText=function(e){return"string"==typeof e?e:e.txt},X.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},X.isValid=function(e){if(!e)return!1;const{txt:t,fmt:s,ent:n}=e;if(!t&&""!==t&&!s&&!n)return!1;const i=typeof t;return!("string"!=i&&"undefined"!=i&&null!==t||void 0!==s&&!Array.isArray(s)&&null!==s||void 0!==n&&!Array.isArray(n)&&null!==n)},X.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},X.attachments=function(e,t,s){if(!Array.isArray(e.fmt))return;let n=0;e.fmt.forEach((i=>{if(i&&i.at<0){const r=e.ent[0|i.key];r&&"EX"==r.tp&&r.data&&t.call(s,r.data,n++,"EX")}}))},X.hasEntities=function(e){return e.ent&&e.ent.length>0},X.entities=function(e,t,s){if(e.ent&&e.ent.length>0)for(let n in e.ent)e.ent[n]&&t.call(s,e.ent[n].data,n,e.ent[n].tp)},X.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 n=ie(s.data);n?e.ent[t].data=n:delete e.ent[t].data}}return e},X.getDownloadUrl=function(e){let t=null;return"application/json"!=e.mime&&e.val?t=Q(e.val,e.mime,X.logger):"string"==typeof e.ref&&(t=e.ref),t},X.isProcessing=function(e){return!!e._processing},X.getPreviewUrl=function(e){return e.val?Q(e.val,e.mime,X.logger):null},X.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},X.getEntityMimeType=function(e){return e.mime||"text/plain"},X.tagName=function(e){return e?V[e]?V[e].name:"_UNKN":void 0},X.attrValue=function(e,t){if(t&&K[e])return K[e].props(t)},X.getContentType=function(){return"text/x-drafty"},G.exports=X,G=G.exports;var re={};let oe;Object.defineProperty(re,"__esModule",{value:!0}),re.default=void 0,re.default=class{constructor(e,t){this._tinode=e,this._version=t,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this._reqId=e.getNextUniqueId(),this.xhr=new oe,this.toResolve=null,this.toReject=null,this.onProgress=null,this.onSuccess=null,this.onFailure=null}uploadWithBaseUrl(e,t,s,n,i,o){if(!this._authToken)throw new Error("Must authenticate first");const a=this;let c="/v".concat(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 '".concat(e,"'"));c=t+c}this.xhr.open("POST",c,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token ".concat(this._authToken.token));const h=new Promise(((e,t)=>{this.toResolve=e,this.toReject=t}));this.onProgress=n,this.onSuccess=i,this.onFailure=o,this.xhr.upload.onprogress=e=>{e.lengthComputable&&a.onProgress&&a.onProgress(e.loaded/e.total)},this.xhr.onload=function(){let e;try{e=JSON.parse(this.response,r.jsonParseHelper)}catch(t){a._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(a.toResolve&&a.toResolve(e.ctrl.params.url),a.onSuccess&&a.onSuccess(e.ctrl)):this.status>=400?(a.toReject&&a.toReject(new Error("".concat(e.ctrl.text," (").concat(e.ctrl.code,")"))),a.onFailure&&a.onFailure(e.ctrl)):a._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},this.xhr.onerror=function(e){a.toReject&&a.toReject(new Error("failed")),a.onFailure&&a.onFailure(null)},this.xhr.onabort=function(e){a.toReject&&a.toReject(new Error("upload cancelled by user")),a.onFailure&&a.onFailure(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._reqId),s&&e.set("topic",s),this.xhr.send(e)}catch(e){this.toReject&&this.toReject(e),this.onFailure&&this.onFailure(null)}return h}upload(e,t,s,n,i){const r=(this._tinode._secure?"https://":"http://")+this._tinode._host;return this.uploadWithBaseUrl(r,e,t,s,n,i)}download(e,t,s,n,i){if(!Tinode.isRelativeURL(e))return void(i&&i("The URL '".concat(e,"' must be relative, not absolute")));if(!this._authToken)return void(i&&i("Must authenticate first"));const o=this;this.xhr.open("GET",e,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),this.xhr.responseType="blob",this.onProgress=n,this.xhr.onprogress=function(e){o.onProgress&&o.onProgress(e.loaded)};const a=new Promise(((e,t)=>{this.toResolve=e,this.toReject=t}));this.xhr.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.toResolve&&o.toResolve()}else if(this.status>=400&&o.toReject){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,r.jsonParseHelper);o.toReject(new Error("".concat(e.ctrl.text," (").concat(e.ctrl.code,")")))}catch(e){o._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),o.toReject(e)}},e.readAsText(this.response)}},this.xhr.onerror=function(e){o.toReject&&o.toReject(new Error("failed"))},this.xhr.onabort=function(){o.toReject&&o.toReject(null)};try{this.xhr.send()}catch(e){this.toReject&&this.toReject(e)}return a}cancel(){this.xhr&&this.xhr.readyState<4&&this.xhr.abort()}getId(){return this._reqId}static setNetworkProvider(e){oe=e}};var ae={};function ce(e,t){ue(e,t),t.add(e)}function he(e,t,s){ue(e,t),t.set(e,s)}function ue(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function le(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}function de(e,t){return function(e,t){return t.get?t.get.call(e):t.value}(e,fe(e,t,"get"))}function pe(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,fe(e,t,"set"),s),s}function fe(e,t,s){if(!t.has(e))throw new TypeError("attempted to "+s+" private field on non-instance");return t.get(e)}Object.defineProperty(ae,"__esModule",{value:!0}),ae.default=void 0;var ge=new WeakMap,_e=new WeakMap,me=new WeakSet,be=new WeakSet;function Se(e,t,s){let n=0,i=t.length-1,r=0,o=0,a=!1;for(;n<=i;)if(r=(n+i)/2|0,(o=de(this,ge).call(this,t[r],e))<0)n=r+1;else{if(!(o>0)){a=!0;break}i=r-1}return a?{idx:r,exact:!0}:s?{idx:-1}:{idx:o<0?r+1:r}}function Ee(e,t){const s=le(this,me,Se).call(this,e,t,!1),n=s.exact&&de(this,_e)?1:0;return t.splice(s.idx,n,e),t}ae.default=class{constructor(e,t){var s;ce(this,be),ce(this,me),he(this,ge,{writable:!0,value:void 0}),he(this,_e,{writable:!0,value:!1}),s=[],"buffer"in this?Object.defineProperty(this,"buffer",{value:s,enumerable:!0,configurable:!0,writable:!0}):this.buffer=s,pe(this,ge,e||((e,t)=>e===t?0:e<t?-1:1)),pe(this,_e,t)}getAt(e){return this.buffer[e]}getLast(e){return e|=0,this.buffer.length>e?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)le(this,be,Ee).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,n){t|=0,s=s||this.buffer.length;for(let i=t;i<s;i++)e.call(n,this.buffer[i],i>t?this.buffer[i-1]:void 0,i<s-1?this.buffer[i+1]:void 0,i)}find(e,t){const{idx:s}=findNearest(e,this.buffer,!t);return s}filter(e,t){let s=0;for(let n=0;n<this.buffer.length;n++)e.call(t,this.buffer[n],n)&&(this.buffer[s]=this.buffer[n],s++);this.buffer.splice(s)}};var we={};function Te(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 ve(e,t,s){if(!t.has(e))throw new TypeError("attempted to get private field on non-instance");return s}Object.defineProperty(we,"__esModule",{value:!0}),we.default=void 0;var Me=new WeakSet,Pe=new WeakSet;function ye(){return this.topic.updated}function Ae(){return this.topic.isP2PType()?ve(this,Me,ye).call(this):this.topic._lastSubsUpdate}we.default=class{constructor(e){Te(this,Pe),Te(this,Me),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(ve(this,Me,ye).call(this))}withSub(e,t,s){const n={ims:e,limit:t};return"me"==this.topic.getType()?n.topic=s:n.user=s,this.what.sub=n,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(ve(this,Pe,Ae).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"].map((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}};var Re={};Object.defineProperty(Re,"__esModule",{value:!0}),Re.TopicMe=Re.TopicFnd=Re.Topic=void 0;var De=Ne(e),Oe=Ne(ae),xe=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var s=function(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap;new WeakMap;return t}();if(s&&s.has(e))return s.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var r in e)if("default"!==r&&Object.prototype.hasOwnProperty.call(e,r)){var o=i?Object.getOwnPropertyDescriptor(e,r):null;o&&(o.get||o.set)?Object.defineProperty(n,r,o):n[r]=e[r]}return n.default=e,s&&s.set(e,n),n}(i),Ce=Ne(G),Ie=Ne(we);function Ne(e){return e&&e.__esModule?e:{default:e}}class Ue{constructor(e,t){this._tinode=null,this.name=e,this.created=null,this.updated=null,this.touched=new Date(0),this.acs=new De.default(null),this.private=null,this.public=null,this.trusted=null,this._users={},this._queuedSeqId=xe.LOCAL_SEQID,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._tags=[],this._credentials=[],this._messages=new Oe.default(((e,t)=>e.seq-t.seq),!0),this._subscribed=!1,this._lastSubsUpdate=new Date(0),this._new=!0,this._deleted=!1,t&&(this.onData=t.onData,this.onMeta=t.onMeta,this.onPres=t.onPres,this.onInfo=t.onInfo,this.onMetaDesc=t.onMetaDesc,this.onMetaSub=t.onMetaSub,this.onSubsUpdated=t.onSubsUpdated,this.onTagsUpdated=t.onTagsUpdated,this.onCredsUpdated=t.onCredsUpdated,this.onDeleteTopic=t.onDeleteTopic,this.onAllMessagesReceived=t.onAllMessagesReceived)}static topicType(e){return{me:xe.TOPIC_ME,fnd:xe.TOPIC_FND,grp:xe.TOPIC_GRP,new:xe.TOPIC_GRP,nch:xe.TOPIC_GRP,chn:xe.TOPIC_GRP,usr:xe.TOPIC_P2P,sys:xe.TOPIC_SYS}["string"==typeof e?e.substring(0,3):"xxx"]}static isMeTopicName(e){return Ue.topicType(e)==xe.TOPIC_ME}static isGroupTopicName(e){return Ue.topicType(e)==xe.TOPIC_GRP}static isP2PTopicName(e){return Ue.topicType(e)==xe.TOPIC_P2P}static isCommTopicName(e){return Ue.isP2PTopicName(e)||Ue.isGroupTopicName(e)}static isNewGroupTopicName(e){return"string"==typeof e&&(e.substring(0,3)==xe.TOPIC_NEW||e.substring(0,3)==xe.TOPIC_NEW_CHAN)}static isChannelTopicName(e){return"string"==typeof e&&(e.substring(0,3)==xe.TOPIC_CHAN||e.substring(0,3)==xe.TOPIC_NEW_CHAN)}isSubscribed(){return this._subscribed}subscribe(e,t){return this._subscribed?Promise.resolve(this):this._tinode.subscribe(this.name||TOPIC_NEW,e,t).then((e=>{if(e.code>=300)return e;if(this._subscribed=!0,this._deleted=!1,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(this._new=!1,this.name!=e.topic&&(this._cacheDelSelf(),this.name=e.topic),this._cachePutSelf(),this.created=e.ts,this.updated=e.ts,this.name!=TOPIC_ME&&this.name!=TOPIC_FND){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._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));let t=null;return Ce.default.hasEntities(e.content)&&(t=[],Ce.default.entities(e.content,(e=>{e&&e.ref&&t.push(e.ref)})),0==t.length&&(t=null)),e._sending=!0,e._failed=!1,this._tinode.publishMessage(e,t).then((t=>(e._sending=!1,e.ts=t.ts,this.swapMessageId(e,t.params.seq),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){if(!t&&!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));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((()=>e._cancelled?{code:300,text:"cancelled"}:this.publishMessage(e)),(t=>{this._tinode.logger("WARNING: Message draft rejected",t),e._sending=!1,e._failed=!0,this._messages.delAt(this._messages.find(e)),this._tinode._db.remMessages(this.name,e.seq),this.onData&&this.onData()}))}leave(e){return this._subscribed||e?this._tinode.leave(this.name,e).then((t=>(this._resetSub(),e&&this._gone(),t))):Promise.reject(new Error("Cannot leave inactive topic"))}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((n=>{if(n==e)return Promise.resolve({topic:this.name,code:200,params:{count:n}});e-=n,s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);let i=this.getMeta(s.build());return t||(i=i.then((e=>{e&&e.params&&!e.params.count&&(this._noEarlierMsgs=!0)}))),i}))}setMeta(e){return e.tags&&(e.tags=(0,r.normalizeArray)(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,n=s?s.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:n}})}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||xe.DEL_CHAR}}})}delMessages(e,t){if(!this._subscribed)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort(((e,t)=>e.low<t.low||e.low==t.low&&(!t.hi||e.hi>=t.hi)));let s,n=e.reduce(((e,t)=>(t.low<xe.LOCAL_SEQID&&(!t.hi||t.hi<xe.LOCAL_SEQID?e.push(t):e.push({low:t.low,hi:this._maxSeq+1})),e)),[]);return(s=n.length>0?this._tinode.delMessages(this.name,n,t):Promise.resolve({params:{del:0}})).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._updateDeletedRanges(),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)}delTopic(e){return this._deleted?(this._gone(),new Promise.resolve(null)):this._tinode.delTopic(this.name,e).then((e=>(this._resetSub(),this._gone(),e)))}delSubscription(e){return this._subscribed?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._subscribed)return;const s=this._users[this._tinode.getCurrentUserID()];let n=!1;s?(!s[e]||s[e]<t)&&(s[e]=t,n=!0):n=(0|this[e])<t,n&&(this._tinode.note(this.name,e,t),this._updateReadRecv(e,t),null!=this.acs&&!this.acs.isMuted())&&this._tinode.getMeTopic()._refreshContact(e,this)}noteRecv(e){this.note("recv",e)}noteRead(e){(e=e||this._maxSeq)>0&&this.note("read",e)}noteKeyPress(){this._subscribed?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")}_updateReadRecv(e,t,s){let n,i=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":n=this.recv,this.recv=Math.max(this.recv,t),i=n!=this.recv;break;case"read":n=this.read,this.read=Math.max(this.read,t),i=n!=this.read;break;case"msg":n=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched<s)&&(this.touched=s),i=n!=this.seq}return this.recv<this.read&&(this.recv=this.read,i=!0),this.seq<this.recv&&(this.seq=this.recv,(!this.touched||this.touched<s)&&(this.touched=s),i=!0),this.unread=this.seq-this.read,i}userDesc(e){const t=this._cacheGetUser(e);if(t)return t}p2pPeerDesc(){if(this.isP2PType())return this._users[this.name]}subscribers(e,t){const s=e||this.onMetaSub;if(s)for(let e in this._users)s.call(t,this._users[e],e,this._users)}tags(){return this._tags.slice(0)}subscriber(e){return this._users[e]}messages(e,t,s,n){const i=e||this.onData;if(i){const e="number"==typeof t?this._messages.find({seq:t},!0):void 0,r="number"==typeof s?this._messages.find({seq:s},!0):void 0;-1!=e&&-1!=r&&this._messages.forEach(i,e,r,n)}}findMessage(e){const t=this._messages.find({seq:e});if(t>=0)return this._messages.getAt(t)}latestMessage(e){const t=this._messages.getLast();return e&&t&&t._status==xe.MESSAGE_STATUS_DEL_RANGE?this._messages.getLast(1):t}maxMsgSeq(){return this._maxSeq}maxClearId(){return this._maxDel}messageCount(){return this._messages.length()}queuedMessages(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,xe.LOCAL_SEQID,void 0,t)}msgReceiptCount(e,t){let s=0;if(t>0){const n=this._tinode.getCurrentUserID();for(let i in this._users){const r=this._users[i];r.user!==n&&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(t>=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)}swapMessageId(e,t){const s=this._messages.find(e),n=this._messages.length();0<=s&&s<n&&(this._messages.delAt(s),this._tinode._db.remMessages(this.name,e.seq),e.seq=t,this._messages.put(e),this._tinode._db.addMessage(e))}flushMessageRange(e,t){this._tinode._db.remMessages(this.name,e,t);const s=this._messages.find({seq:e},!0);return s>=0?this._messages.delRange(s,this._messages.find({seq:t},!0)):[]}cancelSend(e){const t=this._messages.find({seq:e});if(t>=0){const s=this._messages.getAt(t),n=this.msgStatus(s);if(n==xe.MESSAGE_STATUS_QUEUED||n==xe.MESSAGE_STATUS_FAILED)return this._tinode._db.remMessages(this.name,e),s._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1}getType(){return Ue.topicType(this.name)}getAccessMode(){return this.acs}setAccessMode(e){return this.acs=new De.default(e)}getDefaultAccess(){return this.defacs}startMetaQuery(){return new Ie.default(this)}isArchived(){return this.private&&!!this.private.arch}isMeType(){return Ue.isMeTopicName(this.name)}isChannelType(){return Ue.isChannelTopicName(this.name)}isGroupType(){return Ue.isGroupTopicName(this.name)}isP2PType(){return Ue.isP2PTopicName(this.name)}isCommType(){return Ue.isCommTopicName(this.name)}msgStatus(e,t){let s=xe.MESSAGE_STATUS_NONE;return this._tinode.isMe(e.from)?e._sending?s=xe.MESSAGE_STATUS_SENDING:e._failed||e._cancelled?s=xe.MESSAGE_STATUS_FAILED:e.seq>=xe.LOCAL_SEQID?s=xe.MESSAGE_STATUS_QUEUED:this.msgReadCount(e.seq)>0?s=xe.MESSAGE_STATUS_READ:this.msgRecvCount(e.seq)>0?s=xe.MESSAGE_STATUS_RECEIVED:e.seq>0&&(s=xe.MESSAGE_STATUS_SENT):e._status==xe.MESSAGE_STATUS_DEL_RANGE?xe.MESSAGE_STATUS_DEL_RANGE:s=xe.MESSAGE_STATUS_TO_ME,t&&e._status!=s&&(e._status=s,this._tinode._db.updMessageStatus(this.name,e.seq,s)),s}_routeData(e){e.content&&(!this.touched||this.touched<e.ts)&&(this.touched=e.ts,this._tinode._db.updTopic(this)),e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq<this._minSeq||0==this._minSeq)&&(this._minSeq=e.seq),e._noForwarding||(this._messages.put(e),this._tinode._db.addMessage(e),this._updateDeletedRanges()),this.onData&&this.onData(e);const t=!this.isChannelType()&&!e.from||this._tinode.isMe(e.from)?"read":"msg";this._updateReadRecv(t,e.seq,e.ts),this._tinode.getMeTopic()._refreshContact(t,this)}_routeMeta(e){e.desc&&this._processMetaDesc(e.desc),e.sub&&e.sub.length>0&&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 t,s;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":(t=this._users[e.src])?t.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(s=e.src||this._tinode.getCurrentUserID(),t=this._users[s])t.acs.updateAll(e.dacs),this._processMetaSub([{user:s,updated:new Date,acs:t.acs}]);else{const n=(new De.default).updateAll(e.dacs);n&&n.mode!=De.default._NONE&&((t=this._cacheGetUser(s))?t.acs=n:(t={user:s,acs:n},this.getMeta(this.startMetaQuery().withOneSub(void 0,s).build())),t.updated=new Date,this._processMetaSub([t]))}break;default:this._tinode.logger("INFO: Ignored presence update",e.what)}this.onPres&&this.onPres(e)}_routeInfo(e){if("kp"!==e.what){const t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv<t.read&&(t.recv=t.read));const s=this.latestMessage();s&&this.msgStatus(s,!0),this._tinode.isMe(e.from)&&this._updateReadRecv(e.what,e.seq),this._tinode.getMeTopic()._refreshContact(e.what,this)}this.onInfo&&this.onInfo(e)}_processMetaDesc(e){if(this.isP2PType()&&(delete e.defacs,this._tinode._db.updUser(this.name,e.public)),(0,r.mergeObj)(this,e),this._tinode._db.updTopic(this),this.name!==xe.TOPIC_ME&&!e._noForwarding){const e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}this.onMetaDesc&&this.onMetaDesc(this)}_processMetaSub(e){for(let t in e){const s=e[t];s.online=!!s.online,this._lastSubsUpdate=new Date(Math.max(this._lastSubsUpdate,s.updated));let n=null;s.deleted?(delete this._users[s.user],n=s):(this._tinode.isMe(s.user)&&s.acs&&this._processMetaDesc({updated:s.updated,touched:s.touched,acs:s.acs}),n=this._updateCachedUser(s.user,s)),this.onMetaSub&&this.onMetaSub(n)}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))}_processMetaTags(e){1==e.length&&e[0]==xe.DEL_CHAR&&(e=[]),this._tags=e,this.onTagsUpdated&&this.onTagsUpdated(e)}_processMetaCreds(e){}_processDelMessages(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);const s=this;let n=0;Array.isArray(t)&&t.forEach((function(e){if(e.hi)for(let t=e.low;t<e.hi;t++)n++,s.flushMessage(t);else n++,s.flushMessage(e.low)})),n>0&&(this._updateDeletedRanges(),this.onData&&this.onData())}_allMessagesReceived(e){this._updateDeletedRanges(),this.onAllMessagesReceived&&this.onAllMessagesReceived(e)}_resetSub(){this._subscribed=!1}_gone(){this._messages.reset(),this._tinode._db.remMessages(this.name),this._users={},this.acs=new De.default(null),this.private=null,this.public=null,this.trusted=null,this._maxSeq=0,this._minSeq=0,this._subscribed=!1;const e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:xe.TOPIC_ME,src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()}_updateCachedUser(e,t){let s=this._cacheGetUser(e);return s=(0,r.mergeObj)(s||{},t),this._cachePutUser(e,s),(0,r.mergeToCache)(this._users,e,s)}_getQueuedSeqId(){return this._queuedSeqId++}_updateDeletedRanges(){const e=[];let t=null;const s=this._messages.getAt(0);s&&this._minSeq>1&&!this._noEarlierMsgs?s.hi?(s.seq>1&&(s.seq=1),s.hi<this._minSeq-1&&(s.hi=this._minSeq-1),t=s):(t={seq:1,hi:this._minSeq-1},e.push(t)):t={seq:0,hi:0},this._messages.filter((s=>s.seq>=xe.LOCAL_SEQID||(s.seq==(t.hi||t.seq)+1?s.hi&&t.hi?(t.hi=s.hi,!1):(t=s,!0):(t.hi?t.hi=s.hi||s.seq:(t={seq:t.seq+1,hi:s.hi||s.seq},e.push(t)),!s.hi&&(t=s,!0)))));const n=this._messages.getLast(),i=Math.max(this.seq,this._maxSeq)||0;(i>0&&!n||n&&(n.hi||n.seq)<i)&&(n&&n.hi?n.hi=i:e.push({seq:n?n.seq+1:1,hi:i})),e.forEach((e=>{e._status=xe.MESSAGE_STATUS_DEL_RANGE,this._messages.put(e)}))}_loadMessages(e,t){const{since:s,before:n,limit:i}=t||{};return e.readMessages(this.name,{since:s,before:n,limit:i||xe.DEFAULT_MESSAGES_PAGE}).then((e=>(e.forEach((e=>{e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq<this._minSeq||0==this._minSeq)&&(this._minSeq=e.seq),this._messages.put(e)})),e.length>0&&this._updateDeletedRanges(),e.length)))}_updateReceived(e,t){this.touched=new Date,this.seq=0|e,t&&!this._tinode.isMe(t)||(this.read=this.read?Math.max(this.read,this.seq):this.seq,this.recv=this.recv?Math.max(this.read,this.recv):this.read),this.unread=this.seq-(0|this.read),this._tinode._db.updTopic(this)}}Re.Topic=Ue,Re.TopicMe=class extends Ue{constructor(e){super(xe.TOPIC_ME,e),e&&(this.onContactUpdate=e.onContactUpdate)}_processMetaDesc(e){const t=e.acs&&!e.acs.isPresencer()&&this.acs&&this.acs.isPresencer();(0,r.mergeObj)(this,e),this._tinode._db.updTopic(this),this._updateCachedUser(this._tinode._myUID,e),t&&this._tinode.cacheMap("topic",(e=>{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==xe.TOPIC_FND||s==xe.TOPIC_ME)return;e.online=!!e.online;let n=null;if(e.deleted)n=e,this._tinode.cacheDel("topic",s),this._tinode._db.remTopic(s);else if(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),n=(0,r.mergeObj)(this._tinode.getTopic(s),e),this._tinode._db.updTopic(n),Ue.isP2PTopicName(s)&&(this._cachePutUser(s,n),this._tinode._db.updUser(s,n.public)),!e._noForwarding){const t=this._tinode.getTopic(s);t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(n)})),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]==xe.DEL_CHAR&&(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)))>=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==xe.TOPIC_ME)return void this.getMeta(this.startMetaQuery().withDesc().build());const t=this._tinode.cacheGet("topic",e.src);if(t){switch(e.what){case"on":t.online=!0;break;case"off":t.online&&(t.online=!1,t.seen=Object.assign(t.seen||{},{when:new Date}));break;case"msg":t._updateReceived(e.seq,e.act);break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":t.acs?t.acs.updateAll(e.dacs):t.acs=(new De.default).updateAll(e.dacs),t.touched=new Date;break;case"ua":t.seen={when:new Date,ua:e.ua};break;case"recv":e.seq=0|e.seq,t.recv=t.recv?Math.max(t.recv,e.seq):e.seq;break;case"read":e.seq=0|e.seq,t.read=t.read?Math.max(t.read,e.seq):e.seq,t.recv=t.recv?Math.max(t.read,t.recv):t.recv,t.unread=t.seq-t.read;break;case"gone":this._tinode.cacheDel("topic",e.src),this._tinode._db.remTopic(e.src);break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",e.what)}this._refreshContact(e.what,t)}else if("acs"==e.what){const t=new De.default(e.dacs);if(!t||t.mode==De.default._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(t.mode==De.default._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 s=this._tinode.getTopic(e.src);s.topic=e.src,s.online=!1,s.acs=t,this._tinode.attachCacheToTopic(s),s._cachePutSelf(),this._tinode._db.updTopic(s)}}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._subscribed?this._tinode.delCredential(e,t).then((s=>{const n=this._credentials.findIndex((s=>s.meth==e&&s.val==t));return n>-1&&this._credentials.splice(n,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.cacheMap("topic",((n,i)=>{!n.isCommType()||t&&!t(n)||e.call(s,n,i)}))}getContact(e){return this._tinode.cacheGet("topic",e)}getAccessMode(e){if(e){const t=this._tinode.cacheGet("topic",e);return t?t.acs:null}return this.acs}isArchived(e){const t=this._tinode.cacheGet("topic",e);return t&&t.private&&!!t.private.arch}getCredentials(){return this._credentials}};const ke=function(e){Ue.call(this,xe.TOPIC_FND,e),this._contacts={}};Re.TopicFnd=ke,(ke.prototype=Object.create(Ue.prototype,{_processMetaSub:{value:function(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let s in e){let n=e[s];const i=n.topic?n.topic:n.user;n=(0,r.mergeToCache)(this._contacts,i,n),t++,this.onMetaSub&&this.onMetaSub(n)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0},publish:{value:function(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))},enumerable:!0,configurable:!0},setMeta:{value:function(e){const t=this;return Object.getPrototypeOf(ke.prototype).setMeta.call(this,e).then((()=>{Object.keys(t._contacts).length>0&&(t._contacts={},t.onSubsUpdated&&t.onSubsUpdated([]))}))},enumerable:!0,configurable:!0},contacts:{value:function(e,t){const s=e||this.onMetaSub;if(s)for(let e in this._contacts)s.call(t,this._contacts[e],e,this._contacts)},enumerable:!0,configurable:!0}})).constructor=ke;var je={};return function(t){(function(){"use strict";Object.defineProperty(je,"__esModule",{value:!0}),je.default=void 0;var s=l(e),n=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var s=function(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap;new WeakMap;return t}();if(s&&s.has(e))return s.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var r in e)if("default"!==r&&Object.prototype.hasOwnProperty.call(e,r)){var o=i?Object.getOwnPropertyDescriptor(e,r):null;o&&(o.get||o.set)?Object.defineProperty(n,r,o):n[r]=e[r]}return n.default=e,s&&s.set(e,n),n}(i),o=l(u),a=l(L),c=l(G),h=l(re);function l(e){return e&&e.__esModule?e:{default:e}}function d(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}let p,f,g;function _(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function m(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":function(e,t){if(t instanceof Date)t=(0,r.rfc3339DateString)(t);else if(t instanceof s.default)t=t.jsonHelper();else if(null==t||!1===t||Array.isArray(t)&&0==t.length||"object"==typeof t&&0==Object.keys(t).length)return;return t}(0,t)}"undefined"!=typeof WebSocket&&(p=WebSocket),"undefined"!=typeof XMLHttpRequest&&(f=XMLHttpRequest),"undefined"!=typeof indexedDB&&(g=indexedDB),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(t.btoa=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s=t,n="";for(let t,i=0,r=0,o=e;s.charAt(0|r)||(o="=",r%1);n+=o.charAt(63&i>>8-r%1*8)){if((t=s.charCodeAt(r+=.75))>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");i=i<<8|t}return n}),"undefined"==typeof atob&&(t.atob=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s=t.replace(/=+$/,""),n="";if(s.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let t,i=0,r=0,o=0;t=s.charAt(o++);~t&&(r=i%4?64*r+t:t,i++%4)?n+=String.fromCharCode(255&r>>(-2*i&6)):0)t=e.indexOf(t);return n}),"undefined"==typeof window&&(t.window={WebSocket:p,XMLHttpRequest:f,indexedDB:g,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}}),o.default.setNetworkProviders(p,f),h.default.setNetworkProvider(f),a.default.setDatabaseProvider(g)}();class b{constructor(e,t){var s=this;d(this,"onWebsocketOpen",void 0),d(this,"onConnect",void 0),d(this,"onDisconnect",void 0),d(this,"onLogin",void 0),d(this,"onCtrlMessage",void 0),d(this,"onDataMessage",void 0),d(this,"onPresMessage",void 0),d(this,"onMessage",void 0),d(this,"onRawMessage",void 0),d(this,"onNetworkProbe",void 0),d(this,"onAutoreconnectIteration",void 0),this._host=e.host,this._secure=e.secure,this._appName=e.appName||"Undefined",this._apiKey=e.apiKey,this._browser="",this._platform=e.platform||"web",this._hwos="undefined",this._humanLanguage="xx","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";let s,n="";/reactnative/i.test(t)&&(n="ReactNative; ");let i=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(i){const t=["edg","chrome","safari","mobile","version"];let n,r=e.substr(i.index+i[0].length).split(" "),o=[];for(let e=0;e<r.length;e++){let s=/([\w.]+)[\/]([\.\d]+)/.exec(r[e]);s&&(o.push([s[1],s[2],t.findIndex((e=>s[1].toLowerCase().startsWith(e)))]),"Version"==s[1]&&(n=s[2]))}o.sort(((e,t)=>e[2]-t[2])),o.length>0?(o[0][0].toLowerCase().startsWith("edg")?o[0][0]="Edge":"OPR"==o[0][0]?o[0][0]="Opera":"Safari"==o[0][0]&&n&&(o[0][1]=n),s=o[0][0]+"/"+o[0][1]):s=i[1]}else s=/firefox/i.test(e)?(i=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+i[1]:"Firefox/?":(i=/([\w.]+)\/([.\d]+)/.exec(e))?i[1]+"/"+i[2]:(i=e.split(" "))[0];if((i=s.split("/")).length>1){const e=i[1].split("."),t=e[1]?"."+e[1].substr(0,2):"";s="".concat(i[0],"/").concat(e[0]).concat(t)}return n+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),this._loggingEnabled=!1,this._trimLongStrings=!1,this._myUID=null,this._authenticated=!1,this._login=null,this._authToken=null,this._inPacketCount=0,this._messageId=Math.floor(65535*Math.random()+65535),this._serverInfo=null,this._deviceToken=null,this._pendingPromises={},this._expirePromises=null,this.logger=function(e){if(s._loggingEnabled){const s=new Date,r=("0"+s.getUTCHours()).slice(-2)+":"+("0"+s.getUTCMinutes()).slice(-2)+":"+("0"+s.getUTCSeconds()).slice(-2)+"."+("00"+s.getUTCMilliseconds()).slice(-3);for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];console.log("["+r+"]",e,n.join(" "))}},o.default.logger=this.logger,c.default.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 o.default(e,n.PROTOCOL_VERSION,!0),this._cache={};const i=this.cachePut=(e,t,s)=>{this._cache[e+":"+t]=s},h=this.cacheGet=(e,t)=>this._cache[e+":"+t],u=this.cacheDel=(e,t)=>{delete this._cache[e+":"+t]},l=this.cacheMap=(e,t,s)=>{const n=e?e+":":void 0;for(let e in this._cache)if((!n||0==e.indexOf(n))&&t.call(s,this._cache[e],e))break};if(this.attachCacheToTopic=e=>{e._tinode=this,e._cacheGetUser=e=>{const t=h("user",e);if(t)return{user:e,public:(0,r.mergeObj)({},t)}},e._cachePutUser=(e,t)=>i("user",e,(0,r.mergeObj)({},t.public)),e._cacheDelUser=e=>u("user",e),e._cachePutSelf=()=>i("topic",e.name,e),e._cacheDelSelf=()=>u("topic",e.name)},this._persist=e.persist,this._db=new a.default((e=>{this.logger("DB",e)}),this.logger),this._persist){const e=[];this._db.initDatabase().then((()=>this._db.mapTopics((t=>{let s=this.cacheGet("topic",t.name);s||(s=t.name==n.TOPIC_ME?new Re.TopicMe:t.name==n.TOPIC_FND?new Re.TopicFnd:new Re.Topic(t.name),this._db.deserializeTopic(s,t),this.attachCacheToTopic(s),s._cachePutSelf(),e.push(s._loadMessages(this._db)))})))).then((()=>this._db.mapUsers((e=>i("user",e.uid,(0,r.mergeObj)({},e.public)))))).then((()=>Promise.all(e))).then((()=>{t&&t(),this.logger("Persistent cache initialized.")}))}else this._db.deleteDatabase().then((()=>{t&&t()}));const p=(e,t,s,n)=>{const i=this._pendingPromises[e];i&&(delete this._pendingPromises[e],t>=200&&t<400?i.resolve&&i.resolve(s):i.reject&&i.reject(new Error("".concat(n," (").concat(t,")"))))},f=e=>{let t=null;return e&&(t=new Promise(((t,s)=>{this._pendingPromises[e]={resolve:t,reject:s,ts:new Date}}))),t},g=this.getNextUniqueId=()=>0!=this._messageId?""+this._messageId++:void 0,_=()=>this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+n.LIBRARY;this.initPacket=(e,t)=>{switch(e){case"hi":return{hi:{id:g(),ver:n.VERSION,ua:_(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:g(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:g(),scheme:null,secret:null}};case"sub":return{sub:{id:g(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:g(),topic:t,unsub:!1}};case"pub":return{pub:{id:g(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:g(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:g(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:g(),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: ".concat(e))}},this.send=(e,t)=>{let s;t&&(s=f(t)),e=(0,r.simplify)(e);let n=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,m):n));try{this._connection.sendText(n)}catch(e){if(!t)throw e;p(t,o.default.NETWORK_ERROR,null,e.message)}return s},this.loginSuccessful=e=>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,this._connection.onMessage=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,r.jsonParseHelper);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,m):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&p(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout((()=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=h("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=h("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=h("topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((()=>{if(t.meta){const e=h("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&p(t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=h("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=h("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=h("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"))},this._connection.onOpen=()=>{this._expirePromises||(this._expirePromises=setInterval((()=>{const e=new Error("Timeout (504)"),t=new Date((new Date).getTime()-n.EXPIRE_PROMISES_TIMEOUT);for(let s in this._pendingPromises){let n=this._pendingPromises[s];n&&n.ts<t&&(this.logger("Promise expired",s),delete this._pendingPromises[s],n.reject&&n.reject(e))}}),n.EXPIRE_PROMISES_PERIOD)),this.hello()},this._connection.onAutoreconnectIteration=(e,t)=>{this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e,t)},this._connection.onDisconnect=(e,t)=>{this._inPacketCount=0,this._serverInfo=null,this._authenticated=!1,this._expirePromises&&(clearInterval(this._expirePromises),this._expirePromises=null),l("topic",((e,t)=>{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)}}static credential(e,t,s,n){return"object"==typeof e&&({val:t,params:s,resp:n,meth:e}=e),e&&(t||n)?[{meth:e,val:t,resp:n,params:s}]:null}static topicType(e){return Re.Topic.topicType(e)}static isMeTopicName(e){return Re.Topic.isMeTopicName(e)}static isGroupTopicName(e){return Re.Topic.isGroupTopicName(e)}static isP2PTopicName(e){return Re.Topic.isP2PTopicName(e)}static isCommTopicName(e){return Re.Topic.isCommTopicName(e)}static isNewGroupTopicName(e){return Re.Topic.isNewGroupTopicName(e)}static isChannelTopicName(e){return Re.Topic.isChannelTopicName(e)}static getVersion(){return n.VERSION}static setNetworkProviders(e,t){p=e,f=t,o.default.setNetworkProviders(p,f),h.default.setNetworkProvider(f)}static setDatabaseProvider(e){g=e,a.default.setDatabaseProvider(g)}static getLibrary(){return n.LIBRARY}static isNullValue(e){return e===n.DEL_CHAR}static isRelativeURL(e){return!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}connect(e){return this._connection.connect(e)}reconnect(e){this._connection.reconnect(e)}disconnect(){this._connection.disconnect()}clearStorage(){return this._db.isReady()?this._db.deleteDatabase():Promise.resolve()}initStorage(){return this._db.isReady()?Promise.resolve():this._db.initDatabase()}networkProbe(){this._connection.probe()}isConnected(){return this._connection.isConnected()}isAuthenticated(){return this._authenticated}authorizeURL(e){if("string"!=typeof e)return e;if(b.isRelativeURL(e)){const t="scheme://host/",s=new URL(e,t);this._apiKey&&s.searchParams.append("apikey",this._apiKey),this._authToken&&this._authToken.token&&(s.searchParams.append("auth","token"),s.searchParams.append("secret",this._authToken.token)),e=s.toString().substring(t.length-1)}return e}account(e,t,s,n,i){const r=this.initPacket("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=s,r.acc.login=n,i&&(r.acc.desc.defacs=i.defacs,r.acc.desc.public=i.public,r.acc.desc.private=i.private,r.acc.desc.trusted=i.trusted,r.acc.tags=i.tags,r.acc.cred=i.cred,r.acc.token=i.token,Array.isArray(i.attachments)&&i.attachments.length>0&&(r.extra={attachments:i.attachments.filter((e=>b.isRelativeURL(e)))})),this.send(r,r.acc.id)}createAccount(e,t,s,n){let i=this.account(USER_NEW,e,t,s,n);return s&&(i=i.then((e=>this.loginSuccessful(e)))),i}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",_(e+":"+t),!0,s)}updateAccountBasic(e,t,s,n){return t=t||"",s=s||"",this.account(e,"basic",_(t+":"+s),!1,n)}hello(){const e=this.initPacket("hi");return this.send(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()&&(this.send({hi:{dev:e||b.DEL_CHAR}}),t=!0)),t}login(e,t,s){const n=this.initPacket("login");return n.login.scheme=e,n.login.secret=t,n.login.cred=s,this.send(n,n.login.id).then((e=>this.loginSuccessful(e)))}loginBasic(e,t,s){return this.login("basic",_(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",_(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=this.initPacket("sub",e);if(e||(e=n.TOPIC_NEW),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;b.isNewGroupTopicName(e)?i.sub.set.desc=t:b.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.isRelativeURL(e)))}),s.tags&&(i.sub.set.tags=s.tags)}return this.send(i,i.sub.id)}leave(e,t){const s=this.initPacket("leave",e);return s.leave.unsub=t,this.send(s,s.leave.id)}createMessage(e,t,s){const n=this.initPacket("pub",e);let i="string"==typeof t?c.default.parse(t):t;return i&&!c.default.isPlainText(i)&&(n.pub.head={mime:c.default.getContentType()},t=i),n.pub.noecho=s,n.pub.content=t,n.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.isRelativeURL(e)))}),this.send(s,e.id)}oobNotification(e,t,s){const n=this.cacheGet("topic",e);n&&(n._updateReceived(t,s),this.getMeTopic()._refreshContact("msg",n))}getMeta(e,t){const s=this.initPacket("get",e);return s.get=(0,r.mergeObj)(s.get,t),this.send(s,s.get.id)}setMeta(e,t){const s=this.initPacket("set",e),n=[];return t&&(["desc","sub","tags","cred"].forEach((function(e){t.hasOwnProperty(e)&&(n.push(e),s.set[e]=t[e])})),Array.isArray(t.attachments)&&t.attachments.length>0&&(s.extra={attachments:t.attachments.filter((e=>b.isRelativeURL(e)))})),0==n.length?Promise.reject(new Error("Invalid {set} parameters")):this.send(s,s.set.id)}delMessages(e,t,s){const n=this.initPacket("del",e);return n.del.what="msg",n.del.delseq=t,n.del.hard=s,this.send(n,n.del.id)}delTopic(e,t){const s=this.initPacket("del",e);return s.del.what="topic",s.del.hard=t,this.send(s,s.del.id)}delSubscription(e,t){const s=this.initPacket("del",e);return s.del.what="sub",s.del.user=t,this.send(s,s.del.id)}delCredential(e,t){const s=this.initPacket("del",n.TOPIC_ME);return s.del.what="cred",s.del.cred={meth:e,val:t},this.send(s,s.del.id)}delCurrentUser(e){const t=this.initPacket("del",null);return t.del.what="user",t.del.hard=e,this.send(t,t.del.id).then((e=>{this._myUID=null}))}note(e,t,s){if(s<=0||s>=n.LOCAL_SEQID)throw new Error("Invalid message id ".concat(s));const i=this.initPacket("note",e);i.note.what=t,i.note.seq=s,this.send(i)}noteKeyPress(e){const t=this.initPacket("note",e);t.note.what="kp",this.send(t)}getTopic(e){let t=this.cacheGet("topic",e);return!t&&e&&(t=e==n.TOPIC_ME?new Re.TopicMe:e==n.TOPIC_FND?new Re.TopicFnd:new Re.Topic(e),this.attachCacheToTopic(t),t._cachePutSelf()),t}isTopicCached(e){return!!this.cacheGet("topic",e)}newGroupTopicName(e){return(e?n.TOPIC_NEW_CHAN:n.TOPIC_NEW)+this.getNextUniqueId()}getMeTopic(){return this.getTopic(n.TOPIC_ME)}getFndTopic(){return this.getTopic(n.TOPIC_FND)}getLargeFileHelper(){return new h.default(this,n.PROTOCOL_VERSION)}getCurrentUserID(){return this._myUID}isMe(e){return this._myUID===e}getCurrentLogin(){return this._login}getServerInfo(){return this._serverInfo}getServerLimit(e,t){return(this._serverInfo?this._serverInfo[e]:null)||t}enableLogging(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t}setHumanLanguage(e){e&&(this._humanLanguage=e)}isTopicOnline(e){const t=this.cacheGet("topic",e);return t&&t.online}getTopicAccessMode(e){const t=this.cacheGet("topic",e);return t?t.acs:null}wantAkn(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0}}je.default=b,b.MESSAGE_STATUS_NONE=n.MESSAGE_STATUS_NONE,b.MESSAGE_STATUS_QUEUED=n.MESSAGE_STATUS_QUEUED,b.MESSAGE_STATUS_SENDING=n.MESSAGE_STATUS_SENDING,b.MESSAGE_STATUS_FAILED=n.MESSAGE_STATUS_FAILED,b.MESSAGE_STATUS_SENT=n.MESSAGE_STATUS_SENT,b.MESSAGE_STATUS_RECEIVED=n.MESSAGE_STATUS_RECEIVED,b.MESSAGE_STATUS_READ=n.MESSAGE_STATUS_READ,b.MESSAGE_STATUS_TO_ME=n.MESSAGE_STATUS_TO_ME,b.MESSAGE_STATUS_DEL_RANGE=n.MESSAGE_STATUS_DEL_RANGE,b.DEL_CHAR=n.DEL_CHAR,b.MAX_MESSAGE_SIZE="maxMessageSize",b.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",b.MAX_TAG_COUNT="maxTagCount",b.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize"}).call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),je}));