PageSourceSearch

https://www.hukumku.id/_next/static/chunks/6225.1234c78491b13438.js

js hukumku.id collected 2026-10-09 01:54:30 UTC 80,963 bytes, 1 lines download raw bytes

1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6225],{66225:function(e){e.exports=(()=>{"use strict";let e,t,s,i,r,n,a;var o={767:e=>{let t="application/json",s=["act","height","duration","incoming","mime","name","premime","preref","preview","ref","size","state","url","val","width"],i=new Intl.Segmenter,r=[{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)/}],n=["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 h(e,t,s){if(!e)return null;try{let s=atob(e),i=s.length,r=new ArrayBuffer(i),n=new Uint8Array(r);for(let e=0;e<i;e++)n[e]=s.charCodeAt(e);return URL.createObjectURL(new Blob([r],{type:t}))}catch(e){s&&s("Drafty: failed to convert object.",e.message)}return null}function l(e,t){return e?"data:"+(t=t||"image/jpeg")+";base64,"+e:null}let c={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||h(e.val,e.mime,d.logger))+'">',close:e=>"</audio>",props:e=>e?{src:e.ref||h(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=>{let t=l(e._tempPreview,e.mime),s=h(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:l(e._tempPreview,e.mime)||e.ref||h(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=>{let t=l(e._tempPreview,e.mime),s=e.ref||h(e.preview,e.premime||"image/jpeg",d.logger);return'<img src="'+(t||s)+'"'+(e.width?' width="'+e.width+'"':"")+(e.height?' height="'+e.height+'"'
1:"")+' border="0" />'},close:e=>"",props:e=>{if(!e)return null;let t=e.preref||h(e.preview,e.premime||"image/jpeg",d.logger);return{src:t,"data-src":e.ref||h(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){if(!e)return null;let{txt:t,fmt:s,ent:i}=e="string"==typeof e?{txt:e}: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}]}let r=[],a=[];s.forEach(e=>{if(!e||"object"!=typeof e||!["undefined","number"].includes(typeof e.at)||!["undefined","number"].includes(typeof e.len))return;let s=0|e.at,n=0|e.len;if(n<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+n>M(t).length||(e.tp?r.push({type:e.tp,start:s,end:s+n}):i.length>0&&"object"==typeof i[o]&&r.push({start:s,end:s+n,key:o})))}),r.sort((e,t)=>{let s=e.start-t.start;return 0!=s||0!=(s=t.end-e.end)?s:n.indexOf(t.type)-n.indexOf(e.type)}),a.length>0&&r.push(...a),r.forEach(e=>{i.length>0&&!e.type&&i[e.key]&&"object"==typeof i[e.key]&&(e.type=i[e.key].tp,e.data=i[e.key].data),e.type||(e.type="HD")});let h=M(t);return m(function e(t,s,i,r,n){if(!n||0==n.length)return i<r&&p(t,{text:s.slice(i,r).map(e=>e.segment).join("")}),t;for(let r=0;r<n.length;r++){let a=n[r];if(a.start<0&&"EX"==a.type){p(t,{type:a.type,data:a.data,key:a.key,att:!0});continue}i<a.start&&(p(t,{text:s.slice(i,a.start).map(e=>e.segment).join("")}),i=a.start);let h=[];for(;r<n.length-1;){let e=n[r+1];if(e.start<0||!(e.start<a.end))break;if(e.end<=a.end){let t=o[e.tp]||{};(e.start<e.end||t.isVoid)&&h.push(e)}r++}p(t,e({type:a.type,data:a.data,key:a.key},s,i,a.end,h)),i=a.end}return i<r&&p(t,{text:s.slice(i,r).map(e=>e.segment).join("")}),t}({},h,0,h.length,r),function(e){if(Array.isArray(e.children)&&1==e.children.length){let t=e.children[0];if(e.type)t.type||t.children||(e.text=t.text,delete e.children);else{let s=e.parent;(e=t).parent=s}}return e})}function p(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}function g(e,t,s){if(!t)return e;e.txt=e.txt||"";let i=M(e.txt).length;if(t.text?e.txt+=t.text:Array.isArray(t.children)&&t.children.forEach(t=>{g(e,t,s)}),t.type){let r=M(e.txt).length-i;if(e.fmt=e.fmt||[],Object.keys(t.data||{}).length>0){e.ent=e.ent||[];let n=void 0===s[t.key]?e.ent.length:s[t.key];s[t.key]=n,e.ent[n]={tp:t.type,data:t.data},t.att?e.fmt.push({at:-1,len:0,key:n}):e.fmt.push({at:i,len:r,key:n})}else e.fmt.push({tp:t.type,at:i,len:r})}return e}function m(e,t,s){if(!e)return null;let i=t.call(s,e);if(!i||!i.children)return i;let r=[];for(let e in i.children){let n=i.children[e];n&&(n=m(n,t,s))&&r.push(n)}return 0==r.length?i.children=null:i.children=r,i}function f(e,t,s,i,r){if(!e)return null;i&&e.type&&i.push(e.type);let n=[];for(let s in e.children){let a=f(e.children[s],t,s,i,r);a&&n.push(a)}return 0==n.length&&(n=e.text?[e.text]:null),i&&e.type&&i.pop(),t.call(r,e.type,e.data,n,s,i)}function _(e,t,s){return e?(s&&(t-=s.length),m(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){let i=M(e.text);i.length>t?(e.text=i.slice(0,t).map(e=>e.segment).join("")+s,t=-1):t-=i.length}return e})):null}function b(e,t){return m(e,e=>{let s=w(e.data,!0,t?t(e):null);return s?e.data=s:delete e.data,e})}function v(e,s){if(!e)return null;if(e.att)e.text=" ",delete e.att,delete e.children;else if(e.children){let i=[],r=[];for(let n in e.children){let a=e.children[n];if(a.att){if(i.length==s||a.data.mime==t)continue;delete a.att,delete a.children,a.text=" ",i.push(a)}else r.push(a)}e.children=r.concat(i)}return e}function w(e,t,i){if(e&&Object.entries(e).length>0){i=i||[];let r={};if(s.forEach(s=>{!e[s]||t&&!i.includes(s)&&("string"==typeof e[s]||Array.isArray(e[s]))&&e[s].length>64||"object"==typeof e[s]||(r[s]=e[s])}),0!=Object.entries(r).length)return r}return null}function y(e,t,s){let r=function(e){let t=[],s=0,i=0;for(let{segment:r}of e){for(let e=0;e<r.length;e++)t[i+e]=s;i+=r.length,s++}return t}(t=t??i.segment(s)),n=r[e.at];return{at:n,len:(e.at+e.len<=s.length?r[e.at+e.len-1]-n:e.len)+1}}function M(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;let t=e.split(/\r?\n/),s=[],n={},o=[];
1t.forEach(e=>{let t,i,h=[];if(r.forEach(t=>{h=h.concat(function(e,t,s,i){let r=[],n=0,a=e.slice(0);for(;a.length>0;){let o=t.exec(a);if(null==o)break;let h=o.index+o[0].lastIndexOf(o[1]);a=a.slice(h+1),h+=n,n=h+1;let l=s?s.exec(a):null;if(null==l)break;let c=l.index+l[0].indexOf(l[1]);a=a.slice(c+1),c+=n,n=c+1,r.push({txt:e.slice(h+1,c),children:[],at:h,end:c,tp:i})}return r}(e,t.start,t.end,t.name))}),0==h.length)i={txt:e};else{h.sort((e,t)=>{let s=e.at-t.at;return 0!=s?s:t.end-e.end}),h=function e(t){if(0==t.length)return[];let s=[t[0]],i=t[0];for(let e=1;e<t.length;e++)t[e].at>i.end?(s.push(t[e]),i=t[e]):t[e].end<=i.end&&i.children.push(t[e]);for(let t in s)s[t].children=e(s[t].children);return s}(h);let t=function e(t,s){let i="",r=[];for(let n in t){let a=t[n];if(!a.txt){let t=e(a.children,i.length+s);a.txt=t.txt,r=r.concat(t.fmt)}a.tp&&r.push({at:i.length+s,len:a.txt.length,tp:a.tp}),i+=a.txt}return{txt:i,fmt:r}}(function e(t,s,i,r){let n=[];if(0==r.length)return[];for(let i in r){let a=r[i];a.at>s&&n.push({txt:t.slice(s,a.at)});let o={tp:a.tp},h=e(t,a.at+1,a.end,a.children);h.length>0?o.children=h:o.txt=a.txt,n.push(o),s=a.end+1}return s<i&&n.push({txt:t.slice(s,i)}),n}(e,0,e.length,h),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=>{let t=e.offset>i;return i=e.offset+e.len,t})}(i.txt)).length>0){let e=[];for(let i in t){let r=t[i],a=n[r.unique];a||(a=s.length,n[r.unique]=a,s.push({tp:r.type,data:r.data})),e.push({at:r.offset,len:r.len,key:a})}i.ent=e}o.push(i)});let h={txt:""};if(o.length>0){if(h.txt=o[0].txt,h.fmt=(o[0].fmt||[]).concat(o[0].ent||[]),h.fmt.length){let e=i.segment(h.txt);for(let t of h.fmt)({at:t.at,len:t.len}=y(t,e,h.txt))}for(let e=1;e<o.length;e++){let t=o[e],s=M(h.txt).length+1;h.fmt.push({tp:"BR",len:1,at:s-1});let r={};h.txt+=" "+t.txt,t.fmt&&(r=i.segment(t.txt),h.fmt=h.fmt.concat(t.fmt.map(e=>{let{at:i,len:n}=y(e,r,t.txt);return e.at=i+s,e.len=n,e}))),t.ent&&(0==Object.keys(r??{}).length&&(r=i.segment(t.txt)),h.fmt=h.fmt.concat(t.ent.map(e=>{let{at:i,len:n}=y(e,r,t.txt);return e.at=i+s,e.len=n,e})))}0==h.fmt.length&&delete h.fmt,s.length>0&&(h.ent=s)}return h},d.append=function(e,t){if(!e)return t;if(!t)return e;e.txt=e.txt||"";let s=M(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=>{let r={at:(0|i.at)+s,len:0|i.len};-1==i.at&&(r.at=-1,r.len=0),i.tp?r.tp=i.tp:(r.key=e.ent.length,e.ent.push(t.ent[i.key||0])),e.fmt.push(r)})),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});let 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});let 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});let 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){let s,i=((e||{}).fmt||[])[0];if(!i)return e;if("VC"==i.tp)delete i.tp,i.key=0,e.ent=[s={tp:"VC"}];else if(!(s=(e.ent||[])[0|i.key])||"VC"!=s.tp)return e;return s.data=s.data||{},Object.assign(s.data,t),e},d.quote=function(e,t,s){let i=d.append(d.appendLineBreak(d.mention(e,t)),s);return i.fmt.push({at:0,len:M(i.txt).length,tp:"QQ"}),i},d.mention=function(e,t){return{txt:e||"",fmt:[{at:0,len:M(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;let 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});let 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,r,n,a){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length<t+s||s<=0||-1==["url","pub"].indexOf(r)?null:"url"!=r||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:r,val:n,ref:a,name:i}}),e):null},d.appendButton=function(e,t,s,i,r,n){let a=(e=e||{txt:""}).txt.length;return e.txt+=t,d.insertButton(e,a,t.length,s,i,r,n)},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:M(e.txt).length,len:1,tp:"BR"}),e.txt+=" ",e},d.UNSAFE_toHTML=function(e){return f(u(e),function(e,t,s){let i=c[e],r=s?s.join(""):"";return i&&(r=i.open(t)+r+i.close(t)),r},0)},d.format=function(e,t,s){return f(u(e),t,0,[],s)},d.shorten=function(e,t,s){let i=u(e);return(i=_(i,t,"…"))&&s&&(i=b(i)),g({},i,[])},d.forwardedContent=function(e){let t=u(e);return g({},t=function e(t){if("BR"==t.type)t=null;else if(t.text)t.type||(t.text=t.text.trimStart(),t.text||(t=null));else if(!t.type&&t.children&&t.children.length>0){let s=e(t.children[0]);s?t.children[0]=s:(t.children.shift(),t.type||0!=t.children.length||(t=null))}return t}(t=m(t,function(e){return"MN"!=e.type||e.parent&&e.parent.type?e:null})),[])},d.replyContent=function(e,t){let s=u(e);return s?g({},s=b(s=_(s=v(s=m(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)}),3),t,"…"),e=>{switch(e.type){case"IM":return["val"];case"VD":return["preview"]}return null}),[]):e},d.preview=function(e,t,s){let i=u(e);if(i=_(i=m(i=v(i,3),function(e){return"MN"==e.type?e.parent&&e.parent.type||!(e.text||"").startsWith("➦")||(e.text="➦",delete e.children):"QQ"==e.type?(e.text=" ",delete e.children):"BR"==e.type&&(e.text=" ",delete e.children,delete e.type),e}),t,"…"),s){let e={IM:["val"],VD:["preview"]};i=b(i,t=>e[t.type])}else i=b(i);return g({},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 f(u(e),function(e,t,s){let i=o[e],r=s?s.join(""):"";return i&&(i.isVoid?r=i.md_tag||"":i.md_tag&&(r=i.md_tag+r+i.md_tag)),r},0)},d.isValid=function(e){if(!e)return!1;let{txt:t,fmt:s,ent:i}=e;if(!t&&""!==t&&!s&&!i)return!1;let r=typeof t;return("string"==r||"undefined"==r||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){let s=e.fmt[t];if(s&&s.at<0){let 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 r in e.fmt){let n=e.fmt[r];if(n&&n.at<0){let r=e.ent[0|n.key];if(r&&"EX"==r.tp&&r.data&&t.call(s,r.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){let r=e.fmt[i];if(r&&t.call(s,r.tp,r.at,r.len,r.key,i))break}},d.sanitizeEntities=function(e){if(e&&e.ent&&e.ent.length>0)for(let t in e.ent){let s=e.ent[t];if(s&&s.data){let i=w(s.data);i?e.ent[t].data=i:delete e.ent[t].data}}return e},d.getDownloadUrl=function(e){let s=null;return e.mime!=t&&e.val?s=h(e.val,e.mime,d.logger):"string"==typeof e.ref&&(s=e.ref),s},d.isProcessing=function(e){return!!e._processing},d.getPreviewUrl=function(e){return e.val?h(e.val,e.mime,d.logger):null},d.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0}
1,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&&c[e]&&c[e].props)return c[e].props(t)},d.getContentType=function(){return"text/x-drafty"},e.exports=d}},h={};function l(e){var t=h[e];if(void 0!==t)return t.exports;var s=h[e]={exports:{}};return o[e](s,s.exports,l),s.exports}l.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return l.d(t,{a:t}),t},l.d=(e,t)=>{for(var s in t)l.o(t,s)&&!l.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},l.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),l.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var c={};l.r(c),l.d(c,{AccessMode:()=>d,Drafty:()=>E(),Tinode:()=>I});class d{constructor(e){e&&(this.given="number"==typeof e.given?e.given:d.decode(e.given),this.want="number"==typeof e.want?e.want:d.decode(e.want),this.mode=e.mode?"number"==typeof e.mode?e.mode:d.decode(e.mode):this.given&this.want)}static #e(e,t,s){if(["given","want","mode"].includes(t=t||"mode"))return!!(e[t]&s);throw Error(`Invalid AccessMode component '${t}'`)}static decode(e){if(!e)return null;if("number"==typeof e)return e&d._BITMASK;if("N"===e||"n"===e)return d._NONE;let t={J:d._JOIN,R:d._READ,W:d._WRITE,P:d._PRES,A:d._APPROVE,S:d._SHARE,D:d._DELETE,O:d._OWNER},s=d._NONE;for(let i=0;i<e.length;i++){let r=t[e.charAt(i).toUpperCase()];r&&(s|=r)}return s}static encode(e){if(null===e||e===d._INVALID)return null;if(e===d._NONE)return"N";let t=["J","R","W","P","A","S","D","O"],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,r=t.split(/([-+])/);for(let t=1;t<r.length-1;t+=2){s=r[t];let n=d.decode(r[t+1]);if(n==d._INVALID)return e;null!=n&&("+"===s?i|=n:"-"===s&&(i&=~n))}e=i}else{let s=d.decode(t);s!=d._INVALID&&(e=s)}return e}static diff(e,t){return e=d.decode(e),t=d.decode(t),e==d._INVALID||t==d._INVALID?d._INVALID:e&~t}toString(){return'{"mode": "'+d.encode(this.mode)+'", "given": "'+d.encode(this.given)+'", "want": "'+d.encode(this.want)+'"}'}jsonHelper(){return{mode:d.encode(this.mode),given:d.encode(this.given),want:d.encode(this.want)}}setMode(e){return this.mode=d.decode(e),this}updateMode(e){return this.mode=d.update(this.mode,e),this}getMode(){return d.encode(this.mode)}setGiven(e){return this.given=d.decode(e),this}updateGiven(e){return this.given=d.update(this.given,e),this}getGiven(){return d.encode(this.given)}setWant(e){return this.want=d.decode(e),this}updateWant(e){return this.want=d.update(this.want,e),this}getWant(){return d.encode(this.want)}getMissing(){return d.encode(this.want&~this.given)}getExcessive(){return d.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 d.#e(this,e,d._OWNER)}isPresencer(e){return d.#e(this,e,d._PRES)}isMuted(e){return!this.isPresencer(e)}isJoiner(e){return d.#e(this,e,d._JOIN)}isReader(e){return d.#e(this,e,d._READ)}isWriter(e){return d.#e(this,e,d._WRITE)}isApprover(e){return d.#e(this,e,d._APPROVE)}isAdmin(e){return this.isOwner(e)||this.isApprover(e)}isSharer(e){return this.isAdmin(e)||d.#e(this,e,d._SHARE)}isDeleter(e){return d.#e(this,e,d._DELETE)}}d._NONE=0,d._JOIN=1,d._READ=2,d._WRITE=4,d._PRES=8,d._APPROVE=16,d._SHARE=32,d._DELETE=64,d._OWNER=128,d._BITMASK=d._JOIN|d._READ|d._WRITE|d._PRES|d._APPROVE|d._SHARE|d._DELETE|d._OWNER,d._INVALID=1048576;let u="0.23.1",p="tinodejs/"+u;class g extends Error{constructor(e,t){super(`${e} (${t})`),this.name="CommError",this.code=t}}function m(e,t){if("string"==typeof t&&t.length>=20&&t.length<=24&&["ts","touched","updated","created","when","deleted","expires"].includes(e)){let e=new Date(t);if(!isNaN(e))return e}else if("acs"===e&&"object"==typeof t)return new d(t);return t}function f(e){return e&&!/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.test(e)}function _(e){return e instanceof Date&&!isNaN(e)&&0!=e.getTime()}function b(e,t,s){if("object"!=typeof t){if(void 0===t)return e;if("␡"===t)return;return t}if(null===t)return t;if(t instanceof Date&&!isNaN(t))return!e||!(e instanceof Date)||isNaN(e)||e<t?t:e;if(t instanceof d)return new d(t);if(t instanceof Array)return t;for(let i in e&&"␡"!==e||(e=t.constructor()),t)if(t.hasOwnProperty(i)&&(!s||!s[i])&&"_noForwarding"!=i)try{e[i]=b(e[i],t[i])}catch(e){}return e}function v(e,t,s,i){return e[t]=b(e[t],s,i),e[t]}let w="Connection failed",y="Disconnected by client";function M(e,t,s,i){let r=null;return["http","https","ws","wss"].includes(t)&&("/"!==(r=`${t}://${e}`).charAt(r.length-1)&&(r+="/"),r+="v"+s+"/channels",["http","https"].includes(t)&&(r+="/lp"),r+="?apikey="+i),r}class T{static #t=e=>{};#s=null;#i=0;#r=!1;#n=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 T.#t("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'."),Error("Unknown or invalid network transport. Running under Node? Call 'Tinode.setNetworkProviders()'.")}static setNetworkProviders(s,i){e=s,t=i}static set logger(e){T.#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.#h()}#l(){clearTimeout(this.#s);let 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(T.#t(`Reconnecting, iter=${this.#i}, timeout=${e}`),this.#r)this.onAutoreconnectIteration&&this.onAutoreconnectIteration(-1);else{let e=this.connect();this.onAutoreconnectIteration?this.onAutoreconnectIteration(0,e):e.catch(e=>{})}},e)}#c(){clearTimeout(this.#s),this.#s=null}#h(){this.#i=0}#a(){let e=null,s=null,i=null,r=(s,i,n)=>{let a=new t,o=!1;return a.onreadystatechange=t=>{if(4==a.readyState)if(201==a.status)(a=r(e=s+"&sid="+JSON.parse(a.responseText,m).ctrl.params.sid)).send(null),this.onOpen&&this.onOpen(),i&&(o=!0,i()),this.autoreconnect&&this.#c();else if(a.status>0&&a.status<400)this.onMessage&&this.onMessage(a.responseText),(a=r(e)).send(null);else{if(n&&!o&&(o=!0,n(a.responseText)),this.onMessage&&a.responseText&&this.onMessage(a.responseText),this.onDisconnect){let e=a.status||(this.#r?418:503),t=a.responseText||(this.#r?y:w);this.onDisconnect(new g(t,e),e)}a=null,!this.#r&&this.autoreconnect&&this.#l()}},a.open("POST",s,!0),a};this.connect=(e,t)=>
1{if(this.#r=!1,s){if(!t)return Promise.resolve();s.onreadystatechange=void 0,s.abort(),s=null}return e&&(this.host=e),new Promise((e,t)=>{let i=M(this.host,this.secure?"https":"http",this.version,this.apiKey);T.#t("LP connecting to:",i),(s=r(i,e,t)).send(null)}).catch(e=>{T.#t("LP connection failed:",e)})},this.reconnect=e=>{this.#c(),this.connect(null,e)},this.disconnect=t=>{this.#r=!0,this.#c(),i&&(i.onreadystatechange=void 0,i.abort(),i=null),s&&(s.onreadystatechange=void 0,s.abort(),s=null),this.onDisconnect&&this.onDisconnect(new g(y,418),418),e=null},this.sendText=s=>{if(!(i=(e=>{let s=new t;return s.onreadystatechange=e=>{if(4==s.readyState&&s.status>=400)throw new g("LP sender failed",s.status)},s.open("POST",e,!0),s})(e))||1!=i.readyState)throw Error("Long poller failed to connect");i.send(s)},this.isConnected=e=>s&&!0}#o(){this.connect=(t,s)=>{if(this.#r=!1,this.#n){if(!s&&this.#n.readyState==this.#n.OPEN)return this.probe(),Promise.resolve();this.#n.close(),this.#n=null}return t&&(this.host=t),new Promise((t,s)=>{let i=M(this.host,this.secure?"wss":"ws",this.version,this.apiKey);T.#t("WS connecting to: ",i);let r=new e(i);r.onerror=e=>{s(e)},r.onopen=e=>{this.autoreconnect&&this.#c(),this.onOpen&&this.onOpen(),t()},r.onclose=e=>{if(this.#n=null,this.onDisconnect){let e=this.#r?418:503;this.onDisconnect(new g(this.#r?y:w,e),e)}!this.#r&&this.autoreconnect&&this.#l()},r.onmessage=e=>{this.onMessage&&this.onMessage(e.data)},this.#n=r})},this.reconnect=e=>{this.#c(),this.connect(null,e)},this.disconnect=e=>{this.#r=!0,this.#c(),this.#n&&(this.#n.close(),this.#n=null)},this.sendText=e=>{if(!this.#n||this.#n.readyState!=this.#n.OPEN)throw Error("Websocket is not connected");this.#n.send(e)},this.isConnected=e=>this.#n&&this.#n.readyState==this.#n.OPEN}onMessage=void 0;onDisconnect=void 0;onOpen=void 0;onAutoreconnectIteration=void 0}T.NETWORK_ERROR=503,T.NETWORK_ERROR_TEXT=w,T.NETWORK_USER=418,T.NETWORK_USER_TEXT=y;let x="tinode-web";class S{#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,r)=>{let n=this.db.transaction([e]);n.onerror=t=>{this.#u("PCache","mapObjects",e,t.target.error),r(t.target.error)},n.objectStore(e).getAll().onsuccess=e=>{t&&e.target.result.forEach(e=>{t.call(s,e)}),i(e.target.result)}}):disabled?Promise.resolve([]):Promise.reject(Error("not initialized"))}initDatabase(){return new Promise((e,t)=>{let i=s.open(x,1);i.onsuccess=t=>{this.db=t.target.result,this.disabled=!1,e(this.db)},i.onerror=e=>{this.#u("PCache","failed to initialize",e),t(e.target.error),this.#d(e.target.error)},i.onupgradeneeded=e=>{this.db=e.target.result,this.db.onerror=e=>{this.#u("PCache","failed to create storage",e),this.#d(e.target.error)},this.db.createObjectStore("topic",{keyPath:"name"}),this.db.createObjectStore("user",{keyPath:"uid"}),this.db.createObjectStore("subscription",{keyPath:["topic","uid"]}),this.db.createObjectStore("message",{keyPath:["topic","seq"]})}})}deleteDatabase(){return this.db&&(this.db.close(),this.db=null),new Promise((e,t)=>{let i=s.deleteDatabase(x);i.onblocked=e=>{this.db&&this.db.close();let s=Error("blocked");this.#u("PCache","deleteDatabase",s),t(s)},i.onsuccess=t=>{this.db=null,this.disabled=!0,e(!0)},i.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)=>{let 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)};let r=i.objectStore("topic").get(e.name);r.onsuccess=t=>{i.objectStore("topic").put(S.#g(r.result,e)),i.commit()}}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}markTopicAsDeleted(e,t){return this.isReady()?new Promise((s,i)=>{let r=this.db.transaction(["topic"],"readwrite");r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{this.#u("PCache","markTopicAsDeleted",e.target.error),i(e.target.error)},r.objectStore("topic").get(e).onsuccess=e=>{let s=e.target.result;s&&s._deleted!=t&&(s._deleted=t,r.objectStore("topic").put(s)),r.commit()}}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}remTopic(e){return this.isReady()?new Promise((t,s)=>{let 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(Error("not initialized"))}mapTopics(e,t){return this.#p("topic",e,t)}deserializeTopic(e,t){S.#m(e,t)}updUser(e,t){if(!(arguments.length<2||void 0===t))return this.isReady()?new Promise((s,i)=>{let r=this.db.transaction(["user"],"readwrite");r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{this.#u("PCache","updUser",e.target.error),i(e.target.error)},r.objectStore("user").put({uid:e,public:t}),r.commit()}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}remUser(e){return this.isReady()?new Promise((t,s)=>{let 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(Error("not initialized"))}mapUsers(e,t){return this.#p("user",e,t)}getUser(e){return this.isReady()?new Promise((t,s)=>{let i=this.db.transaction(["user"]);i.oncomplete=e=>{let 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(Error("not initialized"))}updSubscription(e,t,s){return this.isReady()?new Promise((i,r)=>{let n=this.db.transaction(["subscription"],"readwrite");n.oncomplete=e=>{i(e.target.result)},n.onerror=e=>
1{this.#u("PCache","updSubscription",e.target.error),r(e.target.error)},n.objectStore("subscription").get([e,t]).onsuccess=i=>{n.objectStore("subscription").put(S.#f(i.target.result,e,t,s)),n.commit()}}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}mapSubscriptions(e,t,s){return this.isReady()?new Promise((i,r)=>{let n=this.db.transaction(["subscription"]);n.onerror=e=>{this.#u("PCache","mapSubscriptions",e.target.error),r(e.target.error)},n.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(Error("not initialized"))}addMessage(e){return this.isReady()?new Promise((t,s)=>{let 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(S.#_(null,e)),i.commit()}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}updMessageStatus(e,t,s){return this.isReady()?new Promise((i,r)=>{let n=this.db.transaction(["message"],"readwrite");n.onsuccess=e=>{i(e.target.result)},n.onerror=e=>{this.#u("PCache","updMessageStatus",e.target.error),r(e.target.error)};let a=n.objectStore("message").get(IDBKeyRange.only([e,t]));a.onsuccess=i=>{let r=a.result||i.target.result;r&&r._status!=s&&n.objectStore("message").put(S.#_(r,{topic:e,seq:t,_status:s})),n.commit()}}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}remMessages(e,t,s){return this.isReady()?new Promise((i,r)=>{t||s||(t=0,s=Number.MAX_SAFE_INTEGER);let n=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),r(e.target.error)},a.objectStore("message").delete(n),a.commit()}):this.disabled?Promise.resolve():Promise.reject(Error("not initialized"))}readMessages(e,t,s,i){return this.isReady()?new Promise((r,n)=>{let a=(t=t||{}).since>0?t.since:0,o=t.before>0?t.before:Number.MAX_SAFE_INTEGER,h=0|t.limit,l=[],c=IDBKeyRange.bound([e,a],[e,o],!1,!0),d=this.db.transaction(["message"]);d.onerror=e=>{this.#u("PCache","readMessages",e.target.error),n(e.target.error)},d.objectStore("message").openCursor(c,"prev").onsuccess=e=>{let t=e.target.result;t?(s&&s.call(i,t.value),l.push(t.value),h<=0||l.length<h?t.continue():r(l)):r(l)}}):this.disabled?Promise.resolve([]):Promise.reject(Error("not initialized"))}static #b=["created","updated","deleted","read","recv","seq","clear","defacs","creds","public","trusted","private","touched","_deleted"];static #m(e,t){S.#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){let s=e||{name:t.name};return S.#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){let r=e||{topic:t,uid:s};return["updated","mode","read","recv","clear","lastSeen","userAgent"].forEach(e=>{i.hasOwnProperty(e)&&(r[e]=i[e])}),r}static #_(e,t){let s=e||{};return["topic","seq","ts","_status","from","head","content"].forEach(e=>{t.hasOwnProperty(e)&&(s[e]=t[e])}),s}static setDatabaseProvider(e){s=e}}var P=l(767),E=l.n(P);class A{constructor(e,t){this._tinode=e,this._version=t,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this.xhr=[]}uploadWithBaseUrl(e,t,s,r,n,a){let o=`/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 Error(`Invalid base URL '${e}'`);o=t+o}let h=this,l=new i;this.xhr.push(l),l.open("POST",o,!0),l.setRequestHeader("X-Tinode-APIKey",this._apiKey),this._authToken&&l.setRequestHeader("X-Tinode-Auth",`Token ${this._authToken.token}`);let c=null,d=null,u=new Promise((e,t)=>{c=e,d=t});l.upload.onprogress=e=>{e.lengthComputable&&(r&&r(e.loaded/e.total),this.onProgress&&this.onProgress(e.loaded/e.total))},l.onload=function(){let e;try{e=JSON.parse(this.response,m)}catch(t){h._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}this.status>=200&&this.status<300?(c&&c(e.ctrl.params.url),n&&n(e.ctrl)):this.status>=400?(d&&d(new g(e.ctrl.text,e.ctrl.code)),a&&a(e.ctrl)):h._tinode.logger("ERROR: Unexpected server response status",this.status,this.response)},l.onerror=function(e){d&&d(e||Error("failed")),a&&a(null)},l.onabort=function(e){d&&d(Error("upload cancelled by user")),a&&a(null)};try{let e=new FormData;e.append("file",t),e.set("id",this._tinode.getNextUniqueId()),s&&e.set("topic",s),l.send(e)}catch(e){d&&d(e),a&&a(null)}return u}upload(e,t,s,i,r){let n=(this._tinode._secure?"https://":"http://")+this._tinode._host;return this.uploadWithBaseUrl(n,e,t,s,i,r)}download(e,t,s,r,n){if(!f(e))return void(n&&n(`The URL '${e}' must be relative, not absolute`));if(!this._authToken)return void(n&&n("Must authenticate first"));let a=this,o=new i;this.xhr.push(o),e=function(e,t,s){let i=new URL(e,window.location.origin);return i.searchParams.append(t,"1"),i.toString().substring(window.location.origin.length)}
1(e,"asatt",0),o.open("GET",e,!0),o.setRequestHeader("X-Tinode-APIKey",this._apiKey),o.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),o.responseType="blob",o.onprogress=function(e){r&&r(e.loaded)};let h=null,l=null,c=new Promise((e,t)=>{h=e,l=t});o.onload=function(){if(200==this.status){let 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),h&&h()}else if(this.status>=400&&l){let e=new FileReader;e.onload=function(){try{let e=JSON.parse(this.result,m);l(new g(e.ctrl.text,e.ctrl.code))}catch(e){a._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),l(e)}},e.readAsText(this.response)}},o.onerror=function(e){l&&l(Error("failed")),n&&n(e)},o.onabort=function(){l&&l(null)};try{o.send()}catch(e){l&&l(e),n&&n(e)}return c}cancel(){this.xhr.forEach(e=>{e.readyState<4&&e.abort()})}static setNetworkProvider(e){i=e}}class D{constructor(e){this.topic=e,this.what={}}#v(){return this.topic._deleted?void 0:this.topic.updated}#w(){return this.topic.isP2PType()?this.#v():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)}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.#v())}withSub(e,t,s){let 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.#w(),e)}withTags(){return this.what.tags=!0,this}withCred(){return"me"==this.topic.getType()?this.what.cred=!0:this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds",this.topic.getType()),this}withDel(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this}withLaterDel(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)}extract(e){return this.what[e]}build(){let e=[],t={};return["data","sub","desc","tags","cred","del"].forEach(s=>{this.what.hasOwnProperty(s)&&(e.push(s),Object.getOwnPropertyNames(this.what[s]).length>0&&(t[s]=this.what[s]))}),e.length>0?t.what=e.join(" "):t=void 0,t}}class N{#y=void 0;#M=!1;buffer=[];constructor(e,t){this.#y=e||((e,t)=>e===t?0:e<t?-1:1),this.#M=t}#T(e,t,s){let i=0,r=t.length-1,n=0,a=0,o=!1;for(;i<=r;)if(n=(i+r)/2|0,(a=this.#y(t[n],e))<0)i=n+1;else{if(!(a>0)){o=!0;break}r=n-1}return o?{idx:n,exact:!0}:s?{idx:-1}:{idx:a<0?n+1:n}}#x(e,t){let s=this.#T(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|=0,this.buffer.length>e?this.buffer[this.buffer.length-1-e]:void 0}put(){let e;for(let t in e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments)this.#x(e[t],this.buffer)}delAt(e){e|=0;let t=this.buffer.splice(e,1);if(t&&t.length>0)return t[0]}delRange(e,t){return this.buffer.splice(e,t-e)}length(){return this.buffer.length}reset(){this.buffer=[]}forEach(e,t,s,i){t|=0,s=s||this.buffer.length;for(let r=t;r<s;r++)e.call(i,this.buffer[r],r>t?this.buffer[r-1]:void 0,r<s-1?this.buffer[r+1]:void 0,r)}find(e,t){let{idx:s}=this.#T(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 R{constructor(e,t){this._tinode=null,this.name=e,this.created=null,this.updated=null,this.touched=new Date(0),this.acs=new d(null),this.private=null,this.public=null,this.trusted=null,this._users={},this._queuedSeqId=0xfffffff,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._recvNotificationTimer=null,this._tags=[],this._credentials=[],this._messageVersions={},this._messages=new N((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.onDeleteTopic=t.onDeleteTopic,this.onAllMessagesReceived=t.onAllMessagesReceived)}
1static topicType(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"]}static isMeTopicName(e){return"me"==R.topicType(e)}static isGroupTopicName(e){return"grp"==R.topicType(e)}static isP2PTopicName(e){return"p2p"==R.topicType(e)}static isCommTopicName(e){return R.isP2PTopicName(e)||R.isGroupTopicName(e)}static isNewGroupTopicName(e){return"string"==typeof e&&("new"==e.substring(0,3)||"nch"==e.substring(0,3))}static isChannelTopicName(e){return"string"==typeof e&&("chn"==e.substring(0,3)||"nch"==e.substring(0,3))}isSubscribed(){return this._attached}subscribe(e,t){return clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=null,this._attached?Promise.resolve(this):this._tinode.subscribe(this.name||"new",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,"me"!=this.name&&"fnd"!=this.name){let 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(Error("Cannot publish on inactive topic"));if(this._sending)return Promise.reject(Error("The message is already being sent"));e._sending=!0,e._failed=!1;let t=null;return E().hasEntities(e.content)&&(t=[],E().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){let 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 g&&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(Error("Cannot leave inactive topic"))}leaveDelayed(e,t){clearTimeout(this._delayedLeaveTimer),this._delayedLeaveTimer=setTimeout(t=>{this._delayedLeaveTimer=null,this.leave(e)},t)}getMeta(e){return this._tinode.getMeta(this.name,e)}getMessagesPage(e,t){let s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);return this._loadMessages(this._tinode._db,s.extract("data")).then(i=>{if(i==e)return Promise.resolve({topic:this.name,code:200,params:{count:i}});e-=i,s=t?this.startMetaQuery().withLaterData(e):this.startMetaQuery().withEarlierData(e);let r=this.getMeta(s.build());return t||(r=r.then(e=>{e&&e.params&&!e.params.count&&(this._noEarlierMsgs=!0)})),r})}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()).length>1&&t.push(i)}t.sort().filter(function(e,t,s){return!t||e!=s[t-1]})}return 0==t.length&&t.push("␡"),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)),t))}updateMode(e,t){let 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||"␡"}}})}delMessages(e,t){if(!this._attached)return Promise.reject(Error("Cannot delete messages in inactive topic"));e.sort((e,t)=>
1e.low<t.low||e.low==t.low&&(!t.hi||e.hi>=t.hi));let s=e.reduce((e,t)=>(t.low<0xfffffff&&(!t.hi||t.hi<0xfffffff?e.push(t):e.push({low:t.low,hi:this._maxSeq+1})),e),[]);return(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.forEach(e=>{e.hi?this.flushMessageRange(e.low,e.hi):this.flushMessage(e.low)}),this.onData&&this.onData(),t))}delMessagesAll(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)}delMessagesList(e,t){e.sort((e,t)=>e-t);let s=e.reduce((e,t)=>{if(0==e.length)e.push({low:t});else{let s=e[e.length-1];!s.hi&&t!=s.low+1||t>s.hi?e.push({low:t}):s.hi=s.hi?Math.max(s.hi,t+1):t+1}return e},[]);return this.delMessages(s,t)}delMessagesEdits(e,t){let 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(Error("Cannot delete subscription in inactive topic"))}note(e,t){if(!this._attached)return;let s=this._users[this._tinode.getCurrentUserID()],i=!1;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,r=!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),r=i!=this.recv;break;case"read":i=this.read,this.read=Math.max(this.read,t),r=i!=this.read;break;case"msg":i=this.seq,this.seq=Math.max(this.seq,t),(!this.touched||this.touched<s)&&(this.touched=s),r=i!=this.seq}return this.recv<this.read&&(this.recv=this.read,r=!0),this.seq<this.recv&&(this.seq=this.recv,(!this.touched||this.touched<s)&&(this.touched=s),r=!0),this.unread=this.seq-this.read,r}userDesc(e){let t=this._cacheGetUser(e);if(t)return t}p2pPeerDesc(){if(this.isP2PType())return this._users[this.name]}subscribers(e,t){let s=e||this.onMetaSub;if(s)for(let e in this._users)s.call(t,this._users[e],e,this._users)}tags(){return this._tags.slice(0)}subscriber(e){return this._users[e]}messageVersions(e,t,s){if(!t)return;let i=this._messageVersions[e];i&&i.forEach(t,void 0,void 0,s)}messages(e,t,s,i){let r=e||this.onData;if(r){let e="number"==typeof t?this._messages.find({seq:t},!0):void 0,n="number"==typeof s?this._messages.find({seq:s},!0):void 0;if(-1!=e&&-1!=n){let t=[];this._messages.forEach((e,s,i,r)=>{if(this._isReplacementMsg(e))return;let n=this.latestMsgVersion(e.seq)||e;n._origTs||(n._origTs=n.ts,n._origSeq=n.seq,n.ts=e.ts,n.seq=e.seq),t.push({data:n,idx:r})},e,n,{}),t.forEach((e,s)=>{r.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){let t=this._messages.find({seq:e});if(t>=0)return this._messages.getAt(t)}latestMessage(){return this._messages.getLast()}latestMsgVersion(e){let 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 Error("Callback must be provided");this.messages(e,0xfffffff,void 0,t)}msgReceiptCount(e,t){let s=0;if(t>0){let i=this._tinode.getCurrentUserID();for(let r in this._users){let n=this._users[r];n.user!==i&&n[e]>
1=t&&s++}}return s}msgReadCount(e){return this.msgReceiptCount("read",e)}msgRecvCount(e){return this.msgReceiptCount("recv",e)}msgHasMoreMessages(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs}isNewMessage(e){return this._maxSeq<=e}flushMessage(e){let 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];let s=this._messages.find({seq:e},!0);return s>=0?this._messages.delRange(s,this._messages.find({seq:t},!0)):[]}swapMessageId(e,t){let 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){let t=this._messages.find({seq:e});if(t>=0){let 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 R.topicType(this.name)}getAccessMode(){return this.acs}setAccessMode(e){return this.acs=new d(e)}getDefaultAccess(){return this.defacs}startMetaQuery(){return new D(this)}isArchived(){return this.private&&!!this.private.arch}isMeType(){return R.isMeTopicName(this.name)}isChannelType(){return R.isChannelTopicName(this.name)}isGroupType(){return R.isGroupTopicName(this.name)}isP2PType(){return R.isP2PTopicName(this.name)}isCommType(){return R.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>=0xfffffff?s=10:this.msgReadCount(e.seq)>0?s=70:this.msgRecvCount(e.seq)>0?s=60:e.seq>0&&(s=50):s=80,t&&e._status!=s&&(e._status=s,this._tinode._db.updMessageStatus(this.name,e.seq,s)),s}_isReplacementMsg(e){return e.head&&e.head.replace}_maybeUpdateMessageVersionsCache(e){if(!this._isReplacementMsg(e))return void(this._messageVersions[e.seq]&&(this._messageVersions[e.seq].filter(t=>t.from==e.from),this._messageVersions[e.seq].isEmpty()&&delete this._messageVersions[e.seq]));let t=parseInt(e.head.replace.split(":")[1]);if(t>e.seq)return;let s=this.findMessage(t);if(s&&s.from!=e.from)return;let i=this._messageVersions[t]||new N((e,t)=>e.seq-t.seq,!0);i.put(e),this._messageVersions[t]=i}
1_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);let t=!this.isChannelType()&&!e.from||this._tinode.isMe(e.from);e.head&&e.head.webrtc&&e.head.mime==E().getContentType()&&e.content&&(e.content=E().updateVideoCall(e.content,{state:e.head.webrtc,duration:e.head["webrtc-duration"],incoming:!t})),e._noForwarding||(this._messages.put(e),this._tinode._db.addMessage(e),this._maybeUpdateMessageVersionsCache(e)),this.onData&&this.onData(e);let 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),this.onMeta&&this.onMeta(e)}_routePres(e){let t,s;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":(t=this._users[e.src])?t.online="on"==e.what:this._tinode.logger("WARNING: Presence update for an unknown user",this.name,e.src);break;case"term":this._resetSub();break;case"upd":e.src&&!this._tinode.isTopicCached(e.src)&&this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build());break;case"acs":if(s=e.src||this._tinode.getCurrentUserID(),t=this._users[s])t.acs.updateAll(e.dacs),this._processMetaSubs([{user:s,updated:new Date,acs:t.acs}]);else{let i=(new d).updateAll(e.dacs);i&&i.mode!=d._NONE&&((t=this._cacheGetUser(s))?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":let t=this._users[e.from];t&&(t[e.what]=e.seq,t.recv<t.read&&(t.recv=t.read));let 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)),b(this,e),this._tinode._db.updTopic(this),"me"!==this.name&&!e._noForwarding){let 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){let 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._tinode.isMe(s.user)&&s.acs&&this._processMetaDesc({updated:s.updated,touched:s.touched,acs:s.acs}),i=this._updateCachedUser(s.user,s)),this.onMetaSub&&this.onMetaSub(i)}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))}_processMetaTags(e){1==e.length&&"␡"==e[0]&&(e=[]),this._tags=e,this.onTagsUpdated&&this.onTagsUpdated(e)}_processMetaCreds(e){}_processDelMessages(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);let s=this,i=0;Array.isArray(t)&&t.forEach(function(e){if(e.hi)for(let t=e.low;t<e.hi;t++)i++,s.flushMessage(t);else i++,s.flushMessage(e.low)}),i>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 d(null),this.private=null,this.public=null,this.trusted=null,this._maxSeq=0,this._minSeq=0,this._attached=!1;let e=this._tinode.getMeTopic();e&&e._routePres({_noForwarding:!0,what:"gone",topic:"me",src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()}_updateCachedUser(e,t){let s=this._cacheGetUser(e);return s=b(s||{},t),this._cachePutUser(e,s),v(this._users,e,s)}_getQueuedSeqId(){return this._queuedSeqId++}_loadMessages(e,t){let{since:s,before:i,limit:r}=t||{};return e.readMessages(this.name,{since:s,before:i,limit:r||24}).then(e=>
1(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)}),e.length))}_updateReceived(e,t){this.touched=new Date,this.seq=0|e,t&&!this._tinode.isMe(t)||(this.read=this.read?Math.max(this.read,this.seq):this.seq,this.recv=this.recv?Math.max(this.read,this.recv):this.read),this.unread=this.seq-(0|this.read),this._tinode._db.updTopic(this)}}class k extends R{onContactUpdate;constructor(e){super("me",e),e&&(this.onContactUpdate=e.onContactUpdate)}_processMetaDesc(e){let t=e.acs&&!e.acs.isPresencer()&&this.acs&&this.acs.isPresencer();b(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=>{let s=e.topic;if("fnd"==s||"me"==s)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);let t=this._tinode.getTopic(s);t._new&&delete t._new,i=b(t,e),this._tinode._db.updTopic(i),R.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){let s=[];e.forEach(e=>{s.push(e.topic)}),this.onSubsUpdated(s,t)}}_processMetaCreds(e,t){1==e.length&&"␡"==e[0]&&(e=[]),t?e.forEach(e=>{if(e.val){let t=this._credentials.findIndex(t=>t.meth==e.meth&&t.val==e.val);t<0?(e.done||(t=this._credentials.findIndex(t=>t.meth==e.meth&&!t.done))>=0&&this._credentials.splice(t,1),this._credentials.push(e)):this._credentials[t].done=e.done}else if(e.resp){let 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&&"me"==e.src)return void this.getMeta(this.startMetaQuery().withDesc().build());let 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 d).updateAll(e.dacs),t.touched=new Date);break;case"ua":t.seen={when:new Date,ua:e.ua};break;
1case"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){let t=new d(e.dacs);if(!t||t.mode==d._INVALID)return void this._tinode.logger("ERROR: Invalid access mode update",e.src,e.dacs);if(t.mode==d._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());let s=this._tinode.getTopic(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());let 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(Error("Publishing to 'me' is not supported"))}delCredential(e,t){return this._attached?this._tinode.delCredential(e,t).then(s=>{let 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(Error("Cannot delete credential in inactive 'me' topic"))}contacts(e,t,s){this._tinode.mapTopics((i,r)=>{i.isCommType()&&(!t||t(i))&&e.call(s,i,r)})}getContact(e){return this._tinode.cacheGetTopic(e)}getAccessMode(e){if(e){let t=this._tinode.cacheGetTopic(e);return t?t.acs:null}return this.acs}isArchived(e){let t=this._tinode.cacheGetTopic(e);return t&&t.private&&!!t.private.arch}getCredentials(){return this._credentials}}class C extends R{_contacts={};constructor(e){super("fnd",e)}_processMetaSubs(e){let t=Object.getOwnPropertyNames(this._contacts).length;for(let s in this._contacts={},e){let i=e[s],r=i.topic?i.topic:i.user;i=v(this._contacts,r,i),t++,this.onMetaSub&&this.onMetaSub(i)}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))}publish(){return Promise.reject(Error("Publishing to 'fnd' is not supported"))}setMeta(e){return Object.getPrototypeOf(C.prototype).setMeta.call(this,e).then(e=>{Object.keys(this._contacts).length>0&&(this._contacts={},this.onSubsUpdated&&this.onSubsUpdated([]))})}contacts(e,t){let s=e||this.onMetaSub;if(s)for(let e in this._contacts)s.call(t,this._contacts[e],e,this._contacts)}}function U(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)}))}function q(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))return;let 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 d)t=t.jsonHelper();else if(null==t||!1===t||Array.isArray(t)&&0==t.length||"object"==typeof t&&0==Object.keys(t).length)return;return t}(0,t)}"undefined"!=typeof WebSocket&&(r=WebSocket),"undefined"!=typeof XMLHttpRequest&&(n=XMLHttpRequest),"undefined"!=typeof indexedDB&&(a=indexedDB),function(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";"undefined"==typeof btoa&&(l.g.btoa=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s="";for(let i,r=0,n=0,a=e;t.charAt(0|n)||(a="=",n%1);s+=a.charAt(63&r>>8-n%1*8)){if((i=t.charCodeAt(n+=3/4))>255)throw Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");r=r<<8|i}return s}),"undefined"==typeof atob&&(l.g.atob=function(){let t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").replace(/=+$/,""),s="";if(t.length%4==1)throw Error("'atob' failed: The string to be decoded is not correctly encoded.");for(let i,r=0,n=0,a=0;i=t.charAt(a++);~i&&(n=r%4?64*n+i:i,r++%4)&&(s+=String.fromCharCode(255&n>>(-2*r&6))))i=e.indexOf(i);return s}),"undefined"==typeof window&&(l.g.window={WebSocket:r,XMLHttpRequest:n,indexedDB:a,URL:{createObjectURL:function(){throw Error("Unable to use URL.createObjectURL in a non-browser application")}}}),T.setNetworkProviders(r,n),A.setNetworkProvider(n),S.setDatabaseProvider(a)}();class I{_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; ");
1let r=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(r){let t=["edg","chrome","safari","mobile","version"],i,n=e.substr(r.index+r[0].length).split(" "),a=[];for(let e=0;e<n.length;e++){let s=/([\w.]+)[\/]([\.\d]+)/.exec(n[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=r[1]}else s=/firefox/i.test(e)?(r=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+r[1]:"Firefox/?":(r=/([\w.]+)\/([.\d]+)/.exec(e))?r[1]+"/"+r[2]:(r=e.split(" "))[0];if((r=s.split("/")).length>1){let e=r[1].split("."),t=e[1]?"."+e[1].substr(0,2):"";s=`${r[0]}/${e[0]}${t}`}return i+s}(navigator.userAgent,navigator.product),this._hwos=navigator.platform,this._humanLanguage=navigator.language||"en-US"),T.logger=this.logger,E().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 T(e,"0",!0),this._connection.onMessage=e=>{this.#S(e)},this._connection.onOpen=e=>this.#P(),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 S(e=>{this.logger("DB",e)},this.logger),this._persist){let e=[];this._db.initDatabase().then(t=>this._db.mapTopics(t=>{let s=this.#A("topic",t.name);s||(s="me"==t.name?new k:"fnd"==t.name?new C:new R(t.name),this._db.deserializeTopic(s,t),this.#D(s),s._cachePutSelf(),delete s._new,e.push(s._loadMessages(this._db)))})).then(e=>this._db.mapUsers(e=>{this.#N("user",e.uid,b({},e.public))})).then(t=>Promise.all(e)).then(e=>{t&&t(),this.logger("Persistent cache initialized.")}).catch(e=>{t&&t(e),this.logger("Failed to initialize persistent cache:",e)})}else this._db.deleteDatabase().then(e=>{t&&t()})}logger(e){if(this._loggingEnabled){let r=new Date,n=("0"+r.getUTCHours()).slice(-2)+":"+("0"+r.getUTCMinutes()).slice(-2)+":"+("0"+r.getUTCSeconds()).slice(-2)+"."+("00"+r.getUTCMilliseconds()).slice(-3);for(var t=arguments.length,s=Array(t>1?t-1:0),i=1;i<t;i++)s[i-1]=arguments[i];console.log("["+n+"]",e,s.join(" "))}}#R(e){let t=null;return e&&(t=new Promise((t,s)=>{this._pendingPromises[e]={resolve:t,reject:s,ts:new Date}})),t}#k(e,t,s,i){let r=this._pendingPromises[e];r&&(delete this._pendingPromises[e],t>=200&&t<400?r.resolve&&r.resolve(s):r.reject&&r.reject(new g(i,t)))}#C(e,t){let s;t&&(s=this.#R(t));let i=JSON.stringify(e=function e(t){return Object.keys(t).forEach(s=>{"_"==s[0]?delete t[s]:t[s]?Array.isArray(t[s])&&0==t[s].length?delete t[s]:t[s]?t[s]instanceof Date?_(t[s])||delete t[s]:"object"==typeof t[s]&&(e(t[s]),0==Object.getOwnPropertyNames(t[s]).length&&delete t[s]):delete t[s]:delete t[s]}),t}(e));this.logger("out: "+(this._trimLongStrings?JSON.stringify(e,q):i));try{this._connection.sendText(i)}catch(e){if(!t)throw e;this.#k(t,T.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,m);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.#k(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),setTimeout(e=>{if(205==t.ctrl.code&&"evicted"==t.ctrl.text){let e=this.#A("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){let e=this.#A("topic",t.ctrl.topic);e&&e._allMessagesReceived(t.ctrl.params.count)}else if("sub"==t.ctrl.params.what){let e=this.#A("topic",t.ctrl.topic);e&&e._processMetaSubs([])}}},0)):setTimeout(e=>{if(t.meta){let e=this.#A("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&this.#k(t.meta.id,200,t.meta,"META"),this.onMetaMessage&&this.onMetaMessage(t.meta)}else if(t.data){let e=this.#A("topic",t.data.topic);e&&e._routeData(t.data),this.onDataMessage&&this.onDataMessage(t.data)}else if(t.pres){let e=this.#A("topic",t.pres.topic);e&&e._routePres(t.pres),this.onPresMessage&&this.onPresMessage(t.pres)}else if(t.info){let e=this.#A("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"))}#P(){this._expirePromises||(this._expirePromises=setInterval(e=>{let t=new g("timeout",504),s=new Date((new Date).getTime()-5e3);
1for(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){for(let t in this._inPacketCount=0,this._serverInfo=null,this._authenticated=!1,this._expirePromises&&(clearInterval(this._expirePromises),this._expirePromises=null),this.#U("topic",(e,t)=>{e._resetSub()}),this._pendingPromises){let s=this._pendingPromises[t];s&&s.reject&&s.reject(e)}this._pendingPromises={},this.onDisconnect&&this.onDisconnect(e)}#q(){return this._appName+" ("+(this._browser?this._browser+"; ":"")+this._hwos+"); "+p}#I(e,t){switch(e){case"hi":return{hi:{id:this.getNextUniqueId(),ver:u,ua:this.#q(),dev:this._deviceToken,lang:this._humanLanguage,platf:this._platform}};case"acc":return{acc:{id:this.getNextUniqueId(),user:null,scheme:null,secret:null,tmpscheme:null,tmpsecret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:this.getNextUniqueId(),scheme:null,secret:null}};case"sub":return{sub:{id:this.getNextUniqueId(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:this.getNextUniqueId(),topic:t,unsub:!1}};case"pub":return{pub:{id:this.getNextUniqueId(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:this.getNextUniqueId(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:this.getNextUniqueId(),topic:t,desc:{},sub:{},tags:[],ephemeral:{}}};case"del":return{del:{id:this.getNextUniqueId(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw Error(`Unknown packet type requested: ${e}`)}}#N(e,t,s){this._cache[e+":"+t]=s}#A(e,t){return this._cache[e+":"+t]}#O(e,t){delete this._cache[e+":"+t]}#U(e,t,s){let 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=>{let t=this.#A("user",e);if(t)return{user:e,public:b({},t)}},e._cachePutUser=(e,t)=>{this.#N("user",e,b({},t.public))},e._cacheDelUser=e=>{this.#O("user",e)},e._cachePutSelf=t=>{this.#N("topic",e.name,e)},e._cacheDelSelf=t=>{this.#O("topic",e.name)}}#j(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}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 R.topicType(e)}static isMeTopicName(e){return R.isMeTopicName(e)}static isGroupTopicName(e){return R.isGroupTopicName(e)}static isP2PTopicName(e){return R.isP2PTopicName(e)}static isCommTopicName(e){return R.isCommTopicName(e)}static isNewGroupTopicName(e){return R.isNewGroupTopicName(e)}static isChannelTopicName(e){return R.isChannelTopicName(e)}static getVersion(){return u}static setNetworkProviders(e,t){r=e,n=t,T.setNetworkProviders(r,n),A.setNetworkProvider(n)}static setDatabaseProvider(e){a=e,S.setDatabaseProvider(a)}static getLibrary(){return p}static isNullValue(e){return"␡"===e}static isServerAssignedSeq(e){return e>0&&e<0xfffffff}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(f(e)){let 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,r){let n=this.#I("acc");return n.acc.user=e,n.acc.scheme=t,n.acc.secret=s,n.acc.login=i,r&&(n.acc.desc.defacs=r.defacs,n.acc.desc.public=r.public,n.acc.desc.private=r.private,n.acc.desc.trusted=r.trusted,n.acc.tags=r.tags,n.acc.cred=r.cred,n.acc.tmpscheme=r.scheme,n.acc.tmpsecret=r.secret,Array.isArray(r.attachments)&&r.attachments.length>0&&(n.extra={attachments:r.attachments.filter(e=>f(e))})),this.#C(n,n.acc.id)}createAccount(e,t,s,i){let r=this.account("new",e,t,s,i);return s&&(r=r.then(e=>this.#j(e))),r}createAccountBasic(e,t,s){return e=e||"",t=t||"",this.createAccount("basic",U(e+":"+t),!0,s)}updateAccountBasic(e,t,s,i){return t=t||"",s=s||"",this.account(e,"basic",U(t+":"+s),!1,i)}hello(){let e=this.#I("hi");return this.#C(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.#C({hi:{dev:e||I.DEL_CHAR}}),t=!0)),t}login(e,t,s){let i=this.#I("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=s,this.#C(i,i.login.id).then(e=>this.#j(e))}loginBasic(e,t,s){return this.login("basic",U(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",U(e+":"+t+":"+s))}getAuthToken(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)}setAuthToken(e){this._authToken=e}
1subscribe(e,t,s){let i=this.#I("sub",e);if(e||(e="new"),i.sub.get=t,s){if(s.sub&&(i.sub.set.sub=s.sub),s.desc){let t=s.desc;I.isNewGroupTopicName(e)?i.sub.set.desc=t:I.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=>f(e))}),s.tags&&(i.sub.set.tags=s.tags)}return this.#C(i,i.sub.id)}leave(e,t){let s=this.#I("leave",e);return s.leave.unsub=t,this.#C(s,s.leave.id)}createMessage(e,t,s){let i=this.#I("pub",e),r="string"==typeof t?E().parse(t):t;return r&&!E().isPlainText(r)&&(i.pub.head={mime:E().getContentType()},t=r),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;let s={pub:e};return t&&(s.extra={attachments:t.filter(e=>f(e))}),this.#C(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||!this.isConnected())break;let t=this.#A("topic",e.topic);if(!t||t.isSubscribed())break;t.maxMsgSeq()<e.seq&&(t.isChannelType()&&t._updateReceived(e.seq,"fake-uid"),e.xfrom&&!this.#A("user",e.xfrom)&&this.getMeta(e.xfrom,(new D).withDesc().build()).catch(e=>{this.logger("Failed to get the name of a new sender",e)}),t.subscribe(null).then(e=>t.getMeta(new D(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;let s={given:e.modeGiven,want:e.modeWant},i=new d(s),r=i.mode&&i.mode!=d._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){let s=this.#I("get",e);return s.get=b(s.get,t),this.#C(s,s.get.id)}setMeta(e,t){let s=this.#I("set",e),i=[];return t&&(["desc","sub","tags","cred","ephemeral"].forEach(function(e){t.hasOwnProperty(e)&&(i.push(e),s.set[e]=t[e])}),Array.isArray(t.attachments)&&t.attachments.length>0&&(s.extra={attachments:t.attachments.filter(e=>f(e))})),0==i.length?Promise.reject(Error("Invalid {set} parameters")):this.#C(s,s.set.id)}delMessages(e,t,s){let i=this.#I("del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=s,this.#C(i,i.del.id)}delTopic(e,t){let s=this.#I("del",e);return s.del.what="topic",s.del.hard=t,this.#C(s,s.del.id)}delSubscription(e,t){let s=this.#I("del",e);return s.del.what="sub",s.del.user=t,this.#C(s,s.del.id)}delCredential(e,t){let s=this.#I("del","me");return s.del.what="cred",s.del.cred={meth:e,val:t},this.#C(s,s.del.id)}delCurrentUser(e){let t=this.#I("del",null);return t.del.what="user",t.del.hard=e,this.#C(t,t.del.id).then(e=>{this._myUID=null})}note(e,t,s){if(s<=0||s>=0xfffffff)throw Error(`Invalid message id ${s}`);let i=this.#I("note",e);i.note.what=t,i.note.seq=s,this.#C(i)}noteKeyPress(e,t){let s=this.#I("note",e);s.note.what=t||"kp",this.#C(s)}videoCall(e,t,s,i){let r=this.#I("note",e);r.note.seq=t,r.note.what="call",r.note.event=s,r.note.payload=i,this.#C(r,r.note.id)}getTopic(e){let t=this.#A("topic",e);return!t&&e&&(t="me"==e?new k:"fnd"==e?new C:new R(e),this.#D(t),t._cachePutSelf()),t}cacheGetTopic(e){return this.#A("topic",e)}cacheRemTopic(e){this.#O("topic",e)}mapTopics(e,t){this.#U("topic",e,t)}isTopicCached(e){return!!this.#A("topic",e)}newGroupTopicName(e){return(e?"nch":"new")+this.getNextUniqueId()}getMeTopic(){return this.getTopic("me")}getFndTopic(){return this.getTopic("fnd")}getLargeFileHelper(){return new A(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",E().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){let t=this.#A("topic",e);return t&&t.online}getTopicAccessMode(e){let t=this.#A("topic",e);return t?t.acs:null}wantAkn(e){this._messageId=e?Math.floor(0xffffff*Math.random()+0xffffff):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 I.MESSAGE_STATUS_NONE=0,I.MESSAGE_STATUS_QUEUED=10,I.MESSAGE_STATUS_SENDING=20,I.MESSAGE_STATUS_FAILED=30,I.MESSAGE_STATUS_FATAL=40,I.MESSAGE_STATUS_SENT=50,I.MESSAGE_STATUS_RECEIVED=60,I.MESSAGE_STATUS_READ=70,I.MESSAGE_STATUS_TO_ME=80,I.DEL_CHAR="␡",I.MAX_MESSAGE_SIZE="maxMessageSize",I.MAX_SUBSCRIBER_COUNT="maxSubscriberCount",I.MAX_TAG_COUNT="maxTagCount",I.MAX_FILE_UPLOAD_SIZE="maxFileUploadSize",I.REQ_CRED_VALIDATORS="reqCred",I.URI_TOPIC_ID_PREFIX="tinode:topic/",c})()}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.