@roeehrl/tinode-sdk 0.25.1-sqlite.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.tinode=t():e.tinode=t()}(this,function(){return function(){"use strict";var e={767:function(e){const t="text/x-drafty-fr",s=["act","height","duration","incoming","mime","name","premime","preref","preview","ref","size","state","url","val","width"],i=new Intl.Segmenter,n=[{name:"ST",start:/(?:^|[\W_])(\*)[^\s*]/,end:/[^\s*](\*)(?=$|[\W_])/},{name:"EM",start:/(?:^|\W)(_)[^\s_]/,end:/[^\s_](_)(?=$|\W)/},{name:"DL",start:/(?:^|[\W_])(~)[^\s~]/,end:/[^\s~](~)(?=$|[\W_])/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],r=["QQ"],a=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(?:(?:https?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#([\p{L}\p{N}][._\p{L}\p{N}]*[\p{L}\p{N}])/gu}],o={AU:{html_tag:"audio",md_tag:void 0,isVoid:!1},BN:{html_tag:"button",md_tag:void 0,isVoid:!1},BR:{html_tag:"br",md_tag:"\n",isVoid:!0},CO:{html_tag:"tt",md_tag:"`",isVoid:!1},DL:{html_tag:"del",md_tag:"~",isVoid:!1},EM:{html_tag:"i",md_tag:"_",isVoid:!1},EX:{html_tag:"",md_tag:void 0,isVoid:!0},FM:{html_tag:"div",md_tag:void 0,isVoid:!1},HD:{html_tag:"",md_tag:void 0,isVoid:!1},HL:{html_tag:"span",md_tag:void 0,isVoid:!1},HT:{html_tag:"a",md_tag:void 0,isVoid:!1},IM:{html_tag:"img",md_tag:void 0,isVoid:!1},LN:{html_tag:"a",md_tag:void 0,isVoid:!1},MN:{html_tag:"a",md_tag:void 0,isVoid:!1},RW:{html_tag:"div",md_tag:void 0,isVoid:!1},QQ:{html_tag:"div",md_tag:void 0,isVoid:!1},ST:{html_tag:"b",md_tag:"*",isVoid:!1},VC:{html_tag:"div",md_tag:void 0,isVoid:!1},VD:{html_tag:"video",md_tag:void 0,isVoid:!1}};function c(e,t,s){if(!e)return null;try{const s=atob(e),i=s.length,n=new ArrayBuffer(i),r=new Uint8Array(n);for(let e=0;e<i;e++)r[e]=s.charCodeAt(e);return URL.createObjectURL(new Blob([n],{type:t}))}catch(e){s&&s("Drafty: failed to convert object.",e.message)}return null}function h(e,t){return e?"data:"+(t=t||"image/jpeg")+";base64,"+e:null}const l={ST:{open:e=>"<b>",close:e=>"</b>"},EM:{open:e=>"<i>",close:e=>"</i>"},DL:{open:e=>"<del>",close:e=>"</del>"},CO:{open:e=>"<tt>",close:e=>"</tt>"},BR:{open:e=>"<br/>",close:e=>""},HD:{open:e=>"",close:e=>""},HL:{open:e=>'<span style="color:teal">',close:e=>"</span>"},LN:{open:e=>'<a href="'+e.url+'">',close:e=>"</a>",props:e=>e?{href:e.url,target:"_blank"}:null},MN:{open:e=>'<a href="#'+e.val+'">',close:e=>"</a>",props:e=>e?{id:e.val}:null},HT:{open:e=>'<a href="#'+e.val+'">',close:e=>"</a>",props:e=>e?{id:e.val}:null},BN:{open:e=>"<button>",close:e=>"</button>",props:e=>e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null},AU:{open:e=>'<audio controls src="'+(e.ref||c(e.val,e.mime,d.logger))+'">',close:e=>"</audio>",props:e=>e?{src:e.ref||c(e.val,e.mime,d.logger),"data-preload":e.ref?"metadata":"auto","data-duration":e.duration,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},IM:{open:e=>{const t=h(e._tempPreview,e.mime),s=c(e.val,e.mime,d.logger),i=e.ref||s;return(e.name?'<a href="'+i+'" download="'+e.name+'">':"")+'<img src="'+(t||s)+'"'+(e.width?' width="'+e.width+'"':"")+(e.height?' height="'+e.height+'"':"")+' border="0" />'},close:e=>e.name?"</a>":"",props:e=>e?{src:h(e._tempPreview,e.mime)||e.ref||c(e.val,e.mime,d.logger),title:e.name,alt:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.ref?0|e.size:e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}:null},FM:{open:e=>"<div>",close:e=>"</div>"},RW:{open:e=>"<div>",close:e=>"</div>"},QQ:{open:e=>"<div>",close:e=>"</div>",props:e=>e?{}:null},VC:{open:e=>"<div>",close:e=>"</div>",props:e=>e?{"data-duration":e.duration,"data-state":e.state}:{}},VD:{open:e=>{const t=h(e._tempPreview,e.mime),s=e.ref||c(e.preview,e.premime||"image/jpeg",d.logger);return'<img src="'+(t||s)+'"'+(e.width?' width="'+e.width+'"':"")+(e.height?' height="'+e.height+'"':"")+' border="0" />'},close:e=>"",props:e=>{if(!e)return null;const t=e.preref||c(e.preview,e.premime||"image/jpeg",d.logger);return{src:t,"data-src":e.ref||c(e.val,e.mime,d.logger),"data-width":e.width,"data-height":e.height,"data-preload":e.ref?"metadata":"auto","data-preview":t,"data-duration":0|e.duration,"data-name":e.name,"data-size":e.ref?0|e.size:e.val?.75*e.val.length|0:0|e.size,"data-mime":e.mime}}}},d=function(){this.txt="",this.fmt=[],this.ent=[]};function u(e,t,s,i){const n=[];if(0==i.length)return[];for(let s in i){const r=i[s];r.at>t&&n.push({txt:e.slice(t,r.at)});const a={tp:r.tp},o=u(e,r.at+1,r.end,r.children);o.length>0?a.children=o:a.txt=r.txt,n.push(a),t=r.end+1}return t<s&&n.push({txt:e.slice(t,s)}),n}function p(e){if(0==e.length)return[];const t=[e[0]];let s=e[0];for(let i=1;i<e.length;i++)e[i].at>s.end?(t.push(e[i]),s=e[i]):e[i].end<=s.end&&s.children.push(e[i]);for(let e in t)t[e].children=p(t[e].children);return t}function g(e){if(!e)return null;e="string"==typeof e?{txt:e}:e;let{txt:t,fmt:s,ent:i}=e;if(t=t||"",Array.isArray(i)||(i=[]),!Array.isArray(s)||0==s.length){if(0==i.length)return{text:t};s=[{at:0,len:0,key:0}]}const n=[],a=[];s.forEach(e=>{if(!e||"object"!=typeof e)return;if(!["undefined","number"].includes(typeof e.at))return;if(!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,r=0|e.len;if(r<0)return;let o=e.key||0;i.length>0&&("number"!=typeof o||o<0||o>=i.length)||(s<=-1?a.push({start:-1,end:0,key:o}):s+r>E(t).length||(e.tp?n.push({type:e.tp,start:s,end:s+r}):i.length>0&&"object"==typeof i[o]&&n.push({start:s,end:s+r,key:o})))}),n.sort((e,t)=>{let s=e.start-t.start;return 0!=s?s:(s=t.end-e.end,0!=s?s:r.indexOf(t.type)-r.indexOf(e.type))}),a.length>0&&n.push(...a),n.forEach(e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")});const o=E(t);let c=f({},o,0,o.length,n);return c=b(c,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}),c}function m(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 f(e,t,s,i,n){if(!n||0==n.length)return s<i&&m(e,{text:t.slice(s,i).map(e=>e.segment).join("")}),e;for(let i=0;i<n.length;i++){const r=n[i];if(r.start<0&&"EX"==r.type){m(e,{type:r.type,data:r.data,key:r.key,att:!0});continue}s<r.start&&(m(e,{text:t.slice(s,r.start).map(e=>e.segment).join("")}),s=r.start);const a=[];for(;i<n.length-1;){const e=n[i+1];if(e.start<0)break;if(!(e.start<r.end))break;if(e.end<=r.end){const t=o[e.tp]||{};(e.start<e.end||t.isVoid)&&a.push(e)}i++}m(e,f({type:r.type,data:r.data,key:r.key},t,s,r.end,a)),s=r.end}return s<i&&m(e,{text:t.slice(s,i).map(e=>e.segment).join("")}),e}function _(e,t,s){if(!t)return e;e.txt=e.txt||"";const i=E(e.txt).length;if(t.text?e.txt+=t.text:Array.isArray(t.children)&&t.children.forEach(t=>{_(e,t,s)}),t.type){const n=E(e.txt).length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];const r=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=r,e.ent[r]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:r}):e.fmt.push({at:i,len:n,key:r})}else e.fmt.push({tp:t.type,at:i,len:n})}return e}function b(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;const n=[];for(let e in i.children){let r=i.children[e];r&&(r=b(r,t,s),r&&n.push(r))}return 0==n.length?i.children=null:i.children=n,i}function w(e,t,s,i,n){if(!e)return null;i&&e.type&&i.push(e.type);let r=[];for(let s in e.children){const a=w(e.children[s],t,s,i,n);a&&r.push(a)}return 0==r.length&&(r=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(n,e.type,e.data,r,s,i)}function v(e,t,s){if(!e)return null;s&&(t-=s.length);return b(e,function(e){if(t<=-1)return null;if(e.att)return e;if(0==t)e.text=s,t=-1;else if(e.text){const i=E(e.text);i.length>t?(e.text=i.slice(0,t).map(e=>e.segment).join("")+s,t=-1):t-=i.length}return e})}function y(e,t){return b(e,e=>{const s=P(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e})}function M(e){if("BR"==e.type)e=null;else if(e.text)e.type||(e.text=e.text.trimStart(),e.text||(e=null));else if(!e.type&&e.children&&e.children.length>0){const t=M(e.children[0]);t?e.children[0]=t:(e.children.shift(),e.type||0!=e.children.length||(e=null))}return e}function x(e,t){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){const s=[],i=[];for(let n in e.children){const r=e.children[n];if(r.att){if(s.length==t)continue;if(d.isFormResponseType(r.data.mime))continue;delete r.att,delete r.children,r.text=" ",s.push(r)}else i.push(r)}e.children=i.concat(s)}return e}function T(e,t){let s="",i=[];for(let n in e){const r=e[n];if(!r.txt){const e=T(r.children,s.length+t);r.txt=e.txt,i=i.concat(e.fmt)}r.tp&&i.push({at:s.length+t,len:r.txt.length,tp:r.tp}),s+=r.txt}return{txt:s,fmt:i}}function P(e,t,i){if(e&&Object.entries(e).length>0){i=i||[];const n={};if(s.forEach(s=>{if(e[s]){if(t&&!i.includes(s)&&("string"==typeof e[s]||Array.isArray(e[s]))&&e[s].length>64)return;if("object"==typeof e[s])return;n[s]=e[s]}}),0!=Object.entries(n).length)return n}return null}function S(e){return 0==Object.keys(e??{}).length}function A(e,t,s){const n=function(e){const t=[];let s=0,i=0;for(const{segment:n}of e){for(let e=0;e<n.length;e++)t[i+e]=s;i+=n.length,s++}return t}(t=t??i.segment(s)),r=n[e.at];return{at:r,len:(e.at+e.len<=s.length?n[e.at+e.len-1]-r:e.len)+1}}function E(e){return Array.from(i.segment(e))}d.init=function(e){if(void 0===e)e="";else if("string"!=typeof e)return null;return{txt:e}},d.parse=function(e){if("string"!=typeof e)return null;const t=e.split(/\r?\n/),s=[],r={},o=[];t.forEach(e=>{let t,i,c=[];if(n.forEach(t=>{c=c.concat(function(e,t,s,i){const n=[];let r=0,a=e.slice(0);for(;a.length>0;){const o=t.exec(a);if(null==o)break;let c=o.index+o[0].lastIndexOf(o[1]);a=a.slice(c+1),c+=r,r=c+1;const h=s?s.exec(a):null;if(null==h)break;let l=h.index+h[0].indexOf(h[1]);a=a.slice(l+1),l+=r,r=l+1,n.push({txt:e.slice(c+1,l),children:[],at:c,end:l,tp:i})}return n}(e,t.start,t.end,t.name))}),0==c.length)i={txt:e};else{c.sort((e,t)=>{const s=e.at-t.at;return 0!=s?s:t.end-e.end}),c=p(c);const t=T(u(e,0,e.length,c),0);i={txt:t.txt,fmt:t.fmt}}if(t=function(e){let t,s=[];if(a.forEach(i=>{for(;null!==(t=i.re.exec(e));)s.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})}),0==s.length)return s;s.sort((e,t)=>e.offset-t.offset);let i=-1;return s=s.filter(e=>{const t=e.offset>i;return i=e.offset+e.len,t}),s}(i.txt),t.length>0){const e=[];for(let i in t){const n=t[i];let a=r[n.unique];a||(a=s.length,r[n.unique]=a,s.push({tp:n.type,data:n.data})),e.push({at:n.offset,len:n.len,key:a})}i.ent=e}o.push(i)});const c={txt:""};if(o.length>0){if(c.txt=o[0].txt,c.fmt=(o[0].fmt||[]).concat(o[0].ent||[]),c.fmt.length){const e=i.segment(c.txt);for(const t of c.fmt)({at:t.at,len:t.len}=A(t,e,c.txt))}for(let e=1;e<o.length;e++){const t=o[e],s=E(c.txt).length+1;c.fmt.push({tp:"BR",len:1,at:s-1});let n={};c.txt+=" "+t.txt,t.fmt&&(n=i.segment(t.txt),c.fmt=c.fmt.concat(t.fmt.map(e=>{const{at:i,len:r}=A(e,n,t.txt);return e.at=i+s,e.len=r,e}))),t.ent&&(S(n)&&(n=i.segment(t.txt)),c.fmt=c.fmt.concat(t.ent.map(e=>{const{at:i,len:r}=A(e,n,t.txt);return e.at=i+s,e.len=r,e})))}0==c.fmt.length&&delete c.fmt,s.length>0&&(c.ent=s)}return c},d.append=function(e,t){if(!e)return t;if(!t)return e;e.txt=e.txt||"";const s=E(e.txt).length;return"string"==typeof t?e.txt+=t:t.txt&&(e.txt+=t.txt),Array.isArray(t.fmt)&&(e.fmt=e.fmt||[],Array.isArray(t.ent)&&(e.ent=e.ent||[]),t.fmt.forEach(i=>{const n={at:(0|i.at)+s,len:0|i.len};-1==i.at&&(n.at=-1,n.len=0),i.tp?n.tp=i.tp:(n.key=e.ent.length,e.ent.push(t.ent[i.key||0])),e.fmt.push(n)})),e},d.insertImage=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"IM",data:{mime:s.mime,ref:s.refurl,val:s.bits||s.preview,width:s.width,height:s.height,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then(e=>{i.data.ref=e,i.data._tempPreview=void 0,i.data._processing=void 0},e=>{i.data._processing=void 0})),e.ent.push(i),e},d.insertVideo=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"VD",data:{mime:s.mime,ref:s.refurl,val:s.bits,preref:s.preref,preview:s.preview,width:s.width,height:s.height,duration:0|s.duration,name:s.filename,size:0|s.size}};return s.urlPromise&&(i.data._tempPreview=s._tempPreview,i.data._processing=!0,s.urlPromise.then(e=>{i.data.ref=e[0],i.data.preref=e[1],i.data._tempPreview=void 0,i.data._processing=void 0},e=>{i.data._processing=void 0})),e.ent.push(i),e},d.insertAudio=function(e,t,s){(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:0|t,len:1,key:e.ent.length});const i={tp:"AU",data:{mime:s.mime,val:s.bits,duration:0|s.duration,preview:s.preview,name:s.filename,size:0|s.size,ref:s.refurl}};return s.urlPromise&&(i.data._processing=!0,s.urlPromise.then(e=>{i.data.ref=e,i.data._processing=void 0},e=>{i.data._processing=void 0})),e.ent.push(i),e},d.videoCall=function(e){return{txt:" ",fmt:[{at:0,len:1,key:0}],ent:[{tp:"VC",data:{aonly:e}}]}},d.updateVideoCall=function(e,t){const s=((e||{}).fmt||[])[0];if(!s)return e;let i;if("VC"==s.tp)delete s.tp,s.key=0,i={tp:"VC"},e.ent=[i];else if(i=(e.ent||[])[0|s.key],!i||"VC"!=i.tp)return e;return i.data=i.data||{},Object.assign(i.data,t),e},d.quote=function(e,t,s){const i=d.append(d.appendLineBreak(d.mention(e,t)),s);return i.fmt.push({at:0,len:E(i.txt).length,tp:"QQ"}),i},d.mention=function(e,t){return{txt:e||"",fmt:[{at:0,len:E(e||"").length,key:0}],ent:[{tp:"MN",data:{val:t}}]}},d.appendLink=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:t.txt.length,key:e.ent.length}),e.txt+=t.txt;const s={tp:"LN",data:{url:t.url}};return e.ent.push(s),e},d.appendImage=function(e,t){return(e=e||{txt:""}).txt+=" ",d.insertImage(e,e.txt.length-1,t)},d.appendAudio=function(e,t){return(e=e||{txt:""}).txt+=" ",d.insertAudio(e,e.txt.length-1,t)},d.attachFile=function(e,t){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});const s={tp:"EX",data:{mime:t.mime,val:t.data,name:t.filename,ref:t.refurl,size:0|t.size}};return t.urlPromise&&(s.data._processing=!0,t.urlPromise.then(e=>{s.data.ref=e,s.data._processing=void 0},e=>{s.data._processing=void 0})),e.ent.push(s),e},d.wrapInto=function(e,t,s,i){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:s||0,len:i||e.txt.length,tp:t}),e},d.wrapAsForm=function(e,t,s){return d.wrapInto(e,"FM",t,s)},d.insertButton=function(e,t,s,i,n,r,a){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length<t+s||s<=0||-1==["url","pub"].indexOf(n)?null:"url"!=n||a?(a=""+a,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:n,val:r,ref:a,name:i}}),e):null},d.appendButton=function(e,t,s,i,n,r){const a=(e=e||{txt:""}).txt.length;return e.txt+=t,d.insertButton(e,a,t.length,s,i,n,r)},d.attachJSON=function(e,s){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:t,val:s}}),e},d.appendLineBreak=function(e){return(e=e||{txt:""}).fmt=e.fmt||[],e.fmt.push({at:E(e.txt).length,len:1,tp:"BR"}),e.txt+=" ",e},d.UNSAFE_toHTML=function(e){return w(g(e),function(e,t,s){const i=l[e];let n=s?s.join(""):"";return i&&(n=i.open(t)+n+i.close(t)),n},0)},d.format=function(e,t,s){return w(g(e),t,0,[],s)},d.shorten=function(e,t,s){let i=g(e);return i=v(i,t,"…"),i&&s&&(i=y(i)),_({},i,[])},d.forwardedContent=function(e){let t=g(e);return t=b(t,function(e){return"MN"!=e.type||e.parent&&e.parent.type?e:null}),t=M(t),_({},t,[])},d.replyContent=function(e,t){let s=g(e);if(!s)return e;s=b(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=x(s,3),s=v(s,t,"…");return s=y(s,e=>{switch(e.type){case"IM":return["val"];case"VD":return["preview"]}return null}),_({},s,[])},d.preview=function(e,t,s){let i=g(e);i=x(i,3);if(i=b(i,function(e){return"MN"==e.type?e.parent&&e.parent.type||!(e.text||"").startsWith("➦")||(e.text="➦",delete e.children):"QQ"==e.type?(e.text=" ",delete e.children):"BR"==e.type&&(e.text=" ",delete e.children,delete e.type),e}),i=v(i,t,"…"),s){const e={IM:["val"],VD:["preview"]};i=y(i,t=>e[t.type])}else i=y(i);return _({},i,[])},d.toPlainText=function(e){return"string"==typeof e?e:e.txt},d.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},d.toMarkdown=function(e){return w(g(e),function(e,t,s){const i=o[e];let n=s?s.join(""):"";return i&&(i.isVoid?n=i.md_tag||"":i.md_tag&&(n=i.md_tag+n+i.md_tag)),n},0)},d.isValid=function(e){if(!e)return!1;const{txt:t,fmt:s,ent:i}=e;if(!t&&""!==t&&!s&&!i)return!1;const n=typeof t;return("string"==n||"undefined"==n||null===t)&&(!(void 0!==s&&!Array.isArray(s)&&null!==s)&&!(void 0!==i&&!Array.isArray(i)&&null!==i))},d.hasAttachments=function(e){if(!Array.isArray(e.fmt))return!1;for(let t in e.fmt){const s=e.fmt[t];if(s&&s.at<0){const t=e.ent[0|s.key];return t&&"EX"==t.tp&&t.data}}return!1},d.attachments=function(e,t,s){if(!Array.isArray(e.fmt))return;let i=0;for(let n in e.fmt){let r=e.fmt[n];if(r&&r.at<0){const n=e.ent[0|r.key];if(n&&"EX"==n.tp&&n.data&&t.call(s,n.data,i++,"EX"))break}}},d.hasEntities=function(e){return e.ent&&e.ent.length>0},d.entities=function(e,t,s){if(e.ent&&e.ent.length>0)for(let i in e.ent)if(e.ent[i]&&t.call(s,e.ent[i].data,i,e.ent[i].tp))break},d.styles=function(e,t,s){if(e.fmt&&e.fmt.length>0)for(let i in e.fmt){const n=e.fmt[i];if(n&&t.call(s,n.tp,n.at,n.len,n.key,i))break}},d.sanitizeEntities=function(e){if(e&&e.ent&&e.ent.length>0)for(let t in e.ent){const s=e.ent[t];if(s&&s.data){const i=P(s.data);i?e.ent[t].data=i:delete e.ent[t].data}}return e},d.getDownloadUrl=function(e){let t=null;return!d.isFormResponseType(e.mime)&&e.val?t=c(e.val,e.mime,d.logger):"string"==typeof e.ref&&(t=e.ref),t},d.isProcessing=function(e){return!!e._processing},d.getPreviewUrl=function(e){return e.val?c(e.val,e.mime,d.logger):null},d.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},d.getEntityMimeType=function(e){return e.mime||"text/plain"},d.tagName=function(e){return o[e]&&o[e].html_tag},d.attrValue=function(e,t){if(t&&l[e]&&l[e].props)return l[e].props(t)},d.getContentType=function(){return"text/x-drafty"},d.isFormResponseType=function(e){return e===t||"application/json"===e},e.exports=d}},t={};function s(i){var n=t[i];if(void 0!==n)return n.exports;var r=t[i]={exports:{}};return e[i](r,r.exports,s),r.exports}s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},s.d=function(e,t){for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};s.r(i),s.d(i,{AccessMode:function(){return n},Drafty:function(){return q()},Tinode:function(){return X}});class n{constructor(e){e&&(this.given="number"==typeof e.given?e.given:n.decode(e.given),this.want="number"==typeof e.want?e.want:n.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:n.decode(e.mode):this.given&this.want)}static#e(e,t,s){if(["given","want","mode"].includes(t=t||"mode"))return 0!=(e[t]&s);throw new Error(`Invalid AccessMode component '${t}'`)}static decode(e){if(!e)return null;if("number"==typeof e)return e&n._BITMASK;if("N"===e||"n"===e)return n._NONE;const t={J:n._JOIN,R:n._READ,W:n._WRITE,P:n._PRES,A:n._APPROVE,S:n._SHARE,D:n._DELETE,O:n._OWNER};let s=n._NONE;for(let i=0;i<e.length;i++){const n=t[e.charAt(i).toUpperCase()];n&&(s|=n)}return s}static encode(e){if(null===e||e===n._INVALID)return null;if(e===n._NONE)return"N";const t=["J","R","W","P","A","S","D","O"];let s="";for(let i=0;i<t.length;i++)e&1<<i&&(s+=t[i]);return s}static update(e,t){if(!t||"string"!=typeof t)return e;let s=t.charAt(0);if("+"==s||"-"==s){let i=e;const r=t.split(/([-+])/);for(let t=1;t<r.length-1;t+=2){s=r[t];const a=n.decode(r[t+1]);if(a==n._INVALID)return e;null!=a&&("+"===s?i|=a:"-"===s&&(i&=~a))}e=i}else{const s=n.decode(t);s!=n._INVALID&&(e=s)}return e}static diff(e,t){return e=n.decode(e),t=n.decode(t),e==n._INVALID||t==n._INVALID?n._INVALID:e&~t}toString(){return'{"mode": "'+n.encode(this.mode)+'", "given": "'+n.encode(this.given)+'", "want": "'+n.encode(this.want)+'"}'}jsonHelper(){return{mode:n.encode(this.mode),given:n.encode(this.given),want:n.encode(this.want)}}setMode(e){return this.mode=n.decode(e),this}updateMode(e){return this.mode=n.update(this.mode,e),this}getMode(){return n.encode(this.mode)}setGiven(e){return this.given=n.decode(e),this}updateGiven(e){return this.given=n.update(this.given,e),this}getGiven(){return n.encode(this.given)}setWant(e){return this.want=n.decode(e),this}updateWant(e){return this.want=n.update(this.want,e),this}getWant(){return n.encode(this.want)}getMissing(){return n.encode(this.want&~this.given)}getExcessive(){return n.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 n.#e(this,e,n._OWNER)}isPresencer(e){return n.#e(this,e,n._PRES)}isMuted(e){return!this.isPresencer(e)}isJoiner(e){return n.#e(this,e,n._JOIN)}isReader(e){return n.#e(this,e,n._READ)}isWriter(e){return n.#e(this,e,n._WRITE)}isApprover(e){return n.#e(this,e,n._APPROVE)}isAdmin(e){return this.isOwner(e)||this.isApprover(e)}isSharer(e){return this.isAdmin(e)||n.#e(this,e,n._SHARE)}isDeleter(e){return n.#e(this,e,n._DELETE)}}n._NONE=0,n._JOIN=1,n._READ=2,n._WRITE=4,n._PRES=8,n._APPROVE=16,n._SHARE=32,n._DELETE=64,n._OWNER=128,n._BITMASK=n._JOIN|n._READ|n._WRITE|n._PRES|n._APPROVE|n._SHARE|n._DELETE|n._OWNER,n._INVALID=1048576;const r="0.25.1",a="tinodejs/"+r,o="new",c="nch",h="me",l="fnd",d="grp",u=268435455,p="␡",g="alias:";class m extends Error{constructor(e,t){super(`${e} (${t})`),this.name="CommError",this.code=t}}function f(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 n(t);return t}function _(e){return e&&!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}function b(e){return e instanceof Date&&!isNaN(e)&&0!=e.getTime()}function w(e,t){if("object"!=typeof t){if(void 0===t)return e;if(t===p)return;return t}if(null===t)return e;if(t instanceof Date&&!isNaN(t))return!e||!(e instanceof Date)||isNaN(e)||e<t?t:e;if(t instanceof n)return new n(t);if(t instanceof Array)return t;e&&e!==p||(e=t.constructor());for(let s in t)if(t.hasOwnProperty(s)&&"_noForwarding"!=s)try{e[s]=w(e[s],t[s])}catch(e){console.warn("Error merging property:",s,e)}return e}function v(e,t,s){return e[t]=w(e[t],s),e[t]}function y(e){return Object.keys(e).forEach(t=>{"_"==t[0]?delete e[t]:e[t]?Array.isArray(e[t])&&0==e[t].length?delete e[t]:e[t]?e[t]instanceof Date?b(e[t])||delete e[t]:"object"==typeof e[t]&&(y(e[t]),0==Object.getOwnPropertyNames(e[t]).length&&delete e[t]):delete e[t]:delete e[t]}),e}function M(e,t){return Array.isArray(e)?(e.sort((e,t)=>e.low<t.low?-1:e.low==t.low?(0|t.hi)-e.hi:1),e=(e=e.reduce((e,s)=>(s.low<u&&s.low>0&&(!s.hi||s.hi<u?e.push(s):e.push({low:s.low,hi:t+1})),e),[])).reduce((e,t)=>{if(0==e.length)e.push(t);else{let s=e[e.length-1];t.low<=s.hi?s.hi=Math.max(s.hi,t.hi):e.push(t)}return e},[])):[]}function x(e){return e.sort((e,t)=>e-t),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},[])}let T,P;const S="Connection failed",A=418,E="Disconnected by client";function k(e,t,s,i){let n=null;return["http","https","ws","wss"].includes(t)&&(n=`${t}://${e}`,"/"!==n.charAt(n.length-1)&&(n+="/"),n+="v"+s+"/channels",["http","https"].includes(t)&&(n+="/lp"),n+="?apikey="+i),n}class D{static#t=e=>{};#s=null;#i=0;#n=!1;#r=null;host;secure;apiKey;version;autoreconnect;initialized;constructor(e,t,s){if(this.host=e.host,this.secure=e.secure,this.apiKey=e.apiKey,this.version=t,this.autoreconnect=s,"lp"===e.transport?(this.#a(),this.initialized="lp"):"ws"===e.transport&&(this.#o(),this.initialized="ws"),!this.initialized)throw D.#t("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."),new Error("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.")}static setNetworkProviders(e,t){T=e,P=t}static set logger(e){D.#t=e}connect(e,t){return Promise.reject(null)}reconnect(e){}disconnect(){}sendText(e){}isConnected(){return!1}transport(){return this.initialized}probe(){this.sendText("1")}backoffReset(){this.#c()}#h(){clearTimeout(this.#s);const e=Math.pow(2,this.#i)*(1+.3*Math.random())*2e3;this.#i=this.#i>=10?this.#i:this.#i+1,this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e),this.#s=setTimeout(t=>{if(D.#t(`Reconnecting, iter=${this.#i}, timeout=${e}`),this.#n)this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{const e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch(e=>{})}},e)}#l(){clearTimeout(this.#s),this.#s=null}#c(){this.#i=0}#a(){let e=null,t=null,s=null,i=(t,s,n)=>{let r=new P,a=!1;return r.onreadystatechange=o=>{if(4==r.readyState)if(201==r.status){let n=JSON.parse(r.responseText,f);e=t+"&sid="+n.ctrl.params.sid,r=i(e),r.send(null),this.onOpen&&this.onOpen(),s&&(a=!0,s()),this.autoreconnect&&this.#l()}else if(r.status>0&&r.status<400)this.onMessage&&this.onMessage(r.responseText),r=i(e),r.send(null);else{if(n&&!a&&(a=!0,n(r.responseText)),this.onMessage&&r.responseText&&this.onMessage(r.responseText),this.onDisconnect){const e=r.status||(this.#n?A:503),t=r.responseText||(this.#n?E:S);this.onDisconnect(new m(t,e),e)}r=null,!this.#n&&this.autoreconnect&&this.#h()}},r.open("POST",t,!0),r};this.connect=(e,s)=>{if(this.#n=!1,t){if(!s)return Promise.resolve();t.onreadystatechange=void 0,t.abort(),t=null}return e&&(this.host=e),new Promise((e,s)=>{const n=k(this.host,this.secure?"https":"http",this.version,this.apiKey);D.#t("LP connecting to:",n),t=i(n,e,s),t.send(null)}).catch(e=>{D.#t("LP connection failed:",e)})},this.reconnect=e=>{this.#l(),this.connect(null,e)},this.disconnect=i=>{this.#n=!0,this.#l(),s&&(s.onreadystatechange=void 0,s.abort(),s=null),t&&(t.onreadystatechange=void 0,t.abort(),t=null),this.onDisconnect&&this.onDisconnect(new m(E,A),A),e=null},this.sendText=t=>{if(s=(e=>{const t=new P;return t.onreadystatechange=e=>{if(4==t.readyState&&t.status>=400)throw new m("LP sender failed",t.status)},t.open("POST",e,!0),t})(e),!s||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(t)},this.isConnected=e=>t&&!0}#o(){this.connect=(e,t)=>{if(this.#n=!1,this.#r){if(!t&&this.#r.readyState==this.#r.OPEN)return this.probe(),Promise.resolve();this.#r.close(),this.#r=null}return e&&(this.host=e),new Promise((e,t)=>{const s=k(this.host,this.secure?"wss":"ws",this.version,this.apiKey);D.#t("WS connecting to: ",s);const i=new T(s);i.onerror=e=>{t(e)},i.onopen=t=>{this.autoreconnect&&this.#l(),this.onOpen&&this.onOpen(),e()},i.onclose=e=>{if(this.#r=null,this.onDisconnect){const e=this.#n?A:503;this.onDisconnect(new m(this.#n?E:S,e),e)}!this.#n&&this.autoreconnect&&this.#h()},i.onmessage=e=>{this.onMessage&&this.onMessage(e.data)},this.#r=i})},this.reconnect=e=>{this.#l(),this.connect(null,e)},this.disconnect=e=>{this.#n=!0,this.#l(),this.#r&&(this.#r.close(),this.#r=null)},this.sendText=e=>{if(!this.#r||this.#r.readyState!=this.#r.OPEN)throw new Error("Websocket is not connected");this.#r.send(e)},this.isConnected=e=>this.#r&&this.#r.readyState==this.#r.OPEN}onMessage=void 0;onDisconnect=void 0;onOpen=void 0;onAutoreconnectIteration=void 0}D.NETWORK_ERROR=503,D.NETWORK_ERROR_TEXT=S,D.NETWORK_USER=A,D.NETWORK_USER_TEXT=E;const R="tinode-web";let N;class C{#d=e=>{};#u=e=>{};db=null;disabled=!0;constructor(e,t){this.#d=e||this.#d,this.#u=t||this.#u}#p(e,t,s){return this.db?new Promise((i,n)=>{const r=this.db.transaction([e]);r.onerror=t=>{this.#u("PCache","mapObjects",e,t.target.error),n(t.target.error)},r.objectStore(e).getAll().onsuccess=e=>{t&&e.target.result.forEach(e=>{t.call(s,e)}),i(e.target.result)}}):disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}initDatabase(){return new Promise((e,t)=>{const s=N.open(R,3);s.onsuccess=t=>{this.db=t.target.result,this.disabled=!1,this.db.onversionchange=e=>{this.#u("PCache","another tab tries to upgrade DB, shutting down"),this.db.close(),this.db=null,this.disabled=!0},e(this.db)},s.onerror=e=>{this.#u("PCache","failed to initialize",e),t(e.target.error),this.#d(e.target.error)},s.onupgradeneeded=e=>{if(this.db=e.target.result,this.db.onerror=e=>{this.#u("PCache","failed to create storage",e),this.#d(e.target.error)},this.db.objectStoreNames.contains("topic")||this.db.createObjectStore("topic",{keyPath:"name"}),this.db.objectStoreNames.contains("user")||this.db.createObjectStore("user",{keyPath:"uid"}),this.db.objectStoreNames.contains("subscription")||this.db.createObjectStore("subscription",{keyPath:["topic","uid"]}),this.db.objectStoreNames.contains("message")||this.db.createObjectStore("message",{keyPath:["topic","seq"]}),!this.db.objectStoreNames.contains("dellog")){const e=this.db.createObjectStore("dellog",{keyPath:["topic","low","hi"]});e.indexNames.contains("topic_clear")||e.createIndex("topic_clear",["topic","clear"],{unique:!1})}}})}deleteDatabase(){return this.db&&(this.db.close(),this.db=null),new Promise((e,t)=>{const s=N.deleteDatabase(R);s.onblocked=e=>{this.db&&this.db.close();const s=new Error("blocked");this.#u("PCache","deleteDatabase",s),t(s)},s.onsuccess=t=>{this.db=null,this.disabled=!0,e(!0)},s.onerror=e=>{this.#u("PCache","deleteDatabase",e.target.error),t(e.target.error)}})}isReady(){return!!this.db}updTopic(e){return this.isReady()?new Promise((t,s)=>{const i=this.db.transaction(["topic"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","updTopic",e.target.error),s(e.target.error)};const n=i.objectStore("topic").get(e.name);n.onsuccess=t=>{i.objectStore("topic").put(C.#g(n.result,e)),i.commit()}}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}markTopicAsDeleted(e,t){return this.isReady()?new Promise((s,i)=>{const n=this.db.transaction(["topic"],"readwrite");n.oncomplete=e=>{s(e.target.result)},n.onerror=e=>{this.#u("PCache","markTopicAsDeleted",e.target.error),i(e.target.error)};n.objectStore("topic").get(e).onsuccess=e=>{const s=e.target.result;s&&s._deleted!=t&&(s._deleted=t,n.objectStore("topic").put(s)),n.commit()}}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remTopic(e){return this.isReady()?new Promise((t,s)=>{const i=this.db.transaction(["topic","subscription","message"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","remTopic",e.target.error),s(e.target.error)},i.objectStore("topic").delete(IDBKeyRange.only(e)),i.objectStore("subscription").delete(IDBKeyRange.bound([e,"-"],[e,"~"])),i.objectStore("message").delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),i.commit()}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapTopics(e,t){return this.#p("topic",e,t)}deserializeTopic(e,t){C.#m(e,t)}updUser(e,t){if(!(arguments.length<2||void 0===t))return this.isReady()?new Promise((s,i)=>{const n=this.db.transaction(["user"],"readwrite");n.oncomplete=e=>{s(e.target.result)},n.onerror=e=>{this.#u("PCache","updUser",e.target.error),i(e.target.error)},n.objectStore("user").put({uid:e,public:t}),n.commit()}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remUser(e){return this.isReady()?new Promise((t,s)=>{const i=this.db.transaction(["user"],"readwrite");i.oncomplete=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","remUser",e.target.error),s(e.target.error)},i.objectStore("user").delete(IDBKeyRange.only(e)),i.commit()}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapUsers(e,t){return this.#p("user",e,t)}getUser(e){return this.isReady()?new Promise((t,s)=>{const i=this.db.transaction(["user"]);i.oncomplete=e=>{const s=e.target.result;t({user:s.uid,public:s.public})},i.onerror=e=>{this.#u("PCache","getUser",e.target.error),s(e.target.error)},i.objectStore("user").get(e)}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updSubscription(e,t,s){return this.isReady()?new Promise((i,n)=>{const r=this.db.transaction(["subscription"],"readwrite");r.oncomplete=e=>{i(e.target.result)},r.onerror=e=>{this.#u("PCache","updSubscription",e.target.error),n(e.target.error)},r.objectStore("subscription").get([e,t]).onsuccess=i=>{r.objectStore("subscription").put(C.#f(i.target.result,e,t,s)),r.commit()}}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}mapSubscriptions(e,t,s){return this.isReady()?new Promise((i,n)=>{const r=this.db.transaction(["subscription"]);r.onerror=e=>{this.#u("PCache","mapSubscriptions",e.target.error),n(e.target.error)},r.objectStore("subscription").getAll(IDBKeyRange.bound([e,"-"],[e,"~"])).onsuccess=e=>{t&&e.target.result.forEach(e=>{t.call(s,e)}),i(e.target.result)}}):this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"))}addMessage(e){return this.isReady()?new Promise((t,s)=>{const i=this.db.transaction(["message"],"readwrite");i.onsuccess=e=>{t(e.target.result)},i.onerror=e=>{this.#u("PCache","addMessage",e.target.error),s(e.target.error)},i.objectStore("message").add(C.#_(null,e)),i.commit()}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}updMessageStatus(e,t,s){return this.isReady()?new Promise((i,n)=>{const r=this.db.transaction(["message"],"readwrite");r.onsuccess=e=>{i(e.target.result)},r.onerror=e=>{this.#u("PCache","updMessageStatus",e.target.error),n(e.target.error)};const a=r.objectStore("message").get(IDBKeyRange.only([e,t]));a.onsuccess=i=>{const n=a.result||i.target.result;n&&n._status!=s?(r.objectStore("message").put(C.#_(n,{topic:e,seq:t,_status:s})),r.commit()):r.commit()}}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}remMessages(e,t,s){return this.isReady()?new Promise((i,n)=>{t||s||(t=0,s=Number.MAX_SAFE_INTEGER);const r=s>0?IDBKeyRange.bound([e,t],[e,s],!1,!0):IDBKeyRange.only([e,t]),a=this.db.transaction(["message"],"readwrite");a.onsuccess=e=>{i(e.target.result)},a.onerror=e=>{this.#u("PCache","remMessages",e.target.error),n(e.target.error)},a.objectStore("message").delete(r),a.commit()}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}readMessages(e,t,s,i){if(t=t||{},!this.isReady())return this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"));const n=this.db.transaction(["message"]);let r=[];return Array.isArray(t.ranges)?new Promise((a,o)=>{n.onerror=e=>{this.#u("PCache","readMessages",e.target.error),o(e.target.error)};let c=0;t.ranges.forEach(o=>{const h=o.hi?IDBKeyRange.bound([e,o.low],[e,o.hi],!1,!0):IDBKeyRange.only([e,o.low]);n.objectStore("message").getAll(h).onsuccess=e=>{const n=e.target.result;n&&(s&&s.call(i,n),Array.isArray(n)?r=r.concat(n):r.push(n)),c++,c==t.ranges.length&&a(r)}})}):new Promise((a,o)=>{const c=t.since>0?t.since:0,h=t.before>0?t.before:Number.MAX_SAFE_INTEGER,l=0|t.limit;n.onerror=e=>{this.#u("PCache","readMessages",e.target.error),o(e.target.error)};const d=IDBKeyRange.bound([e,c],[e,h],!1,!0);n.objectStore("message").openCursor(d,"prev").onsuccess=e=>{const t=e.target.result;t?(s&&s.call(i,t.value),r.push(t.value),l<=0||r.length<l?t.continue():a(r)):a(r)}})}addDelLog(e,t,s){return this.isReady()?new Promise((i,n)=>{const r=this.db.transaction(["dellog"],"readwrite");r.onsuccess=e=>{i(e.target.result)},r.onerror=e=>{this.#u("PCache","addDelLog",e.target.error),n(e.target.error)},s.forEach(s=>r.objectStore("dellog").add({topic:e,clear:t,low:s.low,hi:s.hi||s.low+1})),r.commit()}):this.disabled?Promise.resolve():Promise.reject(new Error("not initialized"))}readDelLog(e,t){if(t=t||{},!this.isReady())return this.disabled?Promise.resolve([]):Promise.reject(new Error("not initialized"));const s=this.db.transaction(["dellog"]);let i=[];return Array.isArray(t.ranges)?new Promise((n,r)=>{s.onerror=e=>{this.#u("PCache","readDelLog",e.target.error),r(e.target.error)};let a=0;t.ranges.forEach(r=>{const o=r.hi||r.low+1,c=IDBKeyRange.bound([e,0,r.low],[e,o,Number.MAX_SAFE_INTEGER],!1,!0);s.objectStore("dellog").getAll(c).onsuccess=e=>{const s=e.target.result;s&&(Array.isArray(s)?i=i.concat(s.map(e=>({low:e.low,hi:e.hi}))):i.push({low:s.low,hi:s.hi})),a++,a==t.ranges.length&&n(i)}})}):new Promise((i,n)=>{const r=t.since>0?t.since:0,a=t.before>0?t.before:Number.MAX_SAFE_INTEGER,o=0|t.limit;s.onerror=e=>{this.#u("PCache","readDelLog",e.target.error),n(e.target.error)};let c=0;const h=[],l=IDBKeyRange.bound([e,0,r],[e,a,Number.MAX_SAFE_INTEGER],!1,!0);s.objectStore("dellog").openCursor(l,"prev").onsuccess=e=>{const t=e.target.result;t?(h.push({low:t.value.low,hi:t.value.hi}),c+=t.value.hi-t.value.low,o<=0||c<o?t.continue():i(h)):i(h)}})}maxDelId(e){return this.isReady()?new Promise((t,s)=>{const i=this.db.transaction(["dellog"]);i.onerror=e=>{this.#u("PCache","maxDelId",e.target.error),s(e.target.error)};i.objectStore("dellog").index("topic_clear").openCursor(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER]),"prev").onsuccess=e=>{e.target.result&&t(e.target.result.value)}}):this.disabled?Promise.resolve(0):Promise.reject(new Error("not initialized"))}static#b=["created","updated","deleted","touched","read","recv","seq","clear","defacs","creds","public","trusted","private","_aux","_deleted"];static#m(e,t){C.#b.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)}static#g(e,t){const s=e||{name:t.name};return C.#b.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}static#f(e,t,s,i){const n=e||{topic:t,uid:s};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach(e=>{i.hasOwnProperty(e)&&(n[e]=i[e])}),n}static#_(e,t){const s=e||{};return["topic","seq","ts","_status","from","head","content"].forEach(e=>{t.hasOwnProperty(e)&&(s[e]=t[e])}),s}static setDatabaseProvider(e){N=e}}var I=s(767),q=s.n(I);let U,O,j,L;class G{constructor(e,t){this._tinode=e,this._version=t,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this.xhr=[]}uploadWithBaseUrl(e,t,s,i,n,r){let a=`/v${this._version}/file/u/`;if(e){let t=e;if(t.endsWith("/")&&(t=t.slice(0,-1)),!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Invalid base URL '${e}'`);a=t+a}const o=this,c=new U;this.xhr.push(c),c.open("POST",a,!0),c.setRequestHeader("X-Tinode-APIKey",this._apiKey),this._authToken&&c.setRequestHeader("X-Tinode-Auth",`Token ${this._authToken.token}`);let h=null,l=null;const d=new Promise((e,t)=>{h=e,l=t});c.upload.onprogress=e=>{e.lengthComputable&&(i&&i(e.loaded/e.total),this.onProgress&&this.onProgress(e.loaded/e.total))},c.onload=function(){let e;try{e=JSON.parse(this.response,f)}catch(t){o._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(h&&h(e.ctrl.params.url),n&&n(e.ctrl)):this.status>=400?(l&&l(new m(e.ctrl.text,e.ctrl.code)),r&&r(e.ctrl)):o._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},c.onerror=function(e){l&&l(e||new Error("failed")),r&&r(null)},c.onabort=function(e){l&&l(new Error("upload cancelled by user")),r&&r(null)};try{const e=new FormData;e.append("file",t),e.set("id",this._tinode.getNextUniqueId()),s&&e.set("topic",s),c.send(e)}catch(e){l&&l(e),r&&r(null)}return d}upload(e,t,s,i,n){const r=(this._tinode._secure?"https://":"http://")+this._tinode._host;return this.uploadWithBaseUrl(r,e,t,s,i,n)}download(e,t,s,i,n){if(!_(e))return void(n&&n(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(n&&n("Must authenticate first"));const r=this,a=new U;this.xhr.push(a),e=function(e,t,s){const i=new URL(e,window.location.origin);return i.searchParams.append(t,s),i.toString().substring(window.location.origin.length)}(e,"asatt","1"),a.open("GET",e,!0),a.setRequestHeader("X-Tinode-APIKey",this._apiKey),a.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),a.responseType="blob",a.onprogress=function(e){i&&i(e.loaded)};let o=null,c=null;const h=new Promise((e,t)=>{o=e,c=t});a.onload=function(){if(200==this.status){const e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:s})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),o&&o()}else if(this.status>=400&&c){const e=new FileReader;e.onload=function(){try{const e=JSON.parse(this.result,f);c(new m(e.ctrl.text,e.ctrl.code))}catch(e){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),c(e)}},e.readAsText(this.response)}},a.onerror=function(e){c&&c(new Error("failed")),n&&n(e)},a.onabort=function(){c&&c(null)};try{a.send()}catch(e){c&&c(e),n&&n(e)}return h}cancel(){this.xhr.forEach(e=>{e.readyState<4&&e.abort()})}static setNetworkProvider(e){U=e}}class V{constructor(e){this.topic=e,this.what={}}#w(){return this.topic._deleted?void 0:this.topic.updated}#v(){return this.topic.isP2PType()?this.#w():this.topic._deleted?void 0:this.topic._lastSubsUpdate}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)}withDataRanges(e,t){return this.what.data={ranges:M(e,this.topic._maxSeq),limit:t},this}withDataList(e){return this.withDataRanges(x(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(this.#w())}withSub(e,t,s){const i={ims:e,limit:t};return"me"==this.topic.getType()?i.topic=s:i.user=s,this.what.sub=i,this}withOneSub(e,t){return this.withSub(e,void 0,t)}withLaterOneSub(e){return this.withOneSub(this.topic._lastSubsUpdate,e)}withLaterSub(e){return this.withSub(this.#v(),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}withAux(){return this.what.aux=!0,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","aux","del"].forEach(s=>{this.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(this.what[s]).length>0&&(t[s]=this.what[s]))}),e.length>0?t.what=e.join(" "):t=void 0,t}}class z{#y=void 0;#M=!1;buffer=[];constructor(e,t){this.#y=e||((e,t)=>e===t?0:e<t?-1:1),this.#M=t}#x(e,t,s){let i=0,n=t.length-1,r=0,a=0,o=!1;for(;i<=n;)if(r=(i+n)/2|0,a=this.#y(t[r],e),a<0)i=r+1;else{if(!(a>0)){o=!0;break}n=r-1}return o?{idx:r,exact:!0}:s?{idx:-1}:{idx:a<0?r+1:r}}#T(e,t){const s=this.#x(e,t,!1),i=s.exact&&this.#M?1:0;return t.splice(s.idx,i,e),t}getAt(e){return this.buffer[e]}getLast(e){return e?this.buffer.findLast(e):this.buffer[this.buffer.length-1]}put(){let e;e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;for(let t in e)this.#T(e[t],this.buffer)}delAt(e){e|=0;let t=this.buffer.splice(e,1);if(t&&t.length>0)return t[0]}delRange(e,t){return this.buffer.splice(e,t-e)}length(){return this.buffer.length}reset(){this.buffer=[]}forEach(e,t,s,i){t=Math.max(0,0|t),s=Math.min(s||this.buffer.length,this.buffer.length);for(let n=t;n<s;n++)e.call(i,this.buffer[n],n>t?this.buffer[n-1]:void 0,n<s-1?this.buffer[n+1]:void 0,n)}find(e,t){const{idx:s}=this.#x(e,this.buffer,!t);return s}filter(e,t){let s=0;for(let i=0;i<this.buffer.length;i++)e.call(t,this.buffer[i],i)&&(this.buffer[s]=this.buffer[i],s++);this.buffer.splice(s)}isEmpty(){return 0==this.buffer.length}}class F{constructor(e,t){this._tinode=null,this.name=e,this.created=null,this.updated=null,this.touched=new Date(0),this.acs=new n(null),this.private=null,this.public=null,this.trusted=null,this._users={},this._queuedSeqId=u,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._recvNotificationTimer=null,this._tags=[],this._credentials=[],this._aux={},this._messageVersions={},this._messages=new z((e,t)=>e.seq-t.seq,!0),this._attached=!1,this._lastSubsUpdate=new Date(0),this._new=!0,this._deleted=!1,this._delayedLeaveTimer=null,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.onAuxUpdated=t.onAuxUpdated,this.onDeleteTopic=t.onDeleteTopic,this.onAllMessagesReceived=t.onAllMessagesReceived)}static topicType(e){return{me:h,fnd:l,grp:d,new:d,nch:d,chn:d,usr:"p2p",sys:"sys",slf:"slf"}["string"==typeof e?e.substring(0,3):"xxx"]}static isMeTopicName(e){return F.topicType(e)==h}static isSelfTopicName(e){return"slf"==F.topicType(e)}static isGroupTopicName(e){return F.topicType(e)==d}static isP2PTopicName(e){return"p2p"==F.topicType(e)}static isCommTopicName(e){return F.isP2PTopicName(e)||F.isGroupTopicName(e)||F.isSelfTopicName(e)}static isNewGroupTopicName(e){return"string"==typeof e&&(e.substring(0,3)==o||e.substring(0,3)==c)}static isChannelTopicName(e){return"string"==typeof e&&("chn"==e.substring(0,3)||e.substring(0,3)==c)}static#P(e){return e.head&&e.head.replace}isSubscribed(){return this._attached}subscribe(e,t){return clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=null,this._attached?Promise.resolve(this):this._tinode.subscribe(this.name||o,e,t).then(e=>{if(e.code>=300)return e;if(this._attached=!0,this._deleted=!1,this.acs=e.params&&e.params.acs?e.params.acs:this.acs,this._new){if(delete this._new,this.name!=e.topic&&(this._cacheDelSelf(),this.name=e.topic),this._cachePutSelf(),this.created=e.ts,this.updated=e.ts,this.name!=h&&this.name!=l){const e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}t&&t.desc&&(t.desc._noForwarding=!0,this._processMetaDesc(t.desc))}return e})}createMessage(e,t){return this._tinode.createMessage(this.name,e,t)}publish(e,t){return this.publishMessage(this.createMessage(e,t))}publishMessage(e){if(!this._attached)return Promise.reject(new Error("Cannot publish on inactive topic"));if(this._sending)return Promise.reject(new Error("The message is already being sent"));e._sending=!0,e._failed=!1;let t=null;return q().hasEntities(e.content)&&(t=[],q().entities(e.content,e=>{e&&(e.ref&&t.push(e.ref),e.preref&&t.push(e.preref))}),0==t.length&&(t=null)),this._tinode.publishMessage(e,t).then(t=>(e._sending=!1,e.ts=t.ts,this.swapMessageId(e,t.params.seq),this._maybeUpdateMessageVersionsCache(e),this._routeData(e),t)).catch(t=>{this._tinode.logger("WARNING: Message rejected by the server",t),e._sending=!1,e._failed=!0,this.onData&&this.onData()})}publishDraft(e,t){const s=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=s,e.ts=new Date,e.from=this._tinode.getCurrentUserID(),e.noecho=!0,this._messages.put(e),this._tinode._db.addMessage(e),this.onData&&this.onData(e)),(t||Promise.resolve()).then(t=>e._cancelled?{code:300,text:"cancelled"}:this.publishMessage(e)).catch(t=>{throw this._tinode.logger("WARNING: Message draft rejected",t),e._sending=!1,e._failed=!0,e._fatal=t instanceof m&&(t.code>=400&&t.code<500),this.onData&&this.onData(),t})}leave(e){return this._attached||e?this._tinode.leave(this.name,e).then(t=>(this._resetSub(),e&&this._gone(),t)):Promise.reject(new Error("Cannot leave inactive topic"))}leaveDelayed(e,t){clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=setTimeout(t=>{this._delayedLeaveTimer=null,this.leave(e)},t)}getMeta(e){return this._tinode.getMeta(this.name,e)}getMessagesPage(e,t,s,i,n){let r=t?this.startMetaQuery().withDataRanges(t,e):n?this.startMetaQuery().withData(s,void 0,e):this.startMetaQuery().withData(void 0,i,e);return this._loadMessages(this._tinode._db,r.extract("data")).then(a=>0==(t=this.msgHasMoreMessages(s,i,n)).length?Promise.resolve({topic:this.name,code:200,params:{count:a}}):(e-=a,r=this.startMetaQuery().withDataRanges(t,e),this.getMeta(r.build())))}getPinnedMessages(){const e=this.aux("pins");if(!Array.isArray(e))return Promise.resolve(0);const t=[];let s=e;return this._tinode._db.readMessages(this.name,{ranges:x(s)}).then(i=>(i.forEach(e=>{e&&(t.push(e.seq),this._messages.put(e),this._maybeUpdateMessageVersionsCache(e))}),t.length<e.length?(s=e.filter(e=>!t.includes(e)),this._tinode._db.readMessages(this.name,{ranges:x(s)})):null)).then(i=>(i&&s.forEach(e=>{i.find(t=>t.low<=e&&t.hi>e)&&t.push(e)}),t.length==e.length?Promise.resolve({topic:this.name,code:200,params:{count:t.length}}):(s=e.filter(e=>!t.includes(e)),this.getMeta(this.startMetaQuery().withDataList(s).build()))))}setMeta(e){return e.tags&&(e.tags=function(e){let t=[];if(Array.isArray(e)){for(let s=0,i=e.length;s<i;s++){let i=e[s];i&&(i=i.trim().toLowerCase(),i.length>1&&t.push(i))}t=t.sort().filter((e,t,s)=>!t||e!=s[t-1])}return 0==t.length&&t.push(p),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._processMetaSubs([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),e.aux&&this._processMetaAux(e.aux)),t))}updateMode(e,t){const s=e?this.subscriber(e):null,i=s?s.acs.updateGiven(t).getGiven():this.getAccessMode().updateWant(t).getWant();return this.setMeta({sub:{user:e,mode:i}})}invite(e,t){return this.setMeta({sub:{user:e,mode:t}})}archive(e){return this.private&&!this.private.arch==!e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||p}}})}pinMessage(e,t){let s=this.aux("pins");Array.isArray(s)||(s=[]);let i=!1;return t?s.includes(e)||(i=!0,5==s.length&&s.shift(),s.push(e)):s.includes(e)&&(i=!0,s=s.filter(t=>t!=e),0==s.length&&(s=p)),i?this.setMeta({aux:{pins:s}}):Promise.resolve()}pinTopic(e,t){return Promise.reject(new Error("Pinning topics is not supported here"))}pinnedTopicRank(e){return 0}delMessages(e,t){if(!this._attached)return Promise.reject(new Error("Cannot delete messages in inactive topic"));const s=M(e,this._maxSeq);let i;return i=s.length>0?this._tinode.delMessages(this.name,s,t):Promise.resolve({params:{del:0}}),i.then(t=>(t.params.del>this._maxDel&&(this._maxDel=Math.max(t.params.del,this._maxDel),this.clear=Math.max(t.params.del,this.clear)),e.forEach(e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low),this._messages.put({seq:e.low,low:e.low,hi:e.hi,_deleted:!0})}),this._tinode._db.addDelLog(this.name,t.params.del,e),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){return this.delMessages(x(e),t)}delMessagesEdits(e,t){const s=[e];return this.messageVersions(e,e=>s.push(e.seq)),this.delMessagesList(s,t)}delTopic(e){return this._deleted?(this._gone(),Promise.resolve(null)):this._tinode.delTopic(this.name,e).then(e=>(this._deleted=!0,this._resetSub(),this._gone(),e))}delSubscription(e){return this._attached?this._tinode.delSubscription(this.name,e).then(t=>(delete this._users[e],this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users)),t)):Promise.reject(new Error("Cannot delete subscription in inactive topic"))}note(e,t){if(!this._attached)return;const s=this._users[this._tinode.getCurrentUserID()];let i=!1;if(s?(!s[e]||s[e]<t)&&(s[e]=t,i=!0):i=(0|this[e])<t,i&&(this._tinode.note(this.name,e,t),this._updateMyReadRecv(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._attached?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")}noteRecording(e){this._attached?this._tinode.noteKeyPress(this.name,e?"kpa":"kpv"):this._tinode.logger("INFO: Cannot send notification in inactive topic")}videoCall(e,t,s){if(this._attached||["ringing","hang-up"].includes(e))return this._tinode.videoCall(this.name,t,e,s)}_updateMyReadRecv(e,t,s){let i,n=!1;switch(t|=0,this.seq=0|this.seq,this.read=0|this.read,this.recv=0|this.recv,e){case"recv":i=this.recv,this.recv=Math.max(this.recv,t),n=i!=this.recv;break;case"read":i=this.read,this.read=Math.max(this.read,t),n=i!=this.read;break;case"msg":i=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched<s)&&(this.touched=s),n=i!=this.seq}return this.recv<this.read&&(this.recv=this.read,n=!0),this.seq<this.recv&&(this.seq=this.recv,(!this.touched||this.touched<s)&&(this.touched=s),n=!0),this.unread=this.seq-this.read,n}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)}aux(e){return this._aux[e]}alias(){const e=this._tags&&this._tags.find(e=>e.startsWith(g));if(e)return e.substring(6)}subscriber(e){return this._users[e]}messageVersions(e,t,s){if(!t)return;const i=this._messageVersions[e];i&&i.forEach(t,void 0,void 0,s)}messages(e,t,s,i){const n=e||this.onData;if(n){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;if(-1!=e&&-1!=r){let t=[];this._messages.forEach((e,s,i,n)=>{if(F.#P(e))return;if(e._deleted)return;const r=this.latestMsgVersion(e.seq)||e;r._origTs||(r._origTs=r.ts,r._origSeq=r.seq,r.ts=e.ts,r.seq=e.seq),t.push({data:r,idx:n})},e,r,{}),t.forEach((e,s)=>{n.call(i,e.data,s>0?t[s-1].data:void 0,s<t.length-1?t[s+1].data:void 0,e.idx)})}}}findMessage(e){const t=this._messages.find({seq:e});if(t>=0)return this._messages.getAt(t)}latestMessage(){return this._messages.getLast(e=>!e._deleted)}latestMsgVersion(e){const t=this._messageVersions[e];return t?t.getLast():null}maxMsgSeq(){return this._maxSeq}minMsgSeq(){return this._minSeq}maxClearId(){return this._maxDel}messageCount(){return this._messages.length()}queuedMessages(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,u,void 0,t)}msgReceiptCount(e,t){let s=0;if(t>0){const i=this._tinode.getCurrentUserID();for(let n in this._users){const r=this._users[n];r.user!==i&&r[e]>=t&&s++}}return s}msgReadCount(e){return this.msgReceiptCount("read",e)}msgRecvCount(e){return this.msgReceiptCount("recv",e)}msgHasMoreMessages(e,t,s){const i=[];if(e>=t)return i;let n,r=0;return this._messages.forEach((a,o)=>{const c=o||{seq:0},h=c._deleted?c.hi:c.seq+1;n=a.seq>h?{low:h,hi:a.seq}:null,n&&(s?n.hi>=e:n.low<t)&&i.push(n),r=h}),r<this.seq&&(n={low:r+1,hi:this.seq+1},(s?n.hi>=e:n.low<t)&&i.push(n)),i}isNewMessage(e){return this._maxSeq<=e}flushMessage(e){const t=this._messages.find({seq:e});if(delete this._messageVersions[e],t>=0)return this._tinode._db.remMessages(this.name,e),this._messages.delAt(t)}flushMessageRange(e,t){this._tinode._db.remMessages(this.name,e,t);for(let s=e;s<t;s++)delete this._messageVersions[s];const s=this._messages.find({seq:e},!0);return s>=0?this._messages.delRange(s,this._messages.find({seq:t},!0)):[]}swapMessageId(e,t){const s=this._messages.find(e),i=this._messages.length();0<=s&&s<i&&(this._messages.delAt(s),this._tinode._db.remMessages(this.name,e.seq),e.seq=t,this._messages.put(e),this._tinode._db.addMessage(e))}cancelSend(e){const t=this._messages.find({seq:e});if(t>=0){const s=this._messages.getAt(t),i=this.msgStatus(s);if(10==i||30==i||40==i)return this._tinode._db.remMessages(this.name,e),s._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1}getType(){return F.topicType(this.name)}getAccessMode(){return this.acs}setAccessMode(e){return this.acs=new n(e)}getDefaultAccess(){return this.defacs}startMetaQuery(){return new V(this)}isArchived(){return this.private&&!!this.private.arch}isMeType(){return F.isMeTopicName(this.name)}isSelfType(){return F.isSelfTopicName(this.name)}isChannelType(){return F.isChannelTopicName(this.name)}isGroupType(){return F.isGroupTopicName(this.name)}isP2PType(){return F.isP2PTopicName(this.name)}isCommType(){return F.isCommTopicName(this.name)}msgStatus(e,t){let s=0;return this._tinode.isMe(e.from)?e._sending?s=20:e._fatal||e._cancelled?s=40:e._failed?s=30:e.seq>=u?s=10:this.msgReadCount(e.seq)>0?s=70:this.msgRecvCount(e.seq)>0?s=60:e.seq>0&&(s=50):s=80,t&&e._status!=s&&(e._status=s,this._tinode._db.updMessageStatus(this.name,e.seq,s)),s}_maybeUpdateMessageVersionsCache(e){if(!F.#P(e))return void(this._messageVersions[e.seq]&&(this._messageVersions[e.seq].filter(t=>t.from==e.from),this._messageVersions[e.seq].isEmpty()&&delete this._messageVersions[e.seq]));const t=parseInt(e.head.replace.split(":")[1]);if(t>e.seq)return;const s=this.findMessage(t);if(s&&s.from!=e.from)return;const i=this._messageVersions[t]||new z((e,t)=>e.seq-t.seq,!0);i.put(e),this._messageVersions[t]=i}_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,this.msgStatus(e,!0),clearTimeout(this._recvNotificationTimer),this._recvNotificationTimer=setTimeout(e=>{this._recvNotificationTimer=null,this.noteRecv(this._maxSeq)},100)),(e.seq<this._minSeq||0==this._minSeq)&&(this._minSeq=e.seq);const t=!this.isChannelType()&&!e.from||this._tinode.isMe(e.from);if(e.head&&e.head.webrtc&&e.head.mime==q().getContentType()&&e.content){const s={state:e.head.webrtc,duration:e.head["webrtc-duration"],incoming:!t};e.head.vc&&(s.vc=!0),e.content=q().updateVideoCall(e.content,s)}e._noForwarding||(this._messages.put(e),this._tinode._db.addMessage(e),this._maybeUpdateMessageVersionsCache(e)),this.onData&&this.onData(e);const s=t?"read":"msg";this._updateMyReadRecv(s,e.seq,e.ts),!t&&e.from&&this._routeInfo({what:"read",from:e.from,seq:e.seq,_noForwarding:!0}),this._tinode.getMeTopic()._refreshContact(s,this)}_routeMeta(e){e.desc&&this._processMetaDesc(e.desc),e.sub&&e.sub.length>0&&this._processMetaSubs(e.sub),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds(e.cred),e.aux&&this._processMetaAux(e.aux),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?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().withOneSub(void 0,e.src).build());break;case"aux":this.getMeta(this.startMetaQuery().withAux().build());break;case"acs":if(s=e.src||this._tinode.getCurrentUserID(),t=this._users[s],t)t.acs.updateAll(e.dacs),this._processMetaSubs([{user:s,updated:new Date,acs:t.acs}]);else{const i=(new n).updateAll(e.dacs);i&&i.mode!=n._NONE&&(t=this._cacheGetUser(s),t?t.acs=i:(t={user:s,acs:i},this.getMeta(this.startMetaQuery().withOneSub(void 0,s).build())),t.updated=new Date,this._processMetaSubs([t]))}break;default:this._tinode.logger("INFO: Ignored presence update",e.what)}this.onPres&&this.onPres(e)}_routeInfo(e){switch(e.what){case"recv":case"read":const t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv<t.read&&(t.recv=t.read));const s=this.latestMessage();s&&this.msgStatus(s,!0),this._tinode.isMe(e.from)&&!e._noForwarding&&this._updateMyReadRecv(e.what,e.seq),this._tinode.getMeTopic()._refreshContact(e.what,this);break;case"kp":case"kpa":case"kpv":case"call":break;default:this._tinode.logger("INFO: Ignored info update",e.what)}this.onInfo&&this.onInfo(e)}_processMetaDesc(e){if(this.isP2PType()&&(delete e.defacs,this._tinode._db.updUser(this.name,e.public)),w(this,e),this._tinode._db.updTopic(this),this.name!==h&&!e._noForwarding){const e=this._tinode.getMeTopic();e.onMetaSub&&e.onMetaSub(this),e.onSubsUpdated&&e.onSubsUpdated([this.name],1)}this.onMetaDesc&&this.onMetaDesc(this)}_processMetaSubs(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 i=null;s.deleted?(delete this._users[s.user],i=s,this.subcnt--):(this._tinode.isMe(s.user)&&s.acs&&this._processMetaDesc({updated:s.updated,touched:s.touched,acs:s.acs}),this._users[s.user]||this.subcnt++,i=this._updateCachedUser(s.user,s)),this.onMetaSub&&this.onMetaSub(i)}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))}_processMetaTags(e){(e==p||1==e.length&&e[0]==p)&&(e=[]),this._tags=e,this._tinode._db.updTopic(this),this.onTagsUpdated&&this.onTagsUpdated(e)}_processMetaCreds(e){}_processMetaAux(e){e=e&&e!=p?e:{},this._aux=w(this._aux,e),this._tinode._db.updTopic(this),this.onAuxUpdated&&this.onAuxUpdated(this._aux)}_processDelMessages(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);let s=0;Array.isArray(t)&&(t.forEach(e=>{e.hi?(s+=e.hi-e.low,this.flushMessageRange(e.low,e.hi)):(s++,this.flushMessage(e.low)),this._messages.put({seq:e.low,low:e.low,hi:e.hi,_deleted:!0})}),this._tinode._db.addDelLog(this.name,e,t)),s>0&&this.onData&&this.onData()}_allMessagesReceived(e){this.onAllMessagesReceived&&this.onAllMessagesReceived(e)}_resetSub(){this._attached=!1}_gone(){this._messages.reset(),this._tinode._db.remMessages(this.name),this._users={},this.acs=new n(null),this.private=null,this.public=null,this.trusted=null,this._maxSeq=0,this._minSeq=0,this._attached=!1;const e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:h,src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()}_updateCachedUser(e,t){let s=this._cacheGetUser(e);return s=w(s||{},t),this._cachePutUser(e,s),v(this._users,e,s)}_getQueuedSeqId(){return this._queuedSeqId++}_loadMessages(e,t){(t=t||{}).limit=t.limit||24;let s=0;return e.readMessages(this.name,t).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),this._maybeUpdateMessageVersionsCache(e)}),s=e.length}).then(s=>e.readDelLog(this.name,t)).then(e=>e.forEach(e=>{this._messages.put({seq:e.low,low:e.low,hi:e.hi,_deleted:!0})})).then(e=>s)}_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)}}class W extends F{_contacts={};constructor(e){super(l,e)}_processMetaSubs(e){let t=Object.getOwnPropertyNames(this._contacts).length;this._contacts={};for(let s in e){let i=e[s];const n=i.topic?i.topic:i.user;i=v(this._contacts,n,i),t++,this.onMetaSub&&this.onMetaSub(i)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))}publish(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))}setMeta(e){return Object.getPrototypeOf(W.prototype).setMeta.call(this,e).then(e=>{Object.keys(this._contacts).length>0&&(this._contacts={},this.onSubsUpdated&&this.onSubsUpdated([]))})}checkTagUniqueness(e,t){return new Promise((s,i)=>{this.subscribe().then(t=>this.setMeta({desc:{public:e}})).then(e=>this.getMeta(this.startMetaQuery().withTags().build())).then(e=>{e&&Array.isArray(e.tags)&&0!=e.tags.length||s(!0);const i=e.tags.filter(e=>e!==t);s(0==i.length)}).catch(e=>{i(e)})})}contacts(e,t){const s=e||this.onMetaSub;if(s)for(let e in this._contacts)s.call(t,this._contacts[e],e,this._contacts)}}class B extends F{onContactUpdate;constructor(e){super(h,e),e&&(this.onContactUpdate=e.onContactUpdate)}_processMetaDesc(e){const t=e.acs&&!e.acs.isPresencer()&&this.acs&&this.acs.isPresencer();w(this,e),this._tinode._db.updTopic(this),this._updateCachedUser(this._tinode._myUID,e),t&&this._tinode.mapTopics(e=>{e.online&&(e.online=!1,e.seen=Object.assign(e.seen||{},{when:new Date}),this._refreshContact("off",e))}),this.onMetaDesc&&this.onMetaDesc(this)}_processMetaSubs(e){let t=0;if(e.forEach(e=>{const s=e.topic;if(s==l||s==h)return;e.online=!!e.online;let i=null;if(e.deleted)i=e,this._tinode.cacheRemTopic(s),this._tinode._db.remTopic(s);else{void 0!==e.seq&&(e.seq=0|e.seq,e.recv=0|e.recv,e.read=0|e.read,e.unread=e.seq-e.read);const t=this._tinode.getTopic(s);t._new&&delete t._new,i=w(t,e),this._tinode._db.updTopic(i),F.isP2PTopicName(s)&&(this._cachePutUser(s,i),this._tinode._db.updUser(s,i.public)),!e._noForwarding&&t&&(e._noForwarding=!0,t._processMetaDesc(e))}t++,this.onMetaSub&&this.onMetaSub(i)}),this.onSubsUpdated&&t>0){const s=[];e.forEach(e=>{s.push(e.topic)}),this.onSubsUpdated(s,t)}}_processMetaCreds(e,t){1==e.length&&e[0]==p&&(e=[]),t?e.forEach(e=>{if(e.val){let t=this._credentials.findIndex(t=>t.meth==e.meth&&t.val==e.val);t<0?(e.done||(t=this._credentials.findIndex(t=>t.meth==e.meth&&!t.done),t>=0&&this._credentials.splice(t,1)),this._credentials.push(e)):this._credentials[t].done=e.done}else if(e.resp){const t=this._credentials.findIndex(t=>t.meth==e.meth&&!t.done);t>=0&&(this._credentials[t].done=!0)}}):this._credentials=e,this.onCredsUpdated&&this.onCredsUpdated(this._credentials)}_routePres(e){if("term"==e.what)return void this._resetSub();if("upd"==e.what&&e.src==h)return void this.getMeta(this.startMetaQuery().withDesc().build());const t=this._tinode.cacheGetTopic(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":e.tgt||(t.acs?t.acs.updateAll(e.dacs):t.acs=(new n).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.cacheRemTopic(e.src),t._deleted?this._tinode._db.remTopic(e.src):(t._deleted=!0,t._attached=!1,this._tinode._db.markTopicAsDeleted(e.src,!0));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 n(e.dacs);if(!t||t.mode==n._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(t.mode==n._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._db.updTopic(s)}}else if("tags"==e.what)this.getMeta(this.startMetaQuery().withTags().build());else if("msg"==e.what){this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build());const t=this._tinode.getTopic(e.src);t._deleted=!1,this._tinode._db.updTopic(t)}this._refreshContact(e.what,t)}this.onPres&&this.onPres(e)}_refreshContact(e,t){this.onContactUpdate&&this.onContactUpdate(e,t)}publish(){return Promise.reject(new Error("Publishing to 'me' is not supported"))}delCredential(e,t){return this._attached?this._tinode.delCredential(e,t).then(s=>{const i=this._credentials.findIndex(s=>s.meth==e&&s.val==t);return i>-1&&this._credentials.splice(i,1),this.onCredsUpdated&&this.onCredsUpdated(this._credentials),s}):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))}contacts(e,t,s){this._tinode.mapTopics((i,n)=>{!i.isCommType()||t&&!t(i)||e.call(s,i,n)})}getContact(e){return this._tinode.cacheGetTopic(e)}getAccessMode(e){if(e){const t=this._tinode.cacheGetTopic(e);return t?t.acs:null}return this.acs}isArchived(e){const t=this._tinode.cacheGetTopic(e);return t&&t.private&&!!t.private.arch}getCredentials(){return this._credentials}pinTopic(e,t){if(!this._attached)return Promise.reject(new Error("Cannot pin topic in inactive 'me' topic"));if(!F.isCommTopicName(e))return Promise.reject(new Error("Invalid topic to pin"));const s=Array.isArray(this.private&&this.private.tpin)?this.private.tpin:[],i=s.includes(e);return t&&i||!t&&!i?Promise.resolve(s):(t?s.unshift(e):s.splice(s.indexOf(e),1),this.setMeta({desc:{private:{tpin:s.length>0?s:p}}}))}pinnedTopicRank(e){if(!this.private||!this.private.tpin)return 0;const t=this.private.tpin.indexOf(e);return t<0?0:this.private.tpin.length-t}}function K(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)}))}function H(e,t){if(t instanceof Date)t=function(e){if(!b(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"}(t);else if(t instanceof n)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}function Q(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":H(0,t)}"undefined"!=typeof WebSocket&&(O=WebSocket),"undefined"!=typeof XMLHttpRequest&&(j=XMLHttpRequest),"undefined"!=typeof indexedDB&&(L=indexedDB),function(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(s.g.btoa=function(t=""){let s=t,i="";for(let t,n=0,r=0,a=e;s.charAt(0|r)||(a="=",r%1);i+=a.charAt(63&n>>8-r%1*8)){if(t=s.charCodeAt(r+=3/4),t>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");n=n<<8|t}return i});"undefined"==typeof atob&&(s.g.atob=function(t=""){let s=t.replace(/=+$/,""),i="";if(s.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let t,n=0,r=0,a=0;t=s.charAt(a++);~t&&(r=n%4?64*r+t:t,n++%4)?i+=String.fromCharCode(255&r>>(-2*n&6)):0)t=e.indexOf(t);return i});"undefined"==typeof window&&(s.g.window={WebSocket:O,XMLHttpRequest:j,indexedDB:L,URL:{createObjectURL:function(){throw new Error("Unable to use URL.createObjectURL in a non-browser application")}}});D.setNetworkProviders(O,j),G.setNetworkProvider(j),C.setDatabaseProvider(L)}();class X{_host;_secure;_appName;_apiKey;_browser="";_platform;_hwos="undefined";_humanLanguage="xx";_loggingEnabled=!1;_trimLongStrings=!1;_myUID=null;_authenticated=!1;_login=null;_authToken=null;_inPacketCount=0;_messageId=Math.floor(65535*Math.random()+65535);_serverInfo=null;_deviceToken=null;_pendingPromises={};_expirePromises=null;_connection=null;_persist=!1;_db=null;_cache={};constructor(e,t){if(this._host=e.host,this._secure=e.secure,this._appName=e.appName||"Undefined",this._apiKey=e.apiKey,this._platform=e.platform||"web","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";let s,i="";/reactnative/i.test(t)&&(i="ReactNative; ");let n=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(n){const t=["edg","chrome","safari","mobile","version"];let i,r=e.substr(n.index+n[0].length).split(" "),a=[];for(let e=0;e<r.length;e++){let s=/([\w.]+)[\/]([\.\d]+)/.exec(r[e]);s&&(a.push([s[1],s[2],t.findIndex(e=>s[1].toLowerCase().startsWith(e))]),"Version"==s[1]&&(i=s[2]))}a.sort((e,t)=>e[2]-t[2]),a.length>0?(a[0][0].toLowerCase().startsWith("edg")?a[0][0]="Edge":"OPR"==a[0][0]?a[0][0]="Opera":"Safari"==a[0][0]&&i&&(a[0][1]=i),s=a[0][0]+"/"+a[0][1]):s=n[1]}else/firefox/i.test(e)?(n=/Firefox\/([.\d]+)/g.exec(e),s=n?"Firefox/"+n[1]:"Firefox/?"):(n=/([\w.]+)\/([.\d]+)/.exec(e),n?s=n[1]+"/"+n[2]:(n=e.split(" "),s=n[0]));if(n=s.split("/"),n.length>1){const e=n[1].split("."),t=e[1]?"."+e[1].substr(0,2):"";s=`${n[0]}/${e[0]}${t}`}return i+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),D.logger=this.logger,q().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 D(e,"0",!0),this._connection.onMessage=e=>{this.#S(e)},this._connection.onOpen=e=>this.#A(),this._connection.onDisconnect=(e,t)=>this.#E(e,t),this._connection.onAutoreconnectIteration=(e,t)=>{this.onAutoreconnectIteration&&this.onAutoreconnectIteration(e,t)},this._persist=e.persist,this._db=new C(this.logger,this.logger),this._persist){const e=[];this._db.initDatabase().then(t=>this._db.mapTopics(t=>{let s=this.#k("topic",t.name);s||(s=t.name==h?new B:t.name==l?new W:new F(t.name),this._db.deserializeTopic(s,t),this.#D(s),s._cachePutSelf(),this._db.maxDelId(s.name).then(e=>{s._maxDel=Math.max(s._maxDel,e||0)}),delete s._new,e.push(s._loadMessages(this._db)))})).then(e=>this._db.mapUsers(e=>{this.#R("user",e.uid,w({},e.public))})).then(t=>Promise.all(e)).then(e=>{t&&t(),this.logger("Persistent cache initialized.")}).catch(e=>{t&&t(e),this.logger("Failed to initialize persistent cache:",e)})}else this._db.deleteDatabase().then(e=>{t&&t()})}logger(e,...t){if(this._loggingEnabled){const s=new Date,i=("0"+s.getUTCHours()).slice(-2)+":"+("0"+s.getUTCMinutes()).slice(-2)+":"+("0"+s.getUTCSeconds()).slice(-2)+"."+("00"+s.getUTCMilliseconds()).slice(-3);console.log("["+i+"]",e,t.join(" "))}}#N(e){let t=null;return e&&(t=new Promise((t,s)=>{this._pendingPromises[e]={resolve:t,reject:s,ts:new Date}})),t}#C(e,t,s,i){const n=this._pendingPromises[e];n&&(delete this._pendingPromises[e],t>=200&&t<400?n.resolve&&n.resolve(s):n.reject&&n.reject(new m(i,t)))}#I(e,t){let s;t&&(s=this.#N(t)),e=y(e);let i=JSON.stringify(e);this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,Q):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;this.#C(t,D.NETWORK_ERROR,null,e.message)}return s}#S(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,Q):e)),this.onMessage&&this.onMessage(t),t.ctrl?(this.onCtrlMessage&&this.onCtrlMessage(t.ctrl),t.ctrl.id&&this.#C(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout(e=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){const e=this.#k("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=this.#k("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){const e=this.#k("topic",t.ctrl.topic);e&&e._processMetaSubs([])}},0)):setTimeout(e=>{if(t.meta){const e=this.#k("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&this.#C(t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){const e=this.#k("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){const e=this.#k("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){const e=this.#k("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"))}#A(){this._expirePromises||(this._expirePromises=setInterval(e=>{const t=new m("timeout",504),s=new Date((new Date).getTime()-5e3);for(let e in this._pendingPromises){let i=this._pendingPromises[e];i&&i.ts<s&&(this.logger("Promise expired",e),delete this._pendingPromises[e],i.reject&&i.reject(t))}},1e3)),this.hello()}#E(e,t){this._inPacketCount=0,this._serverInfo=null,this._authenticated=!1,this._expirePromises&&(clearInterval(this._expirePromises),this._expirePromises=null),this.#q("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)}#U(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+a}#O(e,t){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:r,ua:this.#U(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:t,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:t,desc:{},sub:{},tags:[],aux:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw new Error(`Unknown packet type requested: ${e}`)}}#R(e,t,s){this._cache[e+":"+t]=s}#k(e,t){return this._cache[e+":"+t]}#j(e,t){delete this._cache[e+":"+t]}#q(e,t,s){const i=e?e+":":void 0;for(let e in this._cache)if((!i||0==e.indexOf(i))&&t.call(s,this._cache[e],e))break}#D(e){e._tinode=this,e._cacheGetUser=e=>{const t=this.#k("user",e);if(t)return{user:e,public:w({},t)}},e._cachePutUser=(e,t)=>{this.#R("user",e,w({},t.public))},e._cacheDelUser=e=>{this.#j("user",e)},e._cachePutSelf=t=>{this.#R("topic",e.name,e)},e._cacheDelSelf=t=>{this.#j("topic",e.name)}}#L(e){return e.params&&e.params.user?(this._myUID=e.params.user,this._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?this._authToken={token:e.params.token,expires:e.params.expires}:this._authToken=null,this.onLogin&&this.onLogin(e.code,e.text),e):e}static credential(e,t,s,i){return"object"==typeof e&&({val:t,params:s,resp:i,meth:e}=e),e&&(t||i)?[{meth:e,val:t,resp:i,params:s}]:null}static topicType(e){return F.topicType(e)}static isMeTopicName(e){return F.isMeTopicName(e)}static isSelfTopicName(e){return F.isSelfTopicName(e)}static isGroupTopicName(e){return F.isGroupTopicName(e)}static isP2PTopicName(e){return F.isP2PTopicName(e)}static isCommTopicName(e){return F.isCommTopicName(e)}static isNewGroupTopicName(e){return F.isNewGroupTopicName(e)}static isChannelTopicName(e){return F.isChannelTopicName(e)}static getVersion(){return r}static setNetworkProviders(e,t){O=e,j=t,D.setNetworkProviders(O,j),G.setNetworkProvider(j)}static setDatabaseProvider(e){L=e,C.setDatabaseProvider(L)}static getLibrary(){return a}static isNullValue(e){return e===p}static isServerAssignedSeq(e){return e>0&&e<u}static isValidTagValue(e){return e&&"string"==typeof e&&e.length>3&&e.length<24&&/^[a-z0-9][a-z0-9_\-]{3,23}$/i.test(e)}static tagSplit(e){if(!e)return null;const t=(e=e.trim()).indexOf(":");if(t<=0)return null;const s=e.substring(t+1);return s?{prefix:e.substring(0,t),value:s}:null}static setUniqueTag(e,t){if(!e||0==e.length)return[t];const s=X.tagSplit(t);return s?((e=e.filter(e=>e&&!e.startsWith(s.prefix))).push(t),e):e}static clearTagPrefix(e,t){return e&&0!=e.length?e.filter(e=>e&&!e.startsWith(t)):[]}static tagByPrefix(e,t){if(e)return e.find(e=>e&&e.startsWith(t))}getNextUniqueId(){return 0!=this._messageId?""+this._messageId++:void 0}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(_(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,i,n){const r=this.#O("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=s,r.acc.login=i,n&&(r.acc.desc.defacs=n.defacs,r.acc.desc.public=n.public,r.acc.desc.private=n.private,r.acc.desc.trusted=n.trusted,r.acc.tags=n.tags,r.acc.cred=n.cred,r.acc.tmpscheme=n.scheme,r.acc.tmpsecret=n.secret,Array.isArray(n.attachments)&&n.attachments.length>0&&(r.extra={attachments:n.attachments.filter(e=>_(e))})),this.#I(r,r.acc.id)}createAccount(e,t,s,i){let n=this.account("new",e,t,s,i);return s&&(n=n.then(e=>this.#L(e))),n}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",K(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",K(t+":"+s),!1,i)}hello(){const e=this.#O("hi");return this.#I(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.#I({hi:{dev:e||X.DEL_CHAR}}),t=!0)),t}login(e,t,s){const i=this.#O("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,this.#I(i,i.login.id).then(e=>this.#L(e))}loginBasic(e,t,s){return this.login("basic",K(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",K(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.#O("sub",e);if(e||(e=o),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){const t=s.desc;X.isNewGroupTopicName(e)?i.sub.set.desc=t:X.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=>_(e))}),s.tags&&(i.sub.set.tags=s.tags),s.aux&&(i.sub.set.aux=s.aux)}return this.#I(i,i.sub.id)}leave(e,t){const s=this.#O("leave",e);return s.leave.unsub=t,this.#I(s,s.leave.id)}createMessage(e,t,s){const i=this.#O("pub",e);let n="string"==typeof t?q().parse(t):t;return n&&!q().isPlainText(n)&&(i.pub.head={mime:q().getContentType()},t=n),i.pub.noecho=s,i.pub.content=t,i.pub}publish(e,t,s){return this.publishMessage(this.createMessage(e,t,s))}publishMessage(e,t){(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0;const s={pub:e};return t&&(s.extra={attachments:t.filter(e=>_(e))}),this.#I(s,e.id)}oobNotification(e){switch(this.logger("oob: "+(this._trimLongStrings?JSON.stringify(e,Q):e)),e.what){case"msg":if(!e.seq||e.seq<1||!e.topic)break;if(!this.isConnected())break;const t=this.#k("topic",e.topic);if(!t)break;if(t.isSubscribed())break;t.maxMsgSeq()<e.seq&&(t.isChannelType()&&t._updateReceived(e.seq,"fake-uid"),e.xfrom&&!this.#k("user",e.xfrom)&&this.getMeta(e.xfrom,(new V).withDesc().build()).catch(e=>{this.logger("Failed to get the name of a new sender",e)}),t.subscribe(null).then(e=>t.getMeta(new V(t).withLaterData(24).withLaterDel(24).build())).then(e=>{t.leaveDelayed(!1,1e3)}).catch(e=>{this.logger("On push data fetch failed",e)}).finally(e=>{this.getMeTopic()._refreshContact("msg",t)}));break;case"read":this.getMeTopic()._routePres({what:"read",seq:e.seq});break;case"sub":if(!this.isMe(e.xfrom))break;const s={given:e.modeGiven,want:e.modeWant},i=new n(s),r=i.mode&&i.mode!=n._NONE?{what:"acs",src:e.topic,dacs:s}:{what:"gone",src:e.topic};this.getMeTopic()._routePres(r);break;default:this.logger("Unknown push type ignored",e.what)}}getMeta(e,t){const s=this.#O("get",e);return s.get=w(s.get,t),this.#I(s,s.get.id)}setMeta(e,t){const s=this.#O("set",e),i=[];return t&&(["desc","sub","tags","cred","aux"].forEach(e=>{t.hasOwnProperty(e)&&(i.push(e),s.set[e]=t[e])}),Array.isArray(t.attachments)&&t.attachments.length>0&&(s.extra={attachments:t.attachments.filter(e=>_(e))})),0==i.length?Promise.reject(new Error("Invalid {set} parameters")):this.#I(s,s.set.id)}delMessages(e,t,s){const i=this.#O("del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,this.#I(i,i.del.id)}delTopic(e,t){const s=this.#O("del",e);return s.del.what="topic",s.del.hard=t,this.#I(s,s.del.id)}delSubscription(e,t){const s=this.#O("del",e);return s.del.what="sub",s.del.user=t,this.#I(s,s.del.id)}delCredential(e,t){const s=this.#O("del",h);return s.del.what="cred",s.del.cred={meth:e,val:t},this.#I(s,s.del.id)}delCurrentUser(e){const t=this.#O("del",null);return t.del.what="user",t.del.hard=e,this.#I(t,t.del.id).then(e=>{this._myUID=null})}note(e,t,s){if(s<=0||s>=u)throw new Error(`Invalid message id ${s}`);const i=this.#O("note",e);i.note.what=t,i.note.seq=s,this.#I(i)}noteKeyPress(e,t){const s=this.#O("note",e);s.note.what=t||"kp",this.#I(s)}videoCall(e,t,s,i){const n=this.#O("note",e);n.note.seq=t,n.note.what="call",n.note.event=s,n.note.payload=i,this.#I(n,n.note.id)}getTopic(e){let t=this.#k("topic",e);return!t&&e&&(t=e==h?new B:e==l?new W:new F(e),this.#D(t),t._cachePutSelf()),t}cacheGetTopic(e){return this.#k("topic",e)}cacheRemTopic(e){this.#j("topic",e)}mapTopics(e,t){this.#q("topic",e,t)}isTopicCached(e){return!!this.#k("topic",e)}newGroupTopicName(e){return(e?c:o)+this.getNextUniqueId()}getMeTopic(){return this.getTopic(h)}getFndTopic(){return this.getTopic(l)}getLargeFileHelper(){return new G(this,"0")}getCurrentUserID(){return this._myUID}isMe(e){return this._myUID===e}getCurrentLogin(){return this._login}getServerInfo(){return this._serverInfo}report(e,t){return this.publish("sys",q().attachJSON(null,{action:e,target:t}))}getServerParam(e,t){return this._serverInfo&&this._serverInfo[e]||t}enableLogging(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t}setHumanLanguage(e){e&&(this._humanLanguage=e)}isTopicOnline(e){const t=this.#k("topic",e);return t&&t.online}getTopicAccessMode(e){const t=this.#k("topic",e);return t?t.acs:null}wantAkn(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}return X.MESSAGE_STATUS_NONE=0,X.MESSAGE_STATUS_QUEUED=10,X.MESSAGE_STATUS_SENDING=20,X.MESSAGE_STATUS_FAILED=30,X.MESSAGE_STATUS_FATAL=40,X.MESSAGE_STATUS_SENT=50,X.MESSAGE_STATUS_RECEIVED=60,X.MESSAGE_STATUS_READ=70,X.MESSAGE_STATUS_TO_ME=80,X.DEL_CHAR=p,X.MAX_MESSAGE_SIZE="maxMessageSize",X.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",X.MIN_TAG_LENGTH="minTagLength",X.MAX_TAG_LENGTH="maxTagLength",X.MAX_TAG_COUNT="maxTagCount",X.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",X.REQ_CRED_VALIDATORS="reqCred",X.MSG_DELETE_AGE="msgDelAge",X.URI_TOPIC_ID_PREFIX="tinode:topic/",X.TAG_ALIAS=g,X.TAG_EMAIL="email:",X.TAG_PHONE="tel:",i}()});
2
+ //# sourceMappingURL=tinode.prod.js.map