!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={exports:({},function(e,t){let n=[];function s(t,n,s){let i=0,r=n.length-1,o=0,a=0,c=!1;for(;i<=r;)if((a=e(n[o=(i+r)/2|0],t))<0)i=o+1;else{if(!(a>0)){c=!0;break}r=o-1}return c?{idx:o,exact:!0}:s?{idx:-1}:{idx:a<0?o+1:o}}function i(e,n){const i=s(e,n,!1),r=i.exact&&t?1:0;return n.splice(i.idx,r,e),n}return e=e||function(e,t){return e===t?0:e0?n[n.length-1]:void 0},put:function(){let e;e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;for(let t in e)i(e[t],n)},delAt:function(e){let t=n.splice(e,1);if(t&&t.length>0)return t[0]},delRange:function(e,t){return n.splice(e,t-e)},length:function(){return n.length},reset:function(){n=[]},forEach:function(e,t,s,i){t|=0,s=s||n.length;for(let r=t;r{this.logger&&this.logger(e,...t)};function _(){clearTimeout(p);const e=Math.pow(2,f)*(1+.3*Math.random())*2e3;f=f>=10?f:f+1,this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),p=setTimeout((()=>{if(m(`Reconnecting, iter=${f}, timeout=${e}`),g)this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch((()=>{}))}}),e)}function b(){clearTimeout(p),p=null}function w(e){let t=null;e.connect=function(s,r){if(g=!1,t){if(!r&&t.readyState==t.OPEN)return Promise.resolve();t.close(),t=null}return s&&(c=s),new Promise((function(s,r){const o=i(c,h?"wss":"ws",u,l);m("Connecting to: ",o);const a=new n(o);a.onerror=function(e){r(e)},a.onopen=function(t){d&&b(),e.onOpen&&e.onOpen(),s()},a.onclose=function(n){if(t=null,e.onDisconnect){const t=g?418:503;e.onDisconnect(new Error(g?"Disconnected by client":"Connection failed ("+t+")"),t)}!g&&d&&_.call(e)},a.onmessage=function(t){e.onMessage&&e.onMessage(t.data)},t=a}))},e.reconnect=function(t){b(),e.connect(null,t)},e.disconnect=function(){g=!0,b(),t&&(t.close(),t=null)},e.sendText=function(e){if(!t||t.readyState!=t.OPEN)throw new Error("Websocket is not connected");t.send(e)},e.isConnected=function(){return t&&t.readyState==t.OPEN},e.transport=function(){return"ws"},e.probe=function(){e.sendText("1")}}function v(e){let t=null,n=null,s=null;e.connect=function(s,r){if(g=!1,n){if(!r)return Promise.resolve();n.onreadystatechange=void 0,n.abort(),n=null}return s&&(c=s),new Promise((function(s,r){const o=i(c,h?"https":"http",u,l);m("Connecting to: ",o),(n=function n(s,i,r){let o=new XMLHttpRequest,a=!1;return o.onreadystatechange=function(c){if(4==o.readyState)if(201==o.status){let r=JSON.parse(o.responseText,jsonParseHelper);t=s+"&sid="+r.ctrl.params.sid,(o=n(t)).send(null),e.onOpen&&e.onOpen(),i&&(a=!0,i()),d&&b()}else if(o.status<400)e.onMessage&&e.onMessage(o.responseText),(o=n(t)).send(null);else{if(r&&!a&&(a=!0,r(o.responseText)),e.onMessage&&o.responseText&&e.onMessage(o.responseText),e.onDisconnect){const t=o.status||(g?418:503),n=o.responseText||(g?"Disconnected by client":"Connection failed");e.onDisconnect(new Error(n+" ("+t+")"),t)}o=null,!g&&d&&_.call(e)}},o.open("GET",s,!0),o}(o,s,r)).send(null)})).catch((e=>{m("LP connection failed:",e)}))},e.reconnect=function(t){b(),e.connect(null,t)},e.disconnect=function(){g=!0,b(),s&&(s.onreadystatechange=void 0,s.abort(),s=null),n&&(n.onreadystatechange=void 0,n.abort(),n=null),e.onDisconnect&&e.onDisconnect(new Error("Disconnected by client (418)"),418),t=null},e.sendText=function(e){if(!(s=function(e){let t=new XMLHttpRequest;return t.onreadystatechange=function(e){if(4==t.readyState&&t.status>=400)throw new Error("LP sender failed, "+t.status)},t.open("POST",e,!0),t}(t))||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(e)},e.isConnected=function(){return n&&!0},e.transport=function(){return"lp"},e.probe=function(){e.sendText("1")}}let M=!1;if("lp"===r?(v(this),M=!0):"ws"===r?(w(this),M=!0):"object"==typeof window&&(window.WebSocket?(w(this),M=!0):window.XMLHttpRequest&&(v(this),M=!0)),!M)throw m("No network transport is available. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("No network transport is available. Running under Node? Call 'Tinode.setNetworkProviders()'.");this.transportAvailable=function(e){switch(e){case"ws":return"object"==typeof window&&window.WebSocket;case"lp":return"object"==typeof window&&window.XMLHttpRequest;default:return m("Request for unknown transport",e),!1}},this.backoffReset=function(){f=0},this.onMessage=void 0,this.onDisconnect=void 0,this.onOpen=void 0,this.onAutoreconnectIteration=void 0,this.logger=void 0};r.setNetworkProviders=function(e,t){n=e,s=t},r.NETWORK_ERROR=503,r.NETWORK_ERROR_TEXT="Connection failed",r.NETWORK_USER=418,r.NETWORK_USER_TEXT="Disconnected by client",t.exports=r}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),t=t.exports;var n={exports:({},function(e,t){e=e||function(){},t=t||function(){};let n=null,s=!1;const i=["created","updated","deleted","read","recv","seq","clear","defacs","creds","public","private","touched"];function r(e,t){const n=e||{};return["topic","seq","ts","_status","from","head","content"].forEach((e=>{t.hasOwnProperty(e)&&(n[e]=t[e])})),n}return{initDatabase:function(){return new Promise(((s,i)=>{const r=indexedDB.open("tinode-web",1);r.onsuccess=e=>{n=e.target.result,s(n)},r.onerror=n=>{t("PCache","failed to initialize",n),i(n.target.error),e&&e(n.target.error)},r.onupgradeneeded=function(s){(n=s.target.result).onerror=function(n){t("PCache","failed to create storage",n),e&&e(n.target.error)},n.createObjectStore("topic",{keyPath:"name"}),n.createObjectStore("user",{keyPath:"uid"}),n.createObjectStore("subscription",{keyPath:["topic","uid"]}),n.createObjectStore("message",{keyPath:["topic","seq"]})}}))},deleteDatabase:function(){return new Promise(((e,n)=>{const s=indexedDB.deleteDatabase("tinode-web");s.onsuccess=function(t){e(!0)},s.onerror=function(e){t("PCache","deleteDatabase",e.target.error),n(e.target.error)}}))},isReady:function(){return!!n},disable:function(){n=null,s=!0},updTopic:function(e){return this.isReady()?new Promise(((s,r)=>{const o=n.transaction(["topic"],"readwrite");o.oncomplete=e=>{s(e.target.result)},o.onerror=e=>{t("PCache","updTopic",e.target.error),r(e.target.error)};const a=o.objectStore("topic").get(e.name);a.onsuccess=t=>{o.objectStore("topic").put(function(e,t){const n=e||{name:t.name};return i.forEach((e=>{t.hasOwnProperty(e)&&(n[e]=t[e])})),Array.isArray(t._tags)&&(n.tags=t._tags),t.acs&&(n.acs=t.getAccessMode().jsonHelper()),n}(a.result,e)),o.commit()}})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},remTopic:function(e){return this.isReady()?new Promise(((s,i)=>{const r=n.transaction(["topic","subscription","message"],"readwrite");r.oncomplete=e=>{s(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()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},mapTopics:function(e,i){return this.isReady()?new Promise(((s,r)=>{const o=n.transaction(["topic"]);o.onerror=e=>{t("PCache","mapTopics",e.target.error),r(e.target.error)},o.objectStore("topic").getAll().onsuccess=t=>{e&&t.target.result.forEach((t=>{e.call(i,t)})),s(t.target.result)}})):s?Promise.resolve([]):Promise.reject(new Error("not initialized"))},deserializeTopic:function(e,t){!function(e,t){i.forEach((n=>{t.hasOwnProperty(n)&&(e[n]=t[n])})),Array.isArray(t.tags)&&(e._tags=t.tags),t.acs&&e.setAccessMode(t.acs)}(e,t)},updUser:function(e,i){if(!(arguments.length<2||void 0===i))return this.isReady()?new Promise(((s,r)=>{const o=n.transaction(["user"],"readwrite");o.oncomplete=e=>{s(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()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},remUser:function(e){return this.isReady()?new Promise(((s,i)=>{const r=n.transaction(["user"],"readwrite");r.oncomplete=e=>{s(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()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},getUser:function(e){return this.isReady()?new Promise(((s,i)=>{const r=n.transaction(["user"]);r.oncomplete=e=>{const t=e.target.result;s({user:t.uid,public:t.public})},r.onerror=e=>{t("PCache","getUser",e.target.error),i(e.target.error)},r.objectStore("user").get(e)})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},updSubscription:function(e,i,r){return this.isReady()?new Promise(((s,o)=>{const a=n.transaction(["subscription"],"readwrite");a.oncomplete=e=>{s(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,n,s){const i=e||{topic:t,uid:n};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach((e=>{s.hasOwnProperty(e)&&(i[e]=s[e])})),i}(t.target.result,e,i,r)),a.commit()}})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},mapSubscriptions:function(e,i,r){return this.isReady()?new Promise(((s,o)=>{const a=n.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)})),s(e.target.result)}})):s?Promise.resolve([]):Promise.reject(new Error("not initialized"))},addMessage:function(e){return this.isReady()?new Promise(((s,i)=>{const o=n.transaction(["message"],"readwrite");o.onsuccess=e=>{s(e.target.result)},o.onerror=e=>{t("PCache","addMesssage",e.target.error),i(e.target.error)},o.objectStore("message").add(r(null,e)),o.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},updMessageStatus:function(e,i,o){return this.isReady()?new Promise(((s,a)=>{const c=n.transaction(["message"],"readwrite");c.onsuccess=e=>{s(e.target.result)},c.onerror=e=>{t("PCache","updMessageStatus",e.target.error),a(e.target.error)};const u=c.objectStore("message").get(IDBKeyRange.only([e,i]));u.onsuccess=t=>{const n=u.result||t.target.result;n&&n._status!=o?(c.objectStore("message").put(r(n,{topic:e,seq:i,_status:o})),c.commit()):c.commit()}})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},remMessages:function(e,i,r){return this.isReady()?new Promise(((s,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=n.transaction(["message"],"readwrite");c.onsuccess=e=>{s(e.target.result)},c.onerror=e=>{t("PCache","remMessages",e.target.error),o(e.target.error)},c.objectStore("message").delete(a),c.commit()})):s?Promise.resolve():Promise.reject(new Error("not initialized"))},readMessages:function(e,i,r,o){return this.isReady()?new Promise(((s,a)=>{const c=(i=i||{}).from>0?i.from:0,u=i.to>0?i.to:Number.MAX_SAFE_INTEGER,h=0|i.limit,l=[],d=IDBKeyRange.bound([e,c],[e,u],!1,!0),p=n.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),h<=0||l.length"},close:function(){return""}},EM:{open:function(){return""},close:function(){return""}},DL:{open:function(){return""},close:function(){return""}},CO:{open:function(){return""},close:function(){return""}},BR:{open:function(){return"
"},close:function(){return""}},HD:{open:function(){return""},close:function(){return""}},HL:{open:function(){return''},close:function(){return""}},LN:{open:function(e){return''},close:function(e){return""},props:function(e){return e?{href:e.url,target:"_blank"}:null}},MN:{open:function(e){return''},close:function(e){return""},props:function(e){return e?{name:e.val}:null}},HT:{open:function(e){return''},close:function(e){return""},props:function(e){return e?{name:e.val}:null}},BN:{open:function(e){return""},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=c(e._tempPreview,e.mime),n=a(e.val,e.mime,h.logger),s=e.ref||n;return(e.name?'':"")+''},close:function(e){return e.name?"":""},props:function(e){return e?{src:c(e._tempPreview,e.mime)||e.ref||a(e.val,e.mime,h.logger),title: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"
"},close:function(e){return"
"}},RW:{open:function(e){return"
"},close:function(e){return"
"}}},h=function(){};h.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),n=[],s={},o=[];t.map((function(e){let t,a,c=[];if(i.map((function(t){c=c.concat(function(e,t,n,s){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 u=n?n.exec(o):null;if(null==u)break;let h=u.index+u[0].indexOf(u[1]);o=o.slice(h+1),r=(h+=r)+1,i.push({text:e.slice(c+1,h),children:[],start:c,end:h,type:s})}return i}(e,t.start,t.end,t.name))})),0==c.length)a={txt:e};else{c.sort((function(e,t){return e.start-t.start})),c=function e(t){if(0==t.length)return[];const n=[t[0]];let s=t[0];for(let e=1;es.end?(n.push(t[e]),s=t[e]):t[e].endn&&r.push({text:t.slice(n,o.start)});const a={type:o.type},c=e(t,o.start+1,o.end,o.children);c.length>0?a.children=c:a.text=o.text,r.push(a),n=o.end+1}return ns;return s=e.offset+e.len,t}))}(a.txt)).length>0){const e=[];for(let i in t){const r=t[i];let o=s[r.unique];o||(o=n.length,s[r.unique]=o,n.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:o})}a.ent=e}o.push(a)}));const a={txt:""};if(o.length>0){a.txt=o[0].txt,a.fmt=(o[0].fmt||[]).concat(o[0].ent||[]);for(let e=1;e0&&(a.ent=n)}return a},h.init=function(e){return"string"!=typeof e?null:{txt:e}},h.append=function(e,t){if(null==e)return t;if(null==t)return e;e.txt=e.txt||"",t.txt=t.txt||"";const n=e.txt.length;return e.txt+=t.txt,Array.isArray(t.fmt)&&(e.fmt=e.fmt||[],Array.isArray(t.ent)&&(e.ent=e.ent||[]),t.fmt.forEach((s=>{const i={at:s.at+n,len:s.len};s.tp?i.tp=s.tp:(i.key=e.ent.length,e.ent.push(t.ent[s.key||0])),e.fmt.push(i)}))),e},h.insertImage=function(e,t,n){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:1,key:e.ent.length});const s={tp:"IM",data:{mime:n.mime,val:n.preview,width:n.width,height:n.height,name:n.filename,size:0|n.size,ref:n.refurl}};return n.urlPromise&&(s.data._tempPreview=n._tempPreview,s.data._processing=!0,n.urlPromise.then((e=>{s.data.ref=e,s.data._tempPreview=void 0,s.data._processing=void 0}),(e=>{s.data._processing=void 0}))),e.ent.push(s),e},h.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",h.insertImage(e,e.txt.length-1,t)},h.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 n={tp:"EX",data:{mime:t.mime,val:t.data,name:t.filename,ref:t.refurl,size:0|t.size}};return t.urlPromise&&(n.data._processing=!0,t.urlPromise.then((e=>{n.data.ref=e,n.data._processing=void 0}),(e=>{n.data._processing=void 0}))),e.ent.push(n),e},h.wrapAsForm=function(e,t,n){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:t,len:n,tp:"FM"}),e},h.insertButton=function(e,t,n,s,i,r,o){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length{let t,n=e.tp;return n||(e.key=e.key||0,r[e.key]&&(t=r[e.key].data,n=r[e.key].tp)),{tp:n=n||"HD",data:t,at:e.at,len:e.len}})),function e(t,n,s,i,r,a){const c=[];for(let s=0;s0)for(let t in e.ent)if(e.ent[t]&&"EX"==e.ent[t].tp)return!0;return!1},h.attachments=function(e,t,n){if(e.ent&&e.ent.length>0)for(let s in e.ent)e.ent[s]&&"EX"==e.ent[s].tp&&t.call(n,e.ent[s].data,s)},h.getDownloadUrl=function(e){let t=null;return"application/json"!=e.mime&&e.val?t=a(e.val,e.mime,h.logger):"string"==typeof e.ref&&(t=e.ref),t},h.isProcessing=function(e){return!!e._processing},h.getPreviewUrl=function(e){return e.val?a(e.val,e.mime,h.logger):null},h.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},h.getEntityMimeType=function(e){return e.mime||"text/plain"},h.tagName=function(e){return e?o[e]?o[e].name:"_UNKN":void 0},h.attrValue=function(e,t){if(t&&u[e])return u[e].props(t)},h.getContentType=function(){return"text/x-drafty"},h.preview=function(e,t){if(!e||t<=0||"object"!=typeof e)return null;const{txt:n,fmt:s,ent:i}=e,r={txt:""};let o=0;if("string"==typeof n&&(n.length>t?r.txt=n.substr(0,t):r.txt=n,o=r.txt.length),Array.isArray(s)&&s.length>0){const e=[];let t=0,n=0;if(s.forEach((s=>{if(s.at0&&(r.ent=[]);let a=0;s.forEach((t=>{if(t.ats&&"number"==typeof e[s]))return;n.key=e[s],r.ent[n.key]=function(e){let t={tp:e.tp};if(e.data&&0!=Object.entries(e.data).length){const n={};["mime","name","width","height","size"].forEach((t=>{const s=e.data[t];s&&(n[t]=s)})),0!=Object.entries(n).length&&(t.data=n)}return t}(i[s])}r.fmt[a++]=n}}))}return r},s.exports=h,s=s.exports;var l={exports:{}};return function(i){(function(){"use strict";let r,o;"undefined"!=typeof WebSocket&&(r=WebSocket),"undefined"!=typeof XMLHttpRequest&&(o=XMLHttpRequest),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(i.btoa=function(t=""){let n=t,s="";for(let t,i=0,r=0,o=e;n.charAt(0|r)||(o="=",r%1);s+=o.charAt(63&i>>8-r%1*8)){if((t=n.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 s}),"undefined"==typeof atob&&(i.atob=function(t=""){let n=t.replace(/=+$/,""),s="";if(n.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=n.charAt(o++);~t&&(r=i%4?64*r+t:t,i++%4)?s+=String.fromCharCode(255&r>>(-2*i&6)):0)t=e.indexOf(t);return s}),"undefined"==typeof window&&(i.window={WebSocket:r,XMLHttpRequest:o,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}}),t.setNetworkProviders(r,o)}();const a="0.17.0-beta1",c="tinodejs/"+a;function u(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode("0x"+t)})))}function h(e,t,n){if("object"!=typeof t){if(t===m.DEL_CHAR)return;return void 0===t?e:t}if(null===t)return t;if(t instanceof Date)return e&&e instanceof Date&&!(e=20&&t.length<=24){let e=new Date(t);if(e)return e}else if("acs"===e&&"object"==typeof t)return new b(t);return t}function g(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=function(e){if(!e||0==e.getTime())return;function t(e,t){return"0".repeat((t=t||2)-(""+e).length)+e}const n=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+(n?"."+t(n,3):"")+"Z"}(t);else if(t instanceof b)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)}var m=function(e,i){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 n="";/reactnative/i.test(t)&&(n="ReactNative; ");let s,i=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(i){let t=["chrome","safari","mobile","version"],n=e.substr(i.index+i[0].length).split(" "),r=[];for(let e=0;e0?r[0][0]+"/"+r[0][1]:i[1]}else s=/trident/i.test(e)?(i=/(?:\brv[ :]+([.\d]+))|(?:\bMSIE ([.\d]+))/g.exec(e))?"MSIE/"+(i[1]||i[2]):"MSIE/?":/firefox/i.test(e)?(i=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+i[1]:"Firefox/?":/presto/i.test(e)?(i=/Opera\/([.\d]+)/g.exec(e))?"Opera/"+i[1]:"Opera/?":(i=/([\w.]+)\/([.\d]+)/.exec(e))?i[1]+"/"+i[2]:(i=e.split(" "))[0];if((i=s.split("/")).length>1){let e=i[1].split(".");s=i[0]+"/"+e[0]+(e[1]?"."+e[1]:"")}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._connection=new t(e.host,"0",e.apiKey,e.transport,e.secure,!0),this.logger=(e,...t)=>{if(this._loggingEnabled){const n=new Date,s=("0"+n.getUTCHours()).slice(-2)+":"+("0"+n.getUTCMinutes()).slice(-2)+":"+("0"+n.getUTCSeconds()).slice(-2)+"."+("00"+n.getUTCMilliseconds()).slice(-3);console.log("["+s+"]",e,t.join(" "))}},this._connection.logger=this.logger,s.logger=this.logger,this._lastTopicUpdate=null,this._cache={};const r=this.cachePut=(e,t,n)=>{this._cache[e+":"+t]=n},o=this.cacheGet=(e,t)=>this._cache[e+":"+t],u=this.cacheDel=(e,t)=>{delete this._cache[e+":"+t]},l=this.cacheMap=(e,t,n)=>{const s=e?e+":":void 0;for(let e in this._cache)if((!s||0==e.indexOf(s))&&t.call(n,this._cache[e],e))break};this.attachCacheToTopic=e=>{e._tinode=this,e._cacheGetUser=e=>{const t=o("user",e);if(t)return{user:e,public:h({},t)}},e._cachePutUser=(e,t)=>r("user",e,h({},t.public)),e._cacheDelUser=e=>u("user",e),e._cachePutSelf=()=>(e.updated&&e.updated>this._lastTopicUpdate&&(this._lastTopicUpdate=e.updated),r("topic",e.name,e)),e._cacheDelSelf=()=>u("topic",e.name)},this._persist=e.persist,this._db=n((e=>{this.logger("DB",e)}),this.logger),this._persist?this._db.initDatabase().then((()=>{const e=[];return this._db.mapTopics((t=>{let n=this.cacheGet("topic",t.name);n||(n="me"==t.name?new v:"fnd"==t.name?new M:new w(t.name),this._db.deserializeTopic(n,t),this.attachCacheToTopic(n),n._cachePutSelf(),e.push(n._loadMessages(this._db)))})).then((()=>Promise.all(e))).then((()=>{i&&i(),this.logger("Persistent cache initialized.")}))})):this._db.disable();const d=(e,t,n,s)=>{const i=this._pendingPromises[e];i&&(delete this._pendingPromises[e],t>=200&&t<400?i.resolve&&i.resolve(n):i.reject&&i.reject(new Error(`${s} (${t})`)))},p=e=>{let t=null;return e&&(t=new Promise(((t,n)=>{this._pendingPromises[e]={resolve:t,reject:n,ts:new Date}}))),t},m=this.getNextUniqueId=()=>0!=this._messageId?""+this._messageId++:void 0,_=()=>this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+c;this.initPacket=(e,t)=>{switch(e){case"hi":return{hi:{id:m(),ver:a,ua:_(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:m(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:m(),scheme:null,secret:null}};case"sub":return{sub:{id:m(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:m(),topic:t,unsub:!1}};case"pub":return{pub:{id:m(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:m(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:m(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:m(),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)}},this.send=(e,n)=>{let s;n&&(s=p(n)),e=function e(t){return Object.keys(t).forEach((function(n){"_"==n[0]?delete t[n]:t[n]?Array.isArray(t[n])&&0==t[n].length?delete t[n]:t[n]?"object"!=typeof t[n]||t[n]instanceof Date||(e(t[n]),0==Object.getOwnPropertyNames(t[n]).length&&delete t[n]):delete t[n]:delete t[n]})),t}(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,g):i));try{this._connection.sendText(i)}catch(e){if(!n)throw e;d(n,t.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:new Date(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,f);t?(this.logger("in: "+(this._trimLongStrings?JSON.stringify(t,g):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&d(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout((()=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=o("topic",t.ctrl.topic);e&&(e._resetSub(),t.ctrl.params&&t.ctrl.params.unsub&&e._gone())}else if(t.ctrl.params&&"data"==t.ctrl.params.what){const e=o("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if(t.ctrl.params&&"sub"==t.ctrl.params.what){const e=o("topic",t.ctrl.topic);e&&e._processMetaSub([])}}),0)):setTimeout((()=>{if(t.meta){const e=o("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&d(t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=o("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=o("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=o("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()-5e3);for(let n in this._pendingPromises){let s=this._pendingPromises[n];s&&s.ts{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 n=this._pendingPromises[t];n&&n.reject&&n.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}};m.credential=function(e,t,n,s){return"object"==typeof e&&({val:t,params:n,resp:s,meth:e}=e),e&&(t||s)?[{meth:e,val:t,resp:s,params:n}]:null},m.topicType=function(e){return{me:"me",fnd:"fnd",grp:"grp",new:"grp",nch:"grp",chn:"grp",usr:"p2p",sys:"sys"}["string"==typeof e?e.substring(0,3):"xxx"]},m.isMeTopicName=function(e){return"me"==m.topicType(e)},m.isGroupTopicName=function(e){return"grp"==m.topicType(e)},m.isP2PTopicName=function(e){return"p2p"==m.topicType(e)},m.isCommTopicName=function(e){return m.isP2PTopicName(e)||m.isGroupTopicName(e)},m.isNewGroupTopicName=function(e){return"string"==typeof e&&("new"==e.substring(0,3)||"nch"==e.substring(0,3))},m.isChannelTopicName=function(e){return"string"==typeof e&&("chn"==e.substring(0,3)||"nch"==e.substring(0,3))},m.getVersion=function(){return a},m.setNetworkProviders=function(e,t){r=e,o=t},m.getLibrary=function(){return c},m.MESSAGE_STATUS_NONE=0,m.MESSAGE_STATUS_QUEUED=1,m.MESSAGE_STATUS_SENDING=2,m.MESSAGE_STATUS_FAILED=3,m.MESSAGE_STATUS_SENT=4,m.MESSAGE_STATUS_RECEIVED=5,m.MESSAGE_STATUS_READ=6,m.MESSAGE_STATUS_TO_ME=7,m.DEL_CHAR="␡",m.isNullValue=function(e){return e===m.DEL_CHAR},m.isRelativeURL=function(e){return!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)},m.MAX_MESSAGE_SIZE="maxMessageSize",m.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",m.MAX_TAG_COUNT="maxTagCount",m.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",m.prototype={connect:function(e){return this._connection.connect(e)},reconnect:function(e){this._connection.reconnect(e)},disconnect:function(){this._connection.disconnect()},clearStorage:function(){this._db&&this._db.deleteDatabase()},networkProbe:function(){this._connection.probe()},isConnected:function(){return this._connection.isConnected()},isAuthenticated:function(){return this._authenticated},authorizeURL:function(e){if(!e)return e;if(m.isRelativeURL(e)){const t="scheme://host/",n=new URL(e,t);this._apiKey&&n.searchParams.append("apikey",this._apiKey),this._authToken.token&&(n.searchParams.append("auth","token"),n.searchParams.append("secret",this._authToken.token)),e=n.toString().substring(t.length-1)}return e},account:function(e,t,n,s,i){const r=this.initPacket("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=n,r.acc.login=s,i&&(r.acc.desc.defacs=i.defacs,r.acc.desc.public=i.public,r.acc.desc.private=i.private,r.acc.tags=i.tags,r.acc.cred=i.cred,r.acc.token=i.token),this.send(r,r.acc.id)},createAccount:function(e,t,n,s){let i=this.account("new",e,t,n,s);return n&&(i=i.then((e=>this.loginSuccessful(e)))),i},createAccountBasic:function(e,t,n){return e=e||"",t=t||"",this.createAccount("basic",u(e+":"+t),!0,n)},updateAccountBasic:function(e,t,n,s){return t=t||"",n=n||"",this.account(e,"basic",u(t+":"+n),!1,s)},hello:function(){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:function(e){let t=!1;return(e=e||null)!=this._deviceToken&&(this._deviceToken=e,this.isConnected()&&this.isAuthenticated()&&(this.send({hi:{dev:e||m.DEL_CHAR}}),t=!0)),t},login:function(e,t,n){const s=this.initPacket("login");return s.login.scheme=e,s.login.secret=t,s.login.cred=n,this.send(s,s.login.id).then((e=>this.loginSuccessful(e)))},loginBasic:function(e,t,n){return this.login("basic",u(e+":"+t),n).then((t=>(this._login=e,t)))},loginToken:function(e,t){return this.login("token",e,t)},requestResetAuthSecret:function(e,t,n){return this.login("reset",u(e+":"+t+":"+n))},getAuthToken:function(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)},setAuthToken:function(e){this._authToken=e},subscribe:function(e,t,n){const s=this.initPacket("sub",e);return e||(e="new"),s.sub.get=t,n&&(n.sub&&(s.sub.set.sub=n.sub),n.desc&&(m.isNewGroupTopicName(e)?s.sub.set.desc=n.desc:m.isP2PTopicName(e)&&n.desc.defacs&&(s.sub.set.desc={defacs:n.desc.defacs})),n.tags&&(s.sub.set.tags=n.tags)),this.send(s,s.sub.id)},leave:function(e,t){const n=this.initPacket("leave",e);return n.leave.unsub=t,this.send(n,n.leave.id)},createMessage:function(e,t,n){const i=this.initPacket("pub",e);let r="string"==typeof t?s.parse(t):t;return r&&!s.isPlainText(r)&&(i.pub.head={mime:s.getContentType()},t=r),i.pub.noecho=n,i.pub.content=t,i.pub},publish:function(e,t,n){return this.publishMessage(this.createMessage(e,t,n))},publishMessage:function(e){return(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0,this.send({pub:e},e.id)},getMeta:function(e,t){const n=this.initPacket("get",e);return n.get=h(n.get,t),this.send(n,n.get.id)},setMeta:function(e,t){const n=this.initPacket("set",e),s=[];return t&&["desc","sub","tags","cred"].map((function(e){t.hasOwnProperty(e)&&(s.push(e),n.set[e]=t[e])})),0==s.length?Promise.reject(new Error("Invalid {set} parameters")):this.send(n,n.set.id)},delMessages:function(e,t,n){const s=this.initPacket("del",e);return s.del.what="msg",s.del.delseq=t,s.del.hard=n,this.send(s,s.del.id)},delTopic:function(e,t){const n=this.initPacket("del",e);return n.del.what="topic",n.del.hard=t,this.send(n,n.del.id)},delSubscription:function(e,t){const n=this.initPacket("del",e);return n.del.what="sub",n.del.user=t,this.send(n,n.del.id)},delCredential:function(e,t){const n=this.initPacket("del","me");return n.del.what="cred",n.del.cred={meth:e,val:t},this.send(n,n.del.id)},delCurrentUser:function(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:function(e,t,n){if(n<=0||n>=268435455)throw new Error("Invalid message id "+n);const s=this.initPacket("note",e);s.note.what=t,s.note.seq=n,this.send(s)},noteKeyPress:function(e){const t=this.initPacket("note",e);t.note.what="kp",this.send(t)},getTopic:function(e){let t=this.cacheGet("topic",e);return!t&&e&&(t="me"==e?new v:"fnd"==e?new M:new w(e),this._db.updTopic(t),this.attachCacheToTopic(t),t._cachePutSelf()),t},isTopicCached:function(e){return!!this.cacheGet("topic",e)},newGroupTopicName:function(e){return(e?"nch":"new")+this.getNextUniqueId()},getMeTopic:function(){return this.getTopic("me")},getFndTopic:function(){return this.getTopic("fnd")},getLargeFileHelper:function(){return new S(this)},getCurrentUserID:function(){return this._myUID},isMe:function(e){return this._myUID===e},getCurrentLogin:function(){return this._login},getServerInfo:function(){return this._serverInfo},getServerLimit:function(e,t){return(this._serverInfo?this._serverInfo[e]:null)||t},enableLogging:function(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t},setHumanLanguage:function(e){e&&(this._humanLanguage=e)},isTopicOnline:function(e){const t=this.cacheGet("topic",e);return t&&t.online},getTopicAccessMode:function(e){const t=this.cacheGet("topic",e);return t?t.acs:null},wantAkn:function(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0},onWebsocketOpen:void 0,onConnect:void 0,onDisconnect:void 0,onLogin:void 0,onCtrlMessage:void 0,onDataMessage:void 0,onPresMessage:void 0,onMessage:void 0,onRawMessage:void 0,onNetworkProbe:void 0,onAutoreconnectIteration:void 0};var _=function(e){this.topic=e,this.what={}};_.prototype={_get_desc_ims:function(){const e=this.topic._lastDescUpdate||0;return this.topic.updated>e?this.topic.updated:e},_get_subs_ims:function(){if(this.topic.isP2PType())return this._get_desc_ims();if(this.topic.isMeType()){const e=this.topic._tinode._lastTopicUpdate||0;if(e>this.topic._lastSubsUpdate)return e}return this.topic._lastSubsUpdate},withData:function(e,t,n){return this.what.data={since:e,before:t,limit:n},this},withLaterData:function(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)},withEarlierData:function(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)},withDesc:function(e){return this.what.desc={ims:e},this},withLaterDesc:function(){return this.withDesc(this._get_desc_ims())},withSub:function(e,t,n){const s={ims:e,limit:t};return"me"==this.topic.getType()?s.topic=n:s.user=n,this.what.sub=s,this},withOneSub:function(e,t){return this.withSub(e,void 0,t)},withLaterOneSub:function(e){return this.withOneSub(this.topic._lastSubsUpdate,e)},withLaterSub:function(e){return this.withSub(this._get_subs_ims(),e)},withTags:function(){return this.what.tags=!0,this},withCred:function(){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:function(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this},withLaterDel:function(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)},build:function(){const e=[],t=this;let n={};return["data","sub","desc","tags","cred","del"].map((function(s){t.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(t.what[s]).length>0&&(n[s]=t.what[s]))})),e.length>0?n.what=e.join(" "):n=void 0,n}};var b=function(e){e&&(this.given="number"==typeof e.given?e.given:b.decode(e.given),this.want="number"==typeof e.want?e.want:b.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:b.decode(e.mode):this.given&this.want)};b._NONE=0,b._JOIN=1,b._READ=2,b._WRITE=4,b._PRES=8,b._APPROVE=16,b._SHARE=32,b._DELETE=64,b._OWNER=128,b._BITMASK=b._JOIN|b._READ|b._WRITE|b._PRES|b._APPROVE|b._SHARE|b._DELETE|b._OWNER,b._INVALID=1048576,b._checkFlag=function(e,t,n){if(["given","want","mode"].includes(t=t||"mode"))return 0!=(e[t]&n);throw new Error(`Invalid AccessMode component '${t}'`)},b.decode=function(e){if(!e)return null;if("number"==typeof e)return e&b._BITMASK;if("N"===e||"n"===e)return b._NONE;const t={J:b._JOIN,R:b._READ,W:b._WRITE,P:b._PRES,A:b._APPROVE,S:b._SHARE,D:b._DELETE,O:b._OWNER};let n=b._NONE;for(let s=0;s{if(e.code>=300)return e;if(this._subscribed=!0,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(this._new=!1,this.name=e.topic,this.created=e.ts,this.updated=e.ts,this._cachePutSelf(),"me"!=this.name&&"fnd"!=this.name){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:function(e,t){return this._tinode.createMessage(this.name,e,t)},publish:function(e,t){return this.publishMessage(this.createMessage(e,t))},publishMessage:function(e){if(!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));if(s.hasAttachments(e.content)&&!e.head.attachments){let t=[];s.attachments(e.content,(e=>{t.push(e.ref)})),e.head.attachments=t}return e._sending=!0,e._failed=!1,this._tinode.publishMessage(e).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:function(e,t){if(!t&&!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));const n=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=n,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:function(e){return this._subscribed||e?this._tinode.leave(this.name,e).then((t=>(this._resetSub(),e&&(this._tinode._db.remTopic(this.name),this._tinode.cacheDel("topic",this.name),this._gone()),t))):Promise.reject(new Error("Cannot leave inactive topic"))},getMeta:function(e){return this._tinode.getMeta(this.name,e)},getMessagesPage:function(e,t){const n=this.startMetaQuery();t?n.withLaterData(e):n.withEarlierData(e);let s=this.getMeta(n.build());return t||(s=s.then((e=>{e&&e.params&&!e.params.count&&(this._noEarlierMsgs=!0)}))),s},setMeta:function(e){return e.tags&&(e.tags=function(e){let t=[];if(Array.isArray(e)){for(let n=0,s=e.length;n1&&t.push(s)}t.sort().filter((function(e,t,n){return!t||e!=n[t-1]}))}return 0==t.length&&t.push(m.DEL_CHAR),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:function(e,t){const n=e?this.subscriber(e):null,s=n?n.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:s}})},invite:function(e,t){return this.setMeta({sub:{user:e,mode:t}})},archive:function(e){return this.private&&this.private.arch==e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||m.DEL_CHAR}}})},delMessages:function(e,t){if(!this._subscribed)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort(((e,t)=>e.low=t.hi)));let n,s=e.reduce(((e,t)=>(t.low<268435455&&(!t.hi||t.hi<268435455?e.push(t):e.push({low:t.low,hi:this._maxSeq+1})),e)),[]);return(n=s.length>0?this._tinode.delMessages(this.name,s,t):Promise.resolve({params:{del:0}})).then((t=>(t.params.del>this._maxDel&&(this._maxDel=t.params.del),e.map((e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low)})),this._updateDeletedRanges(),this.onData&&this.onData(),t)))},delMessagesAll:function(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)},delMessagesList:function(e,t){e.sort(((e,t)=>e-t));let n=e.reduce(((e,t)=>{if(0==e.length)e.push({low:t});else{let n=e[e.length-1];!n.hi&&t!=n.low+1||t>n.hi?e.push({low:t}):n.hi=n.hi?Math.max(n.hi,t+1):t+1}return e}),[]);return this.delMessages(n,t)},delTopic:function(e){return this._tinode.delTopic(this.name,e).then((e=>(this._resetSub(),this._gone(),e)))},delSubscription:function(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:function(e,t){if(!this._subscribed)return;const n=this._users[this._tinode.getCurrentUserID()];let s=!1;n?(!n[e]||n[e]0&&this.note("read",e)},noteKeyPress:function(){this._subscribed?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")},_updateReadRecv:function(e,t,n){let s,i=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":s=this.recv,this.recv=Math.max(this.recv,t),i=s!=this.recv;break;case"read":s=this.read,this.read=Math.max(this.read,t),i=s!=this.read;break;case"msg":s=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched0){const s=this._tinode.getCurrentUserID();for(let i in this._users){const r=this._users[i];r.user!==s&&r[e]>=t&&n++}}return n},msgReadCount:function(e){return this.msgReceiptCount("read",e)},msgRecvCount:function(e){return this.msgReceiptCount("recv",e)},msgHasMoreMessages:function(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs},isNewMessage:function(e){return this._maxSeq<=e},flushMessage:function(e){const t=this._messages.find({seq:e});if(t>=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)},swapMessageId:function(e,t){const n=this._messages.find(e),s=this._messages.length();0<=n&&n=0?this._messages.delRange(n,this._messages.find({seq:t},!0)):[]},cancelSend:function(e){const t=this._messages.find({seq:e});if(t>=0){const n=this._messages.getAt(t),s=this.msgStatus(n);if(1==s||3==s)return this._tinode._db.remMessages(this.name,e),n._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1},getType:function(){return m.topicType(this.name)},getAccessMode:function(){return this.acs},setAccessMode:function(e){return this.acs=new b(e)},getDefaultAccess:function(){return this.defacs},startMetaQuery:function(){return new _(this)},isArchived:function(){return!(!this.private||!this.private.arch)},isMeType:function(){return m.isMeTopicName(this.name)},isChannelType:function(){return m.isChannelTopicName(this.name)},isGroupType:function(){return m.isGroupTopicName(this.name)},isP2PType:function(){return m.isP2PTopicName(this.name)},isCommType:function(){return m.isCommTopicName(this.name)},msgStatus:function(e,t){let n=0;return this._tinode.isMe(e.from)?e._sending?n=2:e._failed||e._cancelled?n=3:e.seq>=268435455?n=1:this.msgReadCount(e.seq)>0?n=6:this.msgRecvCount(e.seq)>0?n=5:e.seq>0&&(n=4):n=7,t&&e._status!=n&&(e._status=n,this._tinode._db.updMessageStatus(this.name,e.seq,n)),n},_routeData:function(e){e.content&&(!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq),(e.seq0&&(this._lastSubsUpdate=e.ts,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:function(e){let t;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"acs":const n=e.src||this._tinode.getCurrentUserID();if(t=this._users[n])t.acs.updateAll(e.dacs),this._processMetaSub([{user:n,updated:new Date,acs:t.acs}]);else{const s=(new b).updateAll(e.dacs);s&&s.mode!=b._NONE&&((t=this._cacheGetUser(n))?t.acs=s:(t={user:n,acs:s},this.getMeta(this.startMetaQuery().withOneSub(void 0,n).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:function(e){if("kp"!==e.what){const t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv0&&(this._updateDeletedRanges(),this.onData&&this.onData())},_allMessagesReceived:function(e){this._updateDeletedRanges(),this.onAllMessagesReceived&&this.onAllMessagesReceived(e)},_resetSub:function(){this._subscribed=!1},_gone:function(){this._messages.reset(),this._tinode._db.remMessages(this.name),this._users={},this.acs=new b(null),this.private=null,this.public=null,this._maxSeq=0,this._minSeq=0,this._subscribed=!1;const e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:"me",src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()},_updateCachedUser:function(e,t){let n=this._cacheGetUser(e);return n=h(n||{},t),this._cachePutUser(e,n),d(this._users,e,n)},_getQueuedSeqId:function(){return this._queuedSeqId++},_updateDeletedRanges:function(){const e=[];let t=null;const n=this._messages.getAt(0);n&&this._minSeq>1&&!this._noEarlierMsgs?n.hi?(n.seq>1&&(n.seq=1),n.hi{n.seq>=268435455||(n.seq!=(t.hi||t.seq)+1?t.hi?t.hi=n.hi||n.seq:(t={seq:(t.hi||t.seq)+1,hi:n.hi||n.seq},e.push(t)):t=n)}));const s=this._messages.getLast(),i=Math.max(this.seq,this._maxSeq)||0;(i>0&&!s||s&&(s.hi||s.seq){this._messages.put(e)}))},_loadMessages:function(e){return e.readMessages(this.name,{limit:24}).then((e=>(e.forEach((e=>{e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq{e.online&&(e.online=!1,e.seen?e.seen.when=new Date:e.seen={when:new Date},this._refreshContact("off",e))})),this.onMetaDesc&&this.onMetaDesc(this)},enumerable:!0,configurable:!0},_processMetaSub:{value:function(e){let t=0;if(e.forEach((e=>{const n=e.topic;if("fnd"==n||"me"==n)return;e.updated=new Date(e.updated),e.touched=e.touched?new Date(e.touched):void 0,e.deleted=e.deleted?new Date(e.deleted):null,e.online=!!e.online;let s=null;if(e.deleted)s=e,this._tinode.cacheDel("topic",n),this._tinode._db.remTopic(n);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),e.seen&&e.seen.when&&(e.seen.when=new Date(e.seen.when)),s=h(this._tinode.getTopic(n),e),this._tinode._db.updTopic(s),m.isP2PTopicName(n)&&(this._cachePutUser(n,s),this._tinode._db.updUser(n,s.public)),!e._noForwarding){const t=this._tinode.getTopic(n);t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(s)})),this.onSubsUpdated&&t>0){const n=[];e.forEach((e=>{n.push(e.topic)})),this.onSubsUpdated(n,t)}},enumerable:!0,configurable:!0},_processMetaCreds:{value:function(e,t){1==e.length&&e[0]==m.DEL_CHAR&&(e=[]),t?e.map((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)},enumerable:!0,configurable:!0},_routePres:{value:function(e){if("term"==e.what)return void this._resetSub();if("upd"==e.what&&"me"==e.src)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?t.seen.when=new Date:t.seen={when:new Date});break;case"msg":t.touched=new Date,t.seq=0|e.seq,e.act&&!this._tinode.isMe(e.act)||(t.read=t.read?Math.max(t.read,t.seq):t.seq,t.recv=t.recv?Math.max(t.read,t.recv):t.read),t.unread=t.seq-(0|t.read);break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":t.acs?t.acs.updateAll(e.dacs):t.acs=(new b).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 b(e.dacs);if(!t||t.mode==b._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(t.mode==b._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 n=this._tinode.getTopic(e.src);n.touched=new Date,n.topic=e.src,n.online=!1,n.acs=t,this._tinode.attachCacheToTopic(n),n._cachePutSelf(),this._db.updTopic(n)}}else"tags"==e.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(e)},enumerable:!0,configurable:!0},_refreshContact:{value:function(e,t){this.onContactUpdate&&this.onContactUpdate(e,t)},enumerable:!0,configurable:!0},publish:{value:function(){return Promise.reject(new Error("Publishing to 'me' is not supported"))},enumerable:!0,configurable:!0},delCredential:{value:function(e,t){return this._subscribed?this._tinode.delCredential(e,t).then((n=>{const s=this._credentials.findIndex((n=>n.meth==e&&n.val==t));return s>-1&&this._credentials.splice(s,1),this.onCredsUpdated&&this.onCredsUpdated(this._credentials),n})):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))},enumerable:!0,configurable:!0},contacts:{value:function(e,t,n){this._tinode.cacheMap("topic",((s,i)=>{!s.isCommType()||t&&!t(s)||e.call(n,s,i)}))},enumerable:!0,configurable:!0},getContact:{value:function(e){return this._tinode.cacheGet("topic",e)},enumerable:!0,configurable:!0},getAccessMode:{value:function(e){if(e){const t=this._tinode.cacheGet("topic",e);return t?t.acs:null}return this.acs},enumerable:!0,configurable:!0},isArchived:{value:function(e){const t=this._tinode.cacheGet("topic",e);return t?!(!t.private||!t.private.arch):null},enumerable:!0,configurable:!0},getCredentials:{value:function(){return this._credentials},enumerable:!0,configurable:!0}}),v.prototype.constructor=v;var M=function(e){w.call(this,"fnd",e),this._contacts={}};M.prototype=Object.create(w.prototype,{_processMetaSub:{value:function(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let n in e){let s=e[n];const i=s.topic?s.topic:s.user;s.updated=new Date(s.updated),s.seen&&s.seen.when&&(s.seen.when=new Date(s.seen.when)),s=d(this._contacts,i,s),t++,this.onMetaSub&&this.onMetaSub(s)}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(M.prototype).setMeta.call(this,e).then((function(){Object.keys(t._contacts).length>0&&(t._contacts={},t.onSubsUpdated&&t.onSubsUpdated([]))}))},enumerable:!0,configurable:!0},contacts:{value:function(e,t){const n=e||this.onMetaSub;if(n)for(let e in this._contacts)n.call(t,this._contacts[e],e,this._contacts)},enumerable:!0,configurable:!0}}),M.prototype.constructor=M;var S=function(e){this._tinode=e,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this._msgId=e.getNextUniqueId(),this.xhr=new XMLHttpRequest,this.toResolve=null,this.toReject=null,this.onProgress=null,this.onSuccess=null,this.onFailure=null};S.prototype={uploadWithBaseUrl:function(e,t,n,s,i){if(!this._authToken)throw new Error("Must authenticate first");const r=this;let o="/v0/file/u/";if(e){if(0!=e.indexOf("http://")&&0!=e.indexOf("https://"))throw new Error(`Invalid base URL '${e}'`);o=e+o}this.xhr.open("POST",o,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token);const a=new Promise(((e,t)=>{this.toResolve=e,this.toReject=t}));this.onProgress=n,this.onSuccess=s,this.onFailure=i,this.xhr.upload.onprogress=e=>{e.lengthComputable&&r.onProgress&&r.onProgress(e.loaded/e.total)},this.xhr.onload=function(){let e;try{e=JSON.parse(this.response,f)}catch(t){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(r.toResolve&&r.toResolve(e.ctrl.params.url),r.onSuccess&&r.onSuccess(e.ctrl)):this.status>=400?(r.toReject&&r.toReject(new Error(`${e.ctrl.text} (${e.ctrl.code})`)),r.onFailure&&r.onFailure(e.ctrl)):r._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed")),r.onFailure&&r.onFailure(null)},this.xhr.onabort=function(e){r.toReject&&r.toReject(new Error("upload cancelled by user")),r.onFailure&&r.onFailure(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._msgId),this.xhr.send(e)}catch(e){this.toReject&&this.toReject(e),this.onFailure&&this.onFailure(null)}return a},upload:function(e,t,n,s){return this.uploadWithBaseUrl(void 0,e,t,n,s)},download:function(e,t,n,s,i){if(!m.isRelativeURL(e))return void(i&&i(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(i&&i("Must authenticate first"));const r=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=s,this.xhr.onprogress=function(e){r.onProgress&&r.onProgress(e.loaded)};const o=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:n})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),r.toResolve&&r.toResolve()}else if(this.status>=400&&r.toReject){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,f);r.toReject(new Error(`${e.ctrl.text} (${e.ctrl.code})`))}catch(e){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),r.toReject(e)}},e.readAsText(this.response)}},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed"))},this.xhr.onabort=function(){r.toReject&&r.toReject(null)};try{this.xhr.send()}catch(e){this.toReject&&this.toReject(e)}return o},cancel:function(){this.xhr&&this.xhr.readyState<4&&this.xhr.abort()},getId:function(){return this._msgId}};var y=function(e,t){this.status=y.STATUS_NONE,this.topic=e,this.content=t};y.STATUS_NONE=0,y.STATUS_QUEUED=1,y.STATUS_SENDING=2,y.STATUS_FAILED=3,y.STATUS_SENT=4,y.STATUS_RECEIVED=5,y.STATUS_READ=6,y.STATUS_TO_ME=7,y.prototype={toJSON:function(){},fromJSON:function(e){}},y.prototype.constructor=y,l.exports=m,l.exports.Drafty=s,l.exports.AccessMode=b}).call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),l=l.exports}));