@talkjs/core 1.8.3 → 1.9.0
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.
- package/README.md +11 -0
- package/dist/talkSession.cjs +1 -1
- package/dist/talkSession.d.ts +219 -46
- package/dist/talkSession.js +1463 -1243
- package/package.json +1 -1
package/dist/talkSession.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e,t,n,s,r=Object.defineProperty,i=Object.defineProperties,a=Object.getOwnPropertyDescriptors,o=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,c=Object.prototype.propertyIsEnumerable,u=e=>{throw TypeError(e)},h=(e,t,n)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))l.call(t,n)&&h(e,n,t[n]);if(o)for(var n of o(t))c.call(t,n)&&h(e,n,t[n]);return e},p=(e,t)=>i(e,a(t)),f=(e,t)=>{var n={};for(var s in e)l.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&o)for(var s of o(e))t.indexOf(s)<0&&c.call(e,s)&&(n[s]=e[s]);return n},m=(e,t,n)=>t.has(e)||u("Cannot "+n),g=(e,t,n)=>(m(e,t,"read from private field"),n?n.call(e):t.get(e)),v=(e,t,n)=>t.has(e)?u("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,s)=>(m(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n),y=(e,t,n)=>new Promise((s,r)=>{var i=e=>{try{o(n.next(e))}catch(at){r(at)}},a=e=>{try{o(n.throw(e))}catch(at){r(at)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(i,a);o((n=n.apply(e,t)).next())});function w(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if("*"!==t[n]&&e[n]!==t[n])return!1;return!0}function k(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}function S(e,t){return e*(1-t+2*Math.random()*t)}Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=()=>!0;function T(e,t,n){return y(this,arguments,function*(e,t,{initialDelay:n,maxDelay:s,log:r,shouldRetry:i=C}){return t().catch(a=>y(null,null,function*(){if(0===e)throw a;if(!(yield i(a)))throw a;const o=1e3*n*1.2,l=S(s?Math.min(1e3*s,o):o,.05);return k(l).then(()=>T(e-1,t,{initialDelay:l/1e3,maxDelay:s,log:r,shouldRetry:i}))}))})}function I(){const e={},t=new Promise(function(t,n){e.resolve=t,e.reject=n});return e.promise=t,e}class x{constructor(e,t,n){this.layer=e,this.states=t,this.transitions=n,this._state=t[0]}get state(){return this._state}transition(e){const t=this.transitions[e];if(!t)return;if(!this.canTransition(e))return;const n=this.state;this._state=t.to,t.afterTransition({from:n,to:this.state})}canTransition(e){const t=this.transitions[e];return!!t&&("ANY"===t.from||t.from.includes(this.state))}}function E(e){return{ok:!0,value:e}}function M(e){return{ok:!1,where:"client",value:e}}function _(e){return{ok:!1,where:"server",value:e}}function A(){const e={},t=new Promise(t=>{e.ok=e=>y(null,null,function*(){return t(E(e))}),e.clientErr=e=>t(M(e)),e.serverErr=e=>t(_(e)),e.resolve=e=>t(e)});return e.promise=t,e}function N(e){return e.filter(e=>e.ok).map(e=>e.value)}function D(e,t){if(t.ok)return t.value.data;if("SESSION_DESTROYED"===t.value)throw new Error(`${e} failed because the session was destroyed`);if("server"===t.where)throw new Error(R(e,t.value));throw"unreachable"}function R(e,t){let n;return n=Array.isArray(t.reasons)?t.reasons.join():JSON.stringify(t.reasons),`${e} failed, got status ${t.status} ${t.errorCode}, reasons: ${n}`}let O=null;class P{constructor(e,t){this.realtimeUrl=e,this.handlers=t,this.socket=null,this.stateMachine=new x("ReconnectingSocket",["STOPPED","CONNECTING","READY","DISCONNECTED","TERMINATED"],{startWs:{from:["STOPPED","DISCONNECTED"],to:"CONNECTING",afterTransition:()=>{const e=new(function(){if(O)return O;if(globalThis.WebSocket)return globalThis.WebSocket;throw new Error("Missing WebSocket implementation")}())(this.realtimeUrl+"&talkjs-time="+Date.now());this.socket=e,e.addEventListener("open",()=>{this.socket===e&&this.stateMachine.transition("onOpen")}),e.addEventListener("close",()=>{this.socket===e&&this.stateMachine.transition("onClose")}),e.addEventListener("message",t=>{this.socket===e&&this.handlers.onMessage(t)})}},onOpen:{from:["CONNECTING"],to:"READY",afterTransition:()=>{this.handlers.onOpen()}},onClose:{from:["CONNECTING","READY"],to:"DISCONNECTED",afterTransition:e=>y(this,[e],function*({from:e}){"READY"===e&&this.handlers.onClose(),this.socket=null;const t=S(1e4,.5);setTimeout(()=>{"DISCONNECTED"===this.stateMachine.state&&this.stateMachine.transition("startWs")},t)})},stopWs:{from:["CONNECTING","DISCONNECTED","READY"],to:"STOPPED",afterTransition:({from:e})=>{"READY"===e&&this.handlers.onClose();const t=this.socket;this.socket=null,null==t||t.close(1e3)}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{const e=this.socket;this.socket=null,null==e||e.close(1e3)}}})}stopWs(){this.stateMachine.transition("stopWs")}startWs(){this.stateMachine.transition("startWs")}send(e){return"READY"===this.stateMachine.state?(this.socket.send(e),E(void 0)):M("SOCKET_NOT_READY")}terminate(){const e=this.socket;this.stateMachine.canTransition("onClose")&&this.stateMachine.transition("onClose"),e&&("terminate"in e?e.terminate():e.close(1e3))}destroy(){this.stateMachine.transition("destroy")}}class j{constructor(e,t){this.handlers=t,this.socket=new P(e,{onOpen:()=>this.handlers.onOpen(),onClose:()=>this.handlers.onClose(),onMessage:e=>this.onWebSocketMessage(e)})}call(e,t){const n=`/${t.path.map(e=>encodeURIComponent(e)).join("/")}`,s=JSON.stringify([e,t.method,n,t.data,t.headers]);return this.socket.send(s)}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.socket.destroy()}terminate(){this.socket.terminate()}onWebSocketMessage(e){try{const t=JSON.parse(e.data);if("PUBLISH"===t[1]){const e=t[0],n=JSON.stringify([e,"ACK"]);this.socket.send(n);const s=t.slice(2),r=[];s.forEach(e=>{"session.expired"===e.type?this.handlers.onAuthExpired():"upstream.restarting"===e.type?this.handlers.onUpstreamRestarting():r.push(e)}),r.length>0&&this.handlers.onPublish(e,r)}else{const e=t[0],n=t[1],s=t[2];this.handlers.onResponse(e,n,s)}}catch(t){}}}class ${constructor(e){this.delayMs=e,this.timeout=void 0}schedule(e){this.stop(),this.timeout=setTimeout(()=>{void 0!==this.timeout&&(this.stop(),e())},this.delayMs)}stop(){void 0!==this.timeout&&(clearTimeout(this.timeout),this.timeout=void 0)}}const U="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class W{constructor(){this.i=-1}next(){return this.i++,this.i}reset(){this.i=-1}}class q{constructor(e,t){this.handlers=t,this.seqCounter=new W,this.responseHandlers={},this.heartbeats=new L(this),this.socket=new j(e,{onUpstreamRestarting:()=>{this.heartbeats.serverActive(),this.handlers.onUpstreamRestarting()},onOpen:()=>{this.heartbeats.clientActive(),this.heartbeats.serverActive(),this.handlers.onReady()},onClose:()=>{this.heartbeats.stop(),Object.values(this.responseHandlers).forEach(e=>{e.clientErr("WEBSOCKET_DISCONNECTED")}),this.responseHandlers={},this.seqCounter.reset(),this.handlers.onNotReady()},onResponse:(e,t,n)=>{this.heartbeats.serverActive(),this.onResponse(e,t,n)},onPublish:(e,t)=>{this.heartbeats.serverActive(),this.handlers.onPublish(e,t),this.heartbeats.clientActive()},onAuthExpired:()=>{this.heartbeats.serverActive(),this.handlers.onAuthExpired()}})}sync(){return y(this,null,function*(){yield new Promise(e=>U(()=>e()));const e=Object.values(this.responseHandlers).map(e=>e.promise.catch(()=>{}));return Promise.all(e)})}call(e){const t=this.seqCounter.next(),n=A();this.responseHandlers[t]=n;const s=this.socket.call(t,e);return s.ok||(n.resolve(s),delete this.responseHandlers[t]),this.heartbeats.clientActive(),n.promise}onResponse(e,t,n){return y(this,null,function*(){const s=this.responseHandlers[e];s&&(200===t?s.ok({status:t,data:n}):s.serverErr({status:t,errorCode:n.errorCode,reasons:n.reasons}),delete this.responseHandlers[e])})}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.heartbeats.stop(),Object.values(this.responseHandlers).forEach(e=>{e.clientErr("WEBSOCKET_DISCONNECTED")}),this.responseHandlers={},this.socket.destroy()}terminate(){this.socket.terminate()}}class L{constructor(e){this.connection=e,this.clientInactivityTimer=new $(25e3),this.serverInactivityTimer=new $(1e4),this.serverTimeoutTimer=new $(5e3)}clientActive(){this.clientInactivityTimer.schedule(()=>{this.sendHeartbeat()})}serverActive(){this.serverTimeoutTimer.stop(),this.serverInactivityTimer.schedule(()=>{this.sendHeartbeat(),this.serverTimeoutTimer.schedule(()=>{this.connection.terminate()})})}stop(){this.clientInactivityTimer.stop(),this.serverInactivityTimer.stop(),this.serverTimeoutTimer.stop()}sendHeartbeat(){this.connection.call({method:"GET",path:["ping"],data:{},headers:{}}).catch(()=>{})}}class B{constructor(e,t,n){this.authProvider=t,this.handlers=n,this.stateMachine=new x("AuthenticatedConnection",["WAITING_FOR_WS","LOGGING_IN","RENEWING_SESSION","READY","TERMINATED"],{logIn:{from:["WAITING_FOR_WS"],to:"LOGGING_IN",afterTransition:()=>y(this,null,function*(){yield this.renewSession()})},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>y(this,null,function*(){this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>y(this,null,function*(){yield this.renewSession()})},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>y(this,null,function*(){this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},authenticated:{from:["LOGGING_IN","RENEWING_SESSION"],to:"READY",afterTransition:({from:e})=>{"LOGGING_IN"===e&&this.handlers.onReady()}},authExpired:{from:["READY","RENEWING_SESSION"],to:"LOGGING_IN",afterTransition:()=>y(this,null,function*(){this.handlers.onNotReady(),this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},wsDisconnected:{from:["READY","LOGGING_IN","RENEWING_SESSION"],to:"WAITING_FOR_WS",afterTransition:({from:e})=>{"READY"!==e&&"RENEWING_SESSION"!==e||this.handlers.onNotReady(),this.authProvider.clearScheduledRefresh()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{this.authProvider.clearScheduledRefresh(),this.connection.destroy()}}}),this.connection=new q(e,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onReady:()=>this.stateMachine.transition("logIn"),onNotReady:()=>{this.stateMachine.transition("wsDisconnected")},onAuthExpired:()=>{this.stateMachine.transition("authExpired")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}}),t.onTokenChanged(()=>{"READY"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauth")})}sync(){return y(this,null,function*(){return this.connection.sync()})}call(e){const t=this.connection.call(e);return t.then(e=>{e.ok||"server"!==e.where||401!==e.value.status||"READY"!==this.stateMachine.state&&"RENEWING_SESSION"!==this.stateMachine.state||this.stateMachine.transition("authExpired")}),t}stopWs(){this.connection.stopWs()}startWs(){this.connection.startWs(),this.authProvider.getToken().catch(()=>{})}destroy(){this.stateMachine.transition("destroy")}renewSession(){return y(this,null,function*(){let e;try{const t=this.authProvider.getCachedToken();e=t||(yield this.authProvider.getToken())}catch(r){return}const t=yield this.connection.call({method:"POST",path:["session","renew"],data:{token:e},headers:{}});if(!t.ok&&"client"===t.where)return;const n=t.value;if(n.status,200===n.status){const t=n.data.expiresInSeconds;return void(null!==t&&t<120?(console.warn(`[TalkJS] Authenticated with a token that expires in ${t}s. Treating it as already expired and refreshing. Newly generated tokens should last at least 10 minutes.`),"LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed")):(this.authProvider.scheduleRefresh(t),this.authProvider.emitTokenAccepted(e),this.stateMachine.canTransition("authenticated")&&this.stateMachine.transition("authenticated")))}if(401===n.status)return void("LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed"));if(400===n.status)return void this.authProvider.emitTokenRefreshFailed(R("Authentication",n));if(402===n.status)return void this.authProvider.emitTokenRefreshFailed(R("Authentication",n));const s=5e3*Math.random()+5e3;setTimeout(()=>{this.call({method:"POST",path:["session","renew"],data:{token:e},headers:{}}).catch(()=>{})},s)})}}class G{constructor(e,t,n){this.handlers=n,this.stateMachine=new x("StopStartConnection",["STOPPED","WAITING_FOR_WS","READY","TERMINATED"],{unexpectedDisconnect:{from:["READY"],to:"WAITING_FOR_WS",afterTransition:()=>{this.inactivityTimer.stop(),this.handlers.onNotReady()}},stop:{from:["WAITING_FOR_WS","READY"],to:"STOPPED",afterTransition:()=>{this.connection.stopWs(),this.inactivityTimer.stop(),this.handlers.onNotReady()}},start:{from:["STOPPED"],to:"WAITING_FOR_WS",afterTransition:()=>{this.connection.startWs()}},ready:{from:["WAITING_FOR_WS"],to:"READY",afterTransition:()=>{this.pendingCalls=0,this.activeSubscriptions=0,this.inactivityTimer.schedule(()=>{this.stateMachine.transition("stop")}),this.handlers.onReady()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{this.inactivityTimer.stop(),this.connection.destroy()}}}),this.pendingCalls=0,this.activeSubscriptions=0,this.inactivityTimer=new $(3e3),this.connection=new B(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("ready")},onNotReady:()=>{"READY"===this.stateMachine.state&&this.stateMachine.transition("unexpectedDisconnect")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}get inactive(){return 0===this.pendingCalls&&0===this.activeSubscriptions}sync(){return y(this,null,function*(){return this.connection.sync()})}ensureStarted(){this.stateMachine.canTransition("start")&&this.stateMachine.transition("start")}call(e){return y(this,null,function*(){this.inactivityTimer.stop(),this.pendingCalls++,this.logTrace("Called",e.path,e.data);const t=yield this.connection.call(e);return this.pendingCalls--,this.logTrace("Received",e.path,e.data),"SUBSCRIBE"===e.method&&t.ok?(this.activeSubscriptions++,this.logTrace("Subscribed",e.path,e.data)):"UNSUBSCRIBE"===e.method&&t.ok&&(this.activeSubscriptions--,this.logTrace("Unsubscribed",e.path,e.data)),this.inactive&&this.inactivityTimer.schedule(()=>{this.stateMachine.transition("stop")}),t})}destroy(){this.stateMachine.transition("destroy")}isConnected(){return"READY"===this.stateMachine.state}logTrace(e,t,n){}}class F{constructor(e,t,n){this.handlers=n,this.stateMachine=new x("QueuedConnection",["NOT_READY","PROCESSING_QUEUE","READY","TERMINATED"],{processQueue:{from:["NOT_READY"],to:"PROCESSING_QUEUE",afterTransition:()=>{this.sendQueuedCalls()}},ready:{from:["PROCESSING_QUEUE"],to:"READY",afterTransition:()=>{this.handlers.onReady()}},notReady:{from:["PROCESSING_QUEUE","READY"],to:"NOT_READY",afterTransition:()=>{Object.values(this.subscribeQueue).forEach(e=>e.deferred.ok({status:200,data:{}})),this.subscribeQueue={},this.handlers.onSubscriptionsLost()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{for(var e;this.callQueue.length;){const t=null==(e=this.callQueue.shift())?void 0:e.deferred;null==t||t.clientErr("SESSION_DESTROYED")}this.connection.destroy()}}}),this.subscribeQueue={},this.callQueue=[],this.connection=new G(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("processQueue")},onNotReady:()=>{this.stateMachine.transition("notReady")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}sync(){return y(this,null,function*(){return this.connection.sync()})}call(e){return"READY"===this.stateMachine.state?this.connection.call(e):("NOT_READY"===this.stateMachine.state&&this.connection.ensureStarted(),"SUBSCRIBE"===e.method||"UNSUBSCRIBE"===e.method?this._subscribe(e):this._call(e))}_subscribe(e){const t=e.path.join("/"),n=this.subscribeQueue[t];if(n&&n.params.method===e.method)return n.deferred.promise;n&&n.params.method!==e.method&&(n.deferred.ok({status:200,data:{}}),delete this.subscribeQueue[t]);const s={deferred:A(),params:e};return this.subscribeQueue[t]=s,s.deferred.promise}_call(e){const t={deferred:A(),params:e};return this.callQueue.push(t),t.deferred.promise}dequeue(){for(const e in this.subscribeQueue){const t=this.subscribeQueue[e];return delete this.subscribeQueue[e],t}return this.callQueue.shift()}destroy(){this.stateMachine.transition("destroy")}sendQueuedCalls(){return y(this,null,function*(){let e=0;for(;"PROCESSING_QUEUE"===this.stateMachine.state;){e++;const t=this.dequeue();if(!t)return void this.stateMachine.transition("ready");this.connection.call(t.params).then(e=>{t.deferred.resolve(e)}),e>50&&(yield new Promise(e=>setTimeout(e,100)))}})}isConnected(){return"READY"===this.stateMachine.state||"PROCESSING_QUEUE"===this.stateMachine.state}}function H(e){return Object.freeze(e)}function z(e){return H(e.map(e=>function(e){switch(e.type){case"text":return Object.freeze({type:"text",children:J(e.children)});case"file":case"location":return Object.freeze(e)}}(e)))}function J(e){return H(e.map(e=>function(e){if("string"==typeof e)return e;switch(e.type){case"bold":case"italic":case"strikethrough":case"bulletList":case"bulletPoint":case"link":case"actionLink":case"actionButton":return Object.freeze(p(d({},e),{children:J(e.children)}));case"mention":case"autoLink":case"codeSpan":case"customEmoji":return Object.freeze(e)}}(e)))}function Y(e,t){return void 0===t?e:t}function Q(e,t){return void 0===t?e:H(t)}function V(e,t){if(void 0===t)return e;if(null===t)return H({});const n=d({},e);for(const s in t){const e=t[s];null===e?delete n[s]:n[s]=e}return H(n)}function K(e,t){if(e===t)return!0;if(!e||!t)return!1;if("object"!=typeof e||"object"!=typeof t)return!1;if(e.constructor!==t.constructor)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!K(e[n],t[n]))return!1}else{const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const s of n){if(!Object.hasOwnProperty.call(t,s))return!1;if(!K(e[s],t[s]))return!1}}return!0}const Z="undefined"!=typeof window&&null!=(t=window.queueMicrotask)?t:setTimeout;class X{constructor(e,t,n){this.headers=e,this.clearPendingBatch=t,this.sendCalls=n,this.sent=!1,Z(()=>this.send())}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class ee extends X{constructor(e,t,n){super(t,n,()=>{this.sendSubscribe(),this.sendGet()}),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e){return ee.isCorrectBatchTypeFor(e)&&K(this.headers,e.headers)}static isCorrectBatchTypeFor(e){const t=w(e.path,["users","*"]),n="GET"===e.method||"SUBSCRIBE"===e.method;return t&&n}push(e){const t=e.path[1],n=A();return"GET"===e.method?this.getCalls.push({userId:t,deferred:n}):this.subscribeCalls.push({userId:t,deferred:n}),1e3!==this.getCalls.length&&1e3!==this.subscribeCalls.length||this.send(),n.promise}sendGet(){return y(this,null,function*(){if(0===this.getCalls.length)return;const e=[...new Set(this.getCalls.map(e=>e.userId))],t=yield this.connection.call({method:"GET",path:["users"],data:{ids:e,includePrivateFields:!1},headers:this.headers});if(t.ok)for(const n of this.getCalls){const e=t.value.data[n.userId];e?n.deferred.ok({status:200,data:e}):n.deferred.serverErr({status:404,errorCode:"NOT_FOUND",reasons:["No user with that ID exists"]})}else this.getCalls.forEach(e=>e.deferred.resolve(t))})}sendSubscribe(){if(0===this.subscribeCalls.length)return;const e=[...new Set(this.subscribeCalls.map(e=>e.userId))];this.connection.call({method:"SUBSCRIBE",path:["users"],data:{ids:e},headers:this.headers}).then(e=>this.subscribeCalls.forEach(t=>t.deferred.resolve(e)))}}class te extends X{constructor(e,t,n,s){super(n,s,()=>this.sendMutate()),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e){return!(!te.isCorrectBatchTypeFor(e)||e.path[1]!==this.conversationId||!K(this.headers,e.headers))}static isCorrectBatchTypeFor(e){return!(!w(e.path,["conversations","*","participants","*"])||"PUT"!==e.method&&"POST"!==e.method&&"PATCH"!==e.method)}push(e){const t=e.path[3],n=A();return this.calls.push({action:{id:t,method:e.method,params:e.data},deferred:n}),100===this.calls.length&&this.send(),n.promise}sendMutate(){return y(this,null,function*(){const e=this.calls.map(e=>e.action),t=yield this.connection.call({method:"POST",path:["conversations",this.conversationId,"participants"],data:{actions:e},headers:this.headers});if(!t.ok)return void this.calls.forEach(e=>e.deferred.resolve(t));const n=t.value.data.responses;for(let s=0;s<n.length;s++){const e=this.calls[s].deferred,t=n[s];200===t.status?e.ok(p(d({},t),{data:{}})):e.serverErr(t)}})}}class ne{constructor(e,t,n){this.pendingBatch=null,this.connection=new F(e,t,n)}sync(){return y(this,null,function*(){return this.connection.sync()})}call(e){return y(this,null,function*(){var t;if(null==(t=this.pendingBatch)?void 0:t.canPush(e))return this.pendingBatch.push(e);this.pendingBatch&&this.pendingBatch.send();const n=this.createEmptyBatchFor(e);return n?(this.pendingBatch=n,n.push(e)):this.connection.call(e)})}destroy(){var e;this.connection.destroy(),null==(e=this.pendingBatch)||e.destroy()}isConnected(){return this.connection.isConnected()}createEmptyBatchFor(e){var t,n;if(ee.isCorrectBatchTypeFor(e))return new ee(this.connection,null!=(t=e.headers)?t:{},()=>this.pendingBatch=null);if(te.isCorrectBatchTypeFor(e)){const t=e.path[1];return new te(t,this.connection,null!=(n=e.headers)?n:{},()=>this.pendingBatch=null)}return null}}const se={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class re{constructor(e,t,n){this.throttler=new ie,this.alive=!0,this.connection=new ne(e,t,n)}sync(){return y(this,null,function*(){return this.connection.sync()})}call(e){return y(this,null,function*(){let t=0;for(;this.alive;){const n=yield this.connection.call(e);if((n.ok||"client"!==n.where||"SOCKET_NOT_READY"!==n.value)&&(n.ok||"server"!==n.where||500!==n.value.status)||t++,10===t)return n;if(n.ok||"client"!==n.where){const e=n.value,t=e.status,s=se[t];if("RESOLVE"===s)return this.throttler.resetDelay(),n;if("RETRY"===s)continue;if("DELAY"===s){yield this.throttler.wait();continue}return console.warn("[TalkJS] Unexpected status code",t),e}if("SESSION_DESTROYED"===n.value)return M("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==n.value&&("SOCKET_NOT_READY"!==n.value?n.value:yield this.throttler.wait())}return M("SESSION_DESTROYED")})}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class ie{constructor(){this.initialDelayMs=200,this.exponentialFactor=1.2,this.maxDelayMs=3e4,this.currentDelayMs=this.initialDelayMs,this.lastCall=0}getCurrentDelay(){return this.currentDelayMs}wait(){const e=(new Date).getTime(),t=S(this.currentDelayMs,.05),n=this.lastCall+t,s=Math.max(0,n-e);return this.lastCall=e+s,this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs),k(s)}resetDelay(){this.currentDelayMs=this.initialDelayMs}}function ae(e){return e.map(e=>encodeURIComponent(e)).join()}class oe{constructor(){this.paths={}}add(e){this.paths[ae(e)]=e}delete(e){delete this.paths[ae(e)]}has(e){return Object.hasOwnProperty.call(this.paths,ae(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach(t=>e(t))}}class le{constructor(e,t,n){this.handlers=n,this.targetSubscriptions=new oe,this.connection=new re(e,t,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onSubscriptionsLost:()=>{this.targetSubscriptions.forEach(e=>{this.resubscribe(e)}),this.handlers.onResubscribeSent()},onReady:()=>this.handlers.onReady(),onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}sync(){return y(this,null,function*(){return this.connection.sync()})}call(e){return this.connection.call(e)}subscribe(e){return y(this,null,function*(){return this.targetSubscriptions.add(e),this.connection.call({method:"SUBSCRIBE",path:e,data:{},headers:{}})})}unsubscribe(e){return y(this,null,function*(){return this.targetSubscriptions.delete(e),this.connection.call({method:"UNSUBSCRIBE",path:e,data:{},headers:{}})})}resubscribe(e){return y(this,null,function*(){const t=yield this.connection.call({method:"SUBSCRIBE",path:e,data:{},headers:{}});t.ok||this.handlers.onResubscribeError(e,t)})}destroy(){this.targetSubscriptions.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class ce{constructor(){this.prev=Promise.resolve()}runExclusive(e){return y(this,null,function*(){const t=this.prev.then(()=>e());return this.prev=t,t})}sync(){return y(this,null,function*(){return this.runExclusive(()=>{})})}}class ue{constructor(e){this.initialised=!1,this.getPointer=void 0,this.pendingStates=[e],e.resultPromise.then(()=>this.initialised=!0)}get pendingPointer(){if(0!==this.pendingStates.length)return this.pendingStates[this.pendingStates.length-1]}get mostRecentState(){var e;return null!=(e=this.pendingPointer)?e:this.getPointer}canAppendState(e){var t,n;const s=null==(t=this.getPointer)?void 0:t.seq;if(void 0!==s&&e<=s)return!1;const r=null==(n=this.pendingPointer)?void 0:n.seq;return!(void 0!==r&&e<r)}set(e){if(!this.canAppendState(e.seq))throw"Appending in the past";this.pendingStates.push(e)}mutate(e,t){if(!this.initialised)return;if(!this.canAppendState(e))throw"Mutating in the past";const n=this.mostRecentState.resultPromise.then(e=>e.ok?t(e):e);this.pendingStates.push({seq:e,resultPromise:n})}get(e){for(;this.pendingStates.length>0&&(void 0===this.getPointer||this.pendingStates[0].seq<=e);)this.getPointer=this.pendingStates.shift();return this.getPointer}}class he extends ue{constructor(e,t){super(e),this.onTeardown=t,this._error=null,this._lastGoodState=Promise.resolve(void 0),this.registerNewState(e.resultPromise)}get error(){return this._error}get lastGoodState(){return this._lastGoodState}mutate(e,t){super.mutate(e,t),this.registerNewState(this.mostRecentState.resultPromise)}set(e){super.set(e),this.registerNewState(this.mostRecentState.resultPromise)}registerNewState(e){const t=this.lastGoodState;this._lastGoodState=e.then(e=>e.ok?e.value:t),e.then(e=>{e.ok||this.setError(e)})}setError(e){var t;this._error||(this._error=e,null==(t=this.onTeardown)||t.call(this,e),this.lastGoodState.then(e=>{void 0!==e&&this.teardownNested(e)}))}}class de extends he{constructor(e,t){const n=new Promise(e=>setTimeout(e)).then(()=>this.fetchInitial(e));super({seq:e,resultPromise:n},t.onTeardown),this.initialSeq=e,this.getDeepMutex=new ce,this.lastDeep=void 0}refetchInitial(e){return y(this,null,function*(){const t=this.mostRecentState.resultPromise,n=this.fetchInitial(e),[s,r]=yield Promise.all([t,n]);return void 0!==s&&s.ok&&r.ok&&this.equal(s.value,r.value)?s:r})}refetch(e){if(null!==this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.set(t)}changedBetween(e,t){return y(this,null,function*(){if(e>=t)return!1;const n=this.get(t),s=yield n.resultPromise;return!!s.ok&&(s.value.lastChanged>Math.max(this.initialSeq,e)&&s.value.lastChanged<=t||(yield this.anyChildChanged(e,t,s.value)))})}getDeep(e){return y(this,null,function*(){return this.getDeepMutex.runExclusive(()=>y(this,null,function*(){var t;if(null!==this.error)return this.error;const n=null==(t=this.lastDeep)?void 0:t.seq;if(e===n)return this.lastDeep.deep;if(void 0!==n){if(e<n)throw`Trying to load seq ${e} when we have previously loaded seq ${n}`;if(!(yield this.changedBetween(n,e)))return this.lastDeep.seq=e,this.lastDeep.deep}const s=this.get(e).resultPromise,r=s.then(t=>t.ok?this.loadNested(e,t.value):t);this.lastDeep={seq:e,shallow:s,deep:r};const i=yield r;return i.ok||this.setError(i),i}))})}}class pe extends de{constructor(e,t,n){super(e,n),this.emitMutex=t,this.externallyIdleTimer=new fe,this.externallyIdle=!0,this.internallyIdleTimer=new fe,this.internallyIdle=!0,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive(()=>y(this,null,function*(){yield this.emit(e)}))}registerInternalSubscription(){this.internallyIdleTimer.stop(),this.internallyIdle=!1,this.referencedByOtherStores++;let e=!0;return()=>{e&&(e=!1,this.referencedByOtherStores--,0===this.referencedByOtherStores&&this.internallyIdleTimer.restart(()=>{this.internallyIdle=!0,this.tryFullyUnsubscribe()},this.unsubscribeDebounceMs),this.tryFullyUnsubscribe())}}get onlyUsedInternally(){return 0===this.listeners.length}listen(e){this.externallyIdleTimer.stop(),this.externallyIdle=!1,this.listeners.push(e),void 0!==this.lastEmitResult&&e(this.lastEmitResult);let t=!0;return()=>{t&&(t=!1,this.listeners=this.listeners.filter(t=>t!==e),0===this.listeners.length&&this.externallyIdleTimer.restart(()=>{this.externallyIdle=!0,this.tryFullyUnsubscribe()},this.unsubscribeDebounceMs))}}tryFullyUnsubscribe(){this.externallyIdle&&this.internallyIdle&&this.setError(M("UNSUBSCRIBED"))}emit(e){return y(this,null,function*(){var t;if(this.lastEmitSeq&&this.lastEmitSeq>=e)return;if(!1===(null==(t=this.lastEmitResult)?void 0:t.ok))return;this.lastEmitSeq=e;const n=yield this.getDeep(e);n!==this.lastEmitResult&&(this.lastEmitResult=n,this.listeners.forEach(e=>e(n)))})}}class fe{constructor(){this.timerId=void 0}restart(e,t){void 0!==this.timerId&&clearTimeout(this.timerId),this.timerId=setTimeout(()=>e(),t)}stop(){clearTimeout(this.timerId)}}var me,ge={};function ve(e,t){const n=t.lastIndex;let s;const r=[];for(;null!==(s=t.exec(e));)r.push(s),""===s[0]&&(t.lastIndex+=1);return t.lastIndex=n,r}function be(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1");return decodeURIComponent(t)}function ye(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(me)return ge;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}me=1,Object.defineProperty(ge,"__esModule",{value:!0}),ge.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},ge.decode=function(e){return decodeURIComponent(Array.from(atob(e),t).join(""))}}(),(e=>{function t(e,t){(function(e,t){switch(t){case"undefined":return void 0===e;case String:return"string"==typeof e||e instanceof String;case Boolean:return"boolean"==typeof e||e instanceof Boolean;case Number:return"number"==typeof e||e instanceof Number;default:return e instanceof t}})(e,t)||(t.name,String(e))}e.defined=function(e){},e.has=function(e,t){e[t]},e.is=t,e.equals=function(e,t){},e.oneOf=function(e,t){t.includes(e)||JSON.stringify(t)},e.isArray=function(e,n){t(e,Array),e&&e.length>0&&t(e[0],n)},e.optional=function(e,n){void 0!==e&&t(e,n)},e.falsy=function(e){},e.never=function(e){}})(ye||(ye={}));const we=ye,ke=/^\/.*[^\\]\/[im]*$/;function Se(e){return!!ke.test(e)&&!Ce(e).test("")}function Ce(e){const t=e.match(/^\/(.*[^\\])\/(.*)$/);if(!t)throw new Error(`Expected ${e} to be a (non-empty) regex`);let n=t[2]||"";return n=n.replace(/[^im]/g,"")+"g",new RegExp(t[1],n)}class Te{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:n,allowedMatches:s,forbiddenMatches:r,forbiddenWords:i,suppressLinks:a,suppressEmailAddresses:o,suppressPhoneNumbers:l,replacement:c}){if(we.oneOf(e,["all","otherOnly","off"]),this.mode=e,this.suppressLinks=!1!==a,this.suppressEmailAddresses=!1!==o,this.suppressPhoneNumbers=!1!==l,this.allowedHostnames=t||[],this.allowedPhoneNrs=(n||[]).filter(e=>e).map(e=>e.replace(/[^0-9]/g,"")),this.allowedMatches=(s||[]).filter(Se).map(e=>Ce(e)),this.forbiddenMatches=(r||[]).filter(Se).map(e=>Ce(e)),i){const e=i.split("\n").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0&&!e.startsWith("#")).map(e=>e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"));e.length&&this.forbiddenMatches.push(new RegExp(`\\b(${e.join("|")})\\b`,"gi"))}we(()=>this.allowedMatches.every(e=>e.flags.includes("g")),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),we(()=>this.forbiddenMatches.every(e=>e.flags.includes("g")),"All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"),c=null==c?void 0:c.trim(),this.replacement=c&&c.length>0?c:void 0}shouldSuppress({isContentBySender:e}){return"all"===this.mode||"otherOnly"===this.mode&&!e}}function Ie(e,t){return e.map(e=>function(e,t){if("text"===e.type)return xe(e.children,function(e){var t,n,s,r,i,a,o,l,c,u,h,d,p;let f="";return e.t&&(f=`(${e.t("CONTACT_INFORMATION_HIDDEN")})`),{formattedLinks:null!=(t=e.formattedLinks)?t:"plaintext",markup:null!=(n=e.markup)&&n,useFallbackMentions:null!=(s=e.useFallbackMentions)&&s,sameTabLinkRules:null!=(r=e.sameTabLinkRules)?r:[],enableEmojiImageFallback:null!=(i=e.enableEmojiImageFallback)&&i,highlight:null!=(a=e.highlight)?a:[],contactInfo:null!=(o=e.contactInfo)&&o,suppression:null!=(l=e.suppression)?l:new Te({mode:"off"}),contactInfoHiddenText:null!=(h=null!=(u=e.contactInfoHiddenText)?u:null==(c=e.suppression)?void 0:c.replacement)?h:f,customEmojiUrls:null!=(d=e.customEmojiUrls)?d:{},enableActions:null==(p=e.enableActions)||p}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${be(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${be(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${be(e.url)}`;if("file"===e.type&&"voice"===e.subtype){const t=e.duration;return void 0===t?"🎙️":`🎙️ (${Math.floor(t/60)}:${Math.floor(t%60).toString().padStart(2,"0")})`}return"file"===e.type?(e.subtype,`📎 ${be(e.url)}`):"location"===e.type?"📍":""}(e,t)).join("\n\n")}function xe(e,t){return e.flatMap(e=>{if("string"==typeof e)return e;switch(e.type){case"blockquote":case"bold":case"italic":case"strikethrough":case"link":case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return xe(e.children,t);case"bulletlist":case"bulletList":return"\n"+xe(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+xe(e.children,t)+"\n";case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"emoji":case"customemoji":case"customEmoji":return e.text;case"suppressed":return t.contactInfoHiddenText;case"mention":return`@${e.text}`}}).join("")}function Ee(e){return H({id:e.id,name:e.name,custom:H(e.custom),locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage})}function Me(e,t){return H({user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt})}function _e(e){const t=Object.entries(e).map(([e,t])=>H({emoji:e,count:t.count,currentUserReacted:t.currentUserReacted}));return t.sort((e,t)=>e.emoji.localeCompare(t.emoji)),H(t)}class Ae extends pe{constructor(e,t,n,s,r){super(e,s,r),this.userId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return y(this,null,function*(){const t=yield this.realtimeClient.call({method:"GET",path:["users",this.userId],data:{includePrivateFields:!1},flags:{bypassCache:!0}});return t.ok?E({snapshot:Ee(t.value.data),lastChanged:e}):"server"===t.where&&404===t.value.status?E({snapshot:null,lastChanged:e}):t})}equal(e,t){return K(e.snapshot,t.snapshot)}loadNested(e,t){return y(this,null,function*(){return E(t)})}userCreated(e,t){this.mutate(e,n=>null!==n.value.snapshot?n:E({snapshot:Ee(t.state),lastChanged:e}))}userEdited(e,t){this.mutate(e,n=>{const s=n.value.snapshot;return null===s?(console.warn("[TalkJS] Received a 'used edited' event for a user that we thought didn't exist."),n):E({snapshot:{id:s.id,name:Y(s.name,t.diff.name),custom:V(s.custom,t.diff.custom),locale:Y(s.locale,t.diff.locale),photoUrl:Y(s.photoUrl,t.diff.photoUrl),role:Y(s.role,t.diff.role),welcomeMessage:Y(s.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})})}getFromCache(){return y(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.snapshot?_({status:404,errorCode:"USER_NOT_FOUND",reasons:["That user does not exist yet"]}):E({status:200,data:{id:e.value.snapshot.id,name:e.value.snapshot.name,custom:e.value.snapshot.custom,locale:e.value.snapshot.locale,photoUrl:e.value.snapshot.photoUrl,role:e.value.snapshot.role,welcomeMessage:e.value.snapshot.welcomeMessage}}):M("NOT_IN_CACHE")})}teardownNested(e){}anyChildChanged(e,t,n){return y(this,null,function*(){return!1})}}class Ne extends de{constructor(e,t,n,s){super(e,{}),this.conversationId=t,this.message=n,this.realtimeClient=s}get messageId(){return"string"==typeof this.message?this.message:this.message.id}fetchInitial(e){return y(this,null,function*(){let t;if("object"==typeof this.message)t=this.message;else{const e=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId,"messages",this.message],data:{},flags:{bypassCache:!0}});if(!e.ok)return e;t=e.value.data}return E({lastChanged:e,sender:null===t.senderId?null:this.realtimeClient.internalSubscribe(["users",t.senderId]),data:{id:t.id,type:t.type,custom:H(t.custom),createdAt:t.createdAt,editedAt:t.editedAt,referencedMessageId:t.referencedMessageId,origin:t.origin,plaintext:Ie(t.content,{}),content:z(t.content),reactions:_e(t.reactions)}})})}refetch(e){throw"Do not call refetch on message data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return K(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,function*(){var s;const r=null==(s=n.sender)?void 0:s.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))})}loadNested(e,t){return y(this,null,function*(){var n,s,r;const i=yield null==(s=null==(n=t.sender)?void 0:n.store)?void 0:s.getDeep(e);if(!1===(null==i?void 0:i.ok))return i;if(null===t.data)return E({snapshot:null});const a=null==i?void 0:i.value;return E({snapshot:H({sender:null!=(r=null==a?void 0:a.snapshot)?r:null,id:t.data.id,type:t.data.type,custom:H(t.data.custom),createdAt:t.data.createdAt,editedAt:t.data.editedAt,origin:t.data.origin,plaintext:t.data.plaintext,content:t.data.content,referencedMessageId:t.data.referencedMessageId,reactions:t.data.reactions})})})}messageEdited(e,t){this.mutate(e,n=>{if(null===n.value.data)return n;const s=n.value.data.content,r=(i=s,void 0===(a=t.diff.content)?i:z(a));var i,a;const o=s===r?n.value.data.plaintext:Ie(r,{});return E({lastChanged:e,sender:n.value.sender,data:{id:n.value.data.id,type:n.value.data.type,createdAt:n.value.data.createdAt,origin:n.value.data.origin,referencedMessageId:n.value.data.referencedMessageId,editedAt:Y(n.value.data.editedAt,t.diff.editedAt),custom:V(n.value.data.custom,t.diff.custom),plaintext:o,content:r,reactions:De(n.value.data.reactions,t.diff.reactions)}})})}messageDeleted(e,t){this.mutate(e,n=>null===n.value.data?n:this.messageId===t.messageId?(this.teardownNested(n.value),E({lastChanged:e,sender:null,data:null})):n.value.data.referencedMessageId===t.messageId?E({lastChanged:e,sender:n.value.sender,data:{id:n.value.data.id,type:n.value.data.type,createdAt:n.value.data.createdAt,origin:n.value.data.origin,referencedMessageId:null,editedAt:n.value.data.editedAt,custom:n.value.data.custom,plaintext:n.value.data.plaintext,content:n.value.data.content,reactions:n.value.data.reactions}}):n)}getFromCache(){return y(this,null,function*(){var e;const t=yield this.mostRecentState.resultPromise;if(!t.ok)return M("NOT_IN_CACHE");if(null===t.value.data)return _({status:404,errorCode:"MESSAGE_NOT_FOUND",reasons:["No message with that ID exists"]});const n=t.value,{sender:s}=n,r=f(n,["sender"]),i={};return r.data.reactions.forEach(e=>{i[e.emoji]={count:e.count,currentUserReacted:e.currentUserReacted}}),E({status:200,data:p(d({},r.data),{senderId:null!=(e=null==s?void 0:s.store.userId)?e:null,reactions:i})})})}}function De(e,t){if(void 0===t)return e;const n=e.map(e=>{const n=t[e.emoji];return void 0===n?e:H(null===n?p(d({},e),{count:0}):{emoji:e.emoji,count:Y(e.count,n.count),currentUserReacted:Y(e.currentUserReacted,n.currentUserReacted)})}).filter(e=>e.count>0),s=new Set(n.map(e=>e.emoji));for(const r in t){const e=t[r];e&&!s.has(r)&&n.push(H({emoji:r,count:e.count,currentUserReacted:e.currentUserReacted}))}return n.sort((e,t)=>e.emoji.localeCompare(t.emoji)),H(n)}class Re extends de{constructor(e,t,n,s){super(e,{}),this.createdAt=t,this.dataStore=n,this.referencedDataStore=s}get messageId(){return this.dataStore.messageId}fetchInitial(e){return y(this,null,function*(){return E({lastChanged:e,dataStore:this.dataStore,referencedDataStore:this.referencedDataStore})})}refetch(e){throw"Do not call refetch on message stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return!0}teardownNested(e){}anyChildChanged(e,t,n){return y(this,arguments,function*(e,t,{dataStore:n,referencedDataStore:s}){return!0===(yield n.changedBetween(e,t))||!0===(yield null==s?void 0:s.changedBetween(e,t))})}loadNested(e,t){return y(this,null,function*(){var n,s,r;const i=yield t.dataStore.getDeep(e);if(!i.ok)return i;const a=i.value;if(null===a.snapshot)return E({snapshot:null});const o=yield null==(n=t.referencedDataStore)?void 0:n.getDeep(e);if(o&&!o.ok)return o;const l=null!=(s=null==o?void 0:o.value)?s:null,c=null!=(r=null==l?void 0:l.snapshot)?r:null;return E({snapshot:H({id:a.snapshot.id,type:a.snapshot.type,sender:a.snapshot.sender,custom:H(a.snapshot.custom),createdAt:a.snapshot.createdAt,editedAt:a.snapshot.editedAt,referencedMessage:c,origin:a.snapshot.origin,plaintext:a.snapshot.plaintext,content:a.snapshot.content,reactions:a.snapshot.reactions})})})}}class Oe extends pe{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e4,this.pendingLoadMore=void 0}listen(e){return this.onlyUsedInternally&&this.mostRecentState.resultPromise.then(e=>{if(e.ok&&null!==e.value.inWindow){const t=30-e.value.inWindow.length;t>0&&this.loadMore(t)}}),super.listen(e)}fetchInitial(e){return y(this,null,function*(){const t=this.onlyUsedInternally?1:30,n=yield Pe({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return n.ok?null===n.value.messages?E({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}):je({seq:e,messages:n.value.messages,cursor:n.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):n})}teardownNested(e){if(e.stores){const t=M("TERMINATED");Object.values(e.stores).forEach(e=>e.setError(t)),e.inWindow.forEach(e=>e.setError(t))}}anyChildChanged(e,t,n){return y(this,null,function*(){for(const s in n.stores){const r=n.stores[s];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1})}lastMessageChangedBetween(e,t){return y(this,null,function*(){if(e>=t)return!1;const n=yield this.get(t).resultPromise;if(!n.ok)return!1;if(n.value.lastMessageChanged>e)return!0;if(null===n.value.stores)return!1;const s=n.value.inWindow[0];return void 0!==s&&!0===(yield s.changedBetween(e,t))})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!K(Object.keys(e.stores),Object.keys(t.stores))&&!!K(e.inWindow.map(e=>e.messageId),t.inWindow.map(e=>e.messageId))&&K(e.windowEnd,t.windowEnd)}loadNested(e,t){return y(this,null,function*(){if(null===t.stores)return E({snapshot:null,loadedAll:!0});const n=yield Promise.all(t.inWindow.map(t=>t.getDeep(e))),s=n.find(e=>!e.ok);return s||E({snapshot:H(n.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot)),loadedAll:null===t.windowEnd})})}loadMore(e=30){return y(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=I();this.pendingLoadMore=t.promise;const n=yield this.mostRecentState.resultPromise;if(!n.ok){if("client"===n.where)throw t.reject(n.value),this.pendingLoadMore=void 0,n.value;{const e=R("Loading more messages",n.value);throw t.reject(n.value),this.pendingLoadMore=void 0,e}}if(null===n.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const s=n.value.windowEnd.cursor,r=yield Pe({count:e,cursor:s,conversationId:this.conversationId,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.messages.loadedmore",conversationId:this.conversationId,data:r})})}loadedMore(e,t){this.mutate(e,n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.messages?(console.warn("[TalkJS] When loading more messages, the conversation no longer existed. We should have been told about this."),n):je({seq:e,prevState:n.value,messages:t.data.value.messages,cursor:t.data.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t.data)}messageCreated(e,t){this.mutate(e,n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'message.created' event for a nonexistent conversation."),n;if(n.value.windowEnd&&t.state.createdAt<n.value.windowEnd.oldestMessageTs)return n;if(Object.hasOwnProperty.call(n.value.stores,t.state.id))return n;const s=d({},n.value.stores),r=new Ne(e,this.conversationId,t.state,this.realtimeClient);s[t.state.id]=r;const i=t.state.referencedMessageId;let a;null===i?a=null:i in s?a=s[i]:(a=new Ne(e,this.conversationId,i,this.realtimeClient),s[i]=a);const o=new Re(e,t.state.createdAt,r,a),l=[...n.value.inWindow,o];l.sort((e,t)=>t.createdAt-e.createdAt);const c=l[0].messageId===t.messageId?e:n.value.lastMessageChanged;return E({lastChanged:e,lastMessageChanged:c,stores:s,inWindow:l,windowEnd:n.value.windowEnd})})}messageEdited(e,t){this.mutate(e,n=>{var s;return null===n.value.stores?(console.warn("[TalkJS] Received a 'message.edited' event for a nonexistent conversation."),n):(null==(s=n.value.stores[t.messageId])||s.messageEdited(e,t),n)})}messageDeleted(e,t){this.mutate(e,n=>{if(null===n.value.stores)return console.warn("[TalkJS] Received a 'message.deleted' event for a conversation that we thought didn't exist."),n;if(Object.values(n.value.stores).forEach(n=>n.messageDeleted(e,t)),void 0===n.value.stores[t.messageId])return n;const s=d({},n.value.stores);delete s[t.messageId];const r=n.value.inWindow.filter(e=>e.messageId!==t.messageId);if(t.newLastMessage&&0===r.length){const n=new Ne(e,this.conversationId,t.newLastMessage,this.realtimeClient);s[n.messageId]=n;const i=t.newLastMessage.referencedMessageId;let a;null===i?a=null:i in s?a=s[i]:(a=new Ne(e,this.conversationId,i,this.realtimeClient),s[i]=a);const o=new Re(e,t.newLastMessage.createdAt,n,a);r.push(o)}const i=void 0!==t.newLastMessage?e:n.value.lastMessageChanged;return E({lastChanged:e,lastMessageChanged:i,stores:s,inWindow:r,windowEnd:n.value.windowEnd})})}conversationCleared(e,t){this.mutate(e,t=>{var n;return 0===(null==(n=t.value.inWindow)?void 0:n.length)&&null===t.value.windowEnd?t:(this.teardownNested(t.value),E({lastChanged:e,lastMessageChanged:e,stores:{},inWindow:[],windowEnd:null}))})}sideCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.stores?(n.then(e=>{e.ok&&this.teardownNested(e.value)}),e):n)}sideDeleted(e,t){this.mutate(e,t=>null===t.value.stores?t:(this.teardownNested(t.value),E({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null})))}getMessageFromCache(e){return y(this,null,function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return M("NOT_IN_CACHE");if(null===t.value.stores)return M("NOT_IN_CACHE");const n=t.value.stores[e];return void 0===n?M("NOT_IN_CACHE"):n.getFromCache()})}}function Pe(e){return y(this,arguments,function*({cursor:e,realtimeClient:t,conversationId:n,count:s}){const r={limit:s,cursor:e},i=yield t.call({method:"GET",path:["me","conversations",n,"messages"],data:r,flags:{bypassCache:!0}});if(i.ok){const{data:e,cursor:t}=i.value.data;return E({messages:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?E({messages:null,nextCursor:null}):i})}function je({seq:e,prevState:t,messages:n,cursor:s,conversationId:r,realtimeClient:i}){var a,o,l,c;const u=t?d({},t.stores):{};for(const d of n)if(void 0===u[d.id]){const t=new Ne(e,r,d,i);u[t.messageId]=t}for(const d of n){const t=d.referencedMessageId;if(t&&void 0===u[t]){const n=new Ne(e,r,t,i);u[n.messageId]=n}}const h=t?[...t.inWindow]:[];for(const d of n)h.push(new Re(e,d.createdAt,u[d.id],d.referencedMessageId?u[d.referencedMessageId]:null));h.sort((e,t)=>t.createdAt-e.createdAt);const p=(null==(o=null==(a=null==t?void 0:t.inWindow)?void 0:a[0])?void 0:o.messageId)===(null==(l=null==h?void 0:h[0])?void 0:l.messageId)&&null!=(c=null==t?void 0:t.lastMessageChanged)?c:e;return E(null===s?{lastChanged:e,lastMessageChanged:p,stores:u,inWindow:h,windowEnd:null}:{lastChanged:e,lastMessageChanged:p,stores:u,inWindow:h,windowEnd:{cursor:s,oldestMessageTs:n[n.length-1].createdAt}})}class $e extends pe{constructor(e,t,n,s,r){super(e,s,r),this.convData=t,this.realtimeClient=n,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return y(this,null,function*(){return E({lastChanged:e,convData:this.convData})})}teardownNested(e){e.convData.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,function*(){return n.convData.store.changedBetween(e,t)})}equal(e,t){return!0}loadNested(e,t){return y(this,null,function*(){return t.convData.store.getDeep(e)})}getFromCache(){return y(this,null,function*(){return this.convData.store.getFromCache()})}}function Ue(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(e[n],n)}function We(e,t){return function(e){let n={};return Ue(e,(e,s)=>{const[r,i]=(([e,n])=>[e,t(n,e)])([s,e],0);n[r]=i}),n}(e)}class qe extends pe{constructor(e,t,n,s,r){super(e,s,r),this.conversationId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return y(this,null,function*(){const t=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId,"typing"],data:{},flags:{bypassCache:!0}});if(!t.ok&&"server"===t.where&&404===t.value.status)return E({data:null,lastChanged:e});if(!t.ok&&"server"===t.where&&403===t.value.status&&"NOT_A_PARTICIPANT"===t.value.errorCode)return E({data:null,lastChanged:e});if(!t.ok)return t;const n=t.value.data;return n.many?E({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e}):E({data:n,userSubscriptions:We(n.usersTyping,(e,t)=>this.realtimeClient.internalSubscribe(["users",t])),lastChanged:e})})}equal(e,t){return K(e.data,t.data)}loadNested(e,t){return y(this,null,function*(){if(null===t.data)return E({snapshot:null,lastChanged:t.lastChanged});if(t.data.many)return E({snapshot:H({many:!0}),lastChanged:t.lastChanged});const n=Object.entries(t.data.usersTyping).sort(([e,t],[n,s])=>t-s).map(([e,t])=>e).map(n=>t.userSubscriptions[n].store.getDeep(e)),s=yield Promise.all(n),r=s.find(e=>!e.ok);if(r)return r;const i=s.map(e=>e.value),a=i.map(e=>e.snapshot),o=i.map(e=>e.lastChanged),l=Math.max(t.lastChanged,...o);return E({snapshot:H({users:H(a),many:!1}),lastChanged:l})})}typingAvailable(e,t){this.mutate(e,()=>E({data:t.state,userSubscriptions:t.state.many?{}:We(t.state.usersTyping,(e,t)=>this.realtimeClient.internalSubscribe(["users",t])),lastChanged:e}))}typingChanged(e,t){this.mutate(e,n=>{if(null===n.value.data)return n;if(void 0===t.diff.many){if(!0===n.value.data.many)return n;const s=d({},n.value.data.usersTyping),r=d({},n.value.userSubscriptions);return Ue(t.diff.usersTyping,(e,t)=>{var n;"number"==typeof e?(s[t]=e,r[t]=this.realtimeClient.internalSubscribe(["users",t])):null===e&&(delete s[t],null==(n=r[t])||n.unsubscribe(),delete r[t])}),E({data:{usersTyping:s,many:!1},userSubscriptions:r,lastChanged:e})}if(!0===t.diff.many)return n.value.data.many?n:E({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e});if(!1===t.diff.many){if(!1===n.value.data.many)return n;const s=We(t.diff.usersTyping,(e,t)=>this.realtimeClient.internalSubscribe(["users",t]));return E({data:t.diff,userSubscriptions:s,lastChanged:e})}throw t.diff,"Unreachable"})}sideDeleted(e,t){this.mutate(e,t=>null===t.value.data?t:E({data:null,lastChanged:e}))}teardownNested(e){e.data&&Ue(e.userSubscriptions,e=>e.unsubscribe())}anyChildChanged(e,t,n){return y(this,null,function*(){var s;if(null===n.data)return!1;for(const r in n.userSubscriptions){const i=n.userSubscriptions[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1})}}class Le extends pe{constructor(e,t,n,s,r,i){super(e,r,i),this.conversationId=t,this.participant=n,this.realtimeClient=s,this.unsubscribeDebounceMs=0}get userId(){return"string"==typeof this.participant?this.participant:this.participant.id}fetchInitial(e){return y(this,null,function*(){const t=this.realtimeClient.internalSubscribe(["users",this.userId]);if("object"==typeof this.participant)return E({lastChanged:e,user:t,data:this.participant});const n=yield Be(this.conversationId,this.userId,this.realtimeClient);return n.ok?E({lastChanged:e,user:t,data:n.value}):(t.unsubscribe(),n)})}refetch(e){throw"Do not call refetch on participant data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){var n,s,r,i;return(null==(s=null==(n=e.user)?void 0:n.store)?void 0:s.userId)===(null==(i=null==(r=t.user)?void 0:r.store)?void 0:i.userId)&&K(e.data,t.data)}teardownNested(e){e.user.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,function*(){var s;if(null===n.data)return!1;const r=null==(s=n.user)?void 0:s.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))})}loadNested(e,t){return y(this,null,function*(){if(null===t.data)return E({snapshot:null});const n=yield t.user.store.getDeep(e);if(!1===n.ok)return n;const s=n.value.snapshot;return E({snapshot:Me(t.data,s)})})}participantCreated(e,t){this.mutate(e,n=>null!==n.value.data?n:E({lastChanged:e,user:n.value.user,data:t.state}))}participantEdited(e,t){this.mutate(e,n=>null===n.value.data?n:E({lastChanged:e,user:n.value.user,data:{id:n.value.data.id,access:Y(n.value.data.access,t.diff.access),notify:Y(n.value.data.notify,t.diff.notify),joinedAt:n.value.data.joinedAt}}))}participantDeleted(e,t){this.mutate(e,t=>null===t.value.data?t:E({lastChanged:e,user:t.value.user,data:null}))}sideCreated(e,t){const n=Be(this.conversationId,this.userId,this.realtimeClient);this.mutate(e,t=>y(this,null,function*(){if(null!==t.value.data)return t;const s=yield n;return s.ok?E({lastChanged:e,user:t.value.user,data:s.value}):(this.teardownNested(t.value),s)}))}sideDeleted(e,t){this.mutate(e,t=>null===t.value.data?t:E({lastChanged:e,user:t.value.user,data:null}))}getFromCache(){return y(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.data?_({status:404,errorCode:"PARTICIPANT_NOT_FOUND",reasons:["No participant with that ID exists"]}):E({status:200,data:e.value.data}):M("NOT_IN_CACHE")})}}function Be(e,t,n){return y(this,null,function*(){const s=yield n.call({method:"GET",path:["me","conversations",e,"participants",t],data:{},flags:{bypassCache:!0}});return s.ok?E(s.value.data):"server"===s.where&&404===s.value.status||"server"===s.where&&403===s.value.status&&"NOT_A_PARTICIPANT"===s.value.errorCode?E(null):s})}class Ge extends pe{constructor(e,t,n,s,r,i){super(e,r,i),this.getParticipantDataStore=t,this.conversationId=n,this.realtimeClient=s,this.handlers=i,this.unsubscribeDebounceMs=3e4,this.pendingLoadMore=void 0}fetchInitial(e){return y(this,null,function*(){const t=yield Fe({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:10});return t.ok?null===t.value.participants?E({lastChanged:e,stores:null,inWindow:null,windowEnd:null}):He({seq:e,participants:t.value.participants,cursor:t.value.nextCursor,getParticipantDataStore:this.getParticipantDataStore}):t})}teardownNested(e){null!==e.stores&&Object.values(e.stores).forEach(e=>e.unsubscribe())}anyChildChanged(e,t,n){return y(this,null,function*(){var s;for(const r in n.stores){const i=n.stores[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!K(Object.keys(e.stores),Object.keys(t.stores))&&K(e.windowEnd,t.windowEnd)}loadNested(e,t){return y(this,null,function*(){if(null===t.stores)return E({snapshot:null,loadedAll:!0});const n=yield Promise.all(Object.values(t.stores).map(t=>t.store.getDeep(e))),s=n.find(e=>!e.ok);if(s)return s;const r=n.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot);return r.sort((e,t)=>t.joinedAt-e.joinedAt),E({snapshot:H(r),loadedAll:null===t.windowEnd})})}loadMore(e=10){return y(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=I();this.pendingLoadMore=t.promise;const n=yield this.mostRecentState.resultPromise;if(!n.ok){if("client"===n.where)throw t.reject(n.value),this.pendingLoadMore=void 0,n.value;{const e=R("Loading more participants",n.value);throw t.reject(e),this.pendingLoadMore=void 0,e}}if(null===n.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const s=n.value.windowEnd.cursor,r=yield Fe({count:e,cursor:s,conversationId:this.conversationId,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.participants.loadedmore",conversationId:this.conversationId,data:r})})}loadedMore(e,t){this.mutate(e,n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.participants?(console.warn("[TalkJS] When loading more participants, the conversation no longer existed. We should have been told about this."),n):He({seq:e,prevStores:n.value.stores,participants:t.data.value.participants,cursor:t.data.value.nextCursor,getParticipantDataStore:this.getParticipantDataStore}):t.data)}participantCreated(e,t){const n=this.getParticipantDataStore(t.state);this.mutate(e,s=>{let r=s.value.stores;return null===r&&(console.warn("[TalkJS] Received a 'participant.created' event when we thought the conversation didn't exist."),r={}),Object.hasOwnProperty.call(r,t.userId)?(n.unsubscribe(),s):E({lastChanged:e,stores:p(d({},r),{[t.userId]:n}),windowEnd:s.value.windowEnd})})}participantDeleted(e,t){this.mutate(e,n=>{var s;if(!Object.hasOwnProperty.call(n.value.stores,t.conversationId))return n;const r=d({},n.value.stores);return null==(s=r[t.userId])||s.unsubscribe(),delete r[t.userId],E({lastChanged:e,stores:r,windowEnd:n.value.windowEnd})})}sideCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.stores?(n.then(e=>{e.ok&&this.teardownNested(e.value)}),e):n)}sideDeleted(e,t){this.mutate(e,t=>null===t.value.stores?t:(this.teardownNested(t.value),E({lastChanged:e,stores:null,inWindow:null,windowEnd:null})))}}function Fe(e){return y(this,arguments,function*({cursor:e,realtimeClient:t,conversationId:n,count:s}){const r={limit:s,cursor:e},i=yield t.call({method:"GET",path:["me","conversations",n,"participants"],data:r,flags:{bypassCache:!0}});if(i.ok){const{data:e,cursor:t}=i.value.data;return E({participants:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?E({participants:null,nextCursor:null}):i})}function He({seq:e,prevStores:t,participants:n,cursor:s,getParticipantDataStore:r}){const i=t?d({},t):{};for(const a of n)void 0===i[a.id]&&(i[a.id]=r(a));return E(null===s?{lastChanged:e,stores:i,windowEnd:null}:{lastChanged:e,stores:i,windowEnd:{cursor:s,oldestParticipantTs:n[n.length-1].joinedAt}})}class ze extends pe{constructor(e,t,n,s,r){super(e,s,r),this.getConvDataStore=t,this.realtimeClient=n,this.handlers=r,this.unsubscribeDebounceMs=1e4,this.pendingLoadMore=void 0}fetchInitial(e){return y(this,null,function*(){const t=yield Je({realtimeClient:this.realtimeClient,count:20});return t.ok?null===t.value.conversations?E({lastChanged:e,stores:null,windowEnd:null}):Ye({seq:e,conversations:t.value.conversations,cursor:t.value.nextCursor,getConvDataStore:this.getConvDataStore}):t})}teardownNested(e){null!==e.stores&&Object.values(e.stores).forEach(e=>e.unsubscribe())}anyChildChanged(e,t,n){return y(this,null,function*(){var s;for(const r in n.stores){const i=n.stores[r];if(!0===(yield null==(s=null==i?void 0:i.store)?void 0:s.changedBetween(e,t)))return!0}return!1})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!K(Object.keys(e.stores),Object.keys(t.stores))&&K(e.windowEnd,t.windowEnd)}loadNested(e,t){return y(this,null,function*(){if(null===t.stores)return E({snapshot:H([]),loadedAll:!0});const n=yield Promise.all(Object.values(t.stores).map(t=>t.store.getDeep(e))),s=n.find(e=>!e.ok);if(s)return s;const r=n.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot);return r.sort((e,t)=>{var n,s,r,i;const a=null!=(s=null==(n=e.lastMessage)?void 0:n.createdAt)?s:e.joinedAt;return(null!=(i=null==(r=t.lastMessage)?void 0:r.createdAt)?i:t.joinedAt)-a}),E({snapshot:H(r),loadedAll:null===t.windowEnd})})}loadMore(e=20){return y(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=I();this.pendingLoadMore=t.promise;const n=yield this.mostRecentState.resultPromise;if(!n.ok){if("client"===n.where)throw t.reject(n.value),this.pendingLoadMore=void 0,n.value;{const e=R("Loading more conversations",n.value);throw t.reject(e),this.pendingLoadMore=void 0,e}}if(null===n.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const s=n.value.windowEnd.cursor,r=yield Je({count:e,cursor:s,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.conversations.loadedmore",data:r})})}loadedMore(e,t){this.mutate(e,n=>null===n.value.windowEnd?n:t.data.ok?null===t.data.value.conversations?(console.warn("[TalkJS] When loading more conversations, the user stopped existing, which should be impossible."),n):Ye({seq:e,prevStores:n.value.stores,conversations:t.data.value.conversations,cursor:t.data.value.nextCursor,getConvDataStore:this.getConvDataStore}):t.data)}userCreated(e,t){this.mutate(e,e=>null!==e.value.stores?e:E({lastChanged:e.value.lastChanged,stores:{},windowEnd:null}))}sideCreated(e,t){const n=this.getConvDataStore(t.state);this.mutate(e,s=>{let r=s.value.stores;return null===r&&(console.warn("[TalkJS] Received a 'side.created' event when we thought your user didn't exist."),r={}),Object.hasOwnProperty.call(r,t.conversationId)?(n.unsubscribe(),s):E({lastChanged:e,stores:p(d({},r),{[t.conversationId]:n}),windowEnd:s.value.windowEnd})})}sideDeleted(e,t){this.mutate(e,n=>{var s;if(!Object.hasOwnProperty.call(n.value.stores,t.conversationId))return n;const r=d({},n.value.stores);return null==(s=r[t.conversationId])||s.unsubscribe(),delete r[t.conversationId],E({lastChanged:e,stores:r,windowEnd:n.value.windowEnd})})}sideEdited(e,t){const n=t.diff.lastMessageAt;void 0!==n&&this.mutate(e,s=>{var r;if(null===s.value.stores)return console.warn("[TalkJS] Received a 'side.edited' event when we thought your user didn't exist."),s;if(null===s.value.windowEnd)return s;const i=Object.hasOwnProperty.call(s.value.stores,t.conversationId);if(i&&n<s.value.windowEnd.oldestMessageTs){const n=d({},s.value.stores);return null==(r=n[t.conversationId])||r.unsubscribe(),delete n[t.conversationId],E({lastChanged:e,stores:n,windowEnd:s.value.windowEnd})}if(!i&&n>=s.value.windowEnd.oldestMessageTs){const n=this.getConvDataStore(t.conversationId);return E({lastChanged:e,stores:p(d({},s.value.stores),{[t.conversationId]:n}),windowEnd:s.value.windowEnd})}return s})}}function Je(e){return y(this,arguments,function*({cursor:e,realtimeClient:t,count:n}){const s={limit:n,cursor:e},r=yield t.call({method:"GET",path:["me","conversations"],data:s,flags:{bypassCache:!0}});if(r.ok){const{data:e,cursor:t}=r.value.data;return E({conversations:e,nextCursor:t})}return r.ok||"server"!==r.where||404!==r.value.status||"USER_NOT_FOUND"!==r.value.errorCode?r:E({conversations:null,nextCursor:null})})}function Ye({seq:e,prevStores:t,conversations:n,cursor:s,getConvDataStore:r}){const i=t?d({},t):{};for(const a of n)void 0===i[a.id]&&(i[a.id]=r(a));return E(null===s?{lastChanged:e,stores:i,windowEnd:null}:{lastChanged:e,stores:i,windowEnd:{cursor:s,oldestMessageTs:Math.min(...n.map(e=>e.lastMessageAt))}})}class Qe extends pe{constructor(e,t,n,s,r){super(e,s,r),this.conversation=t,this.realtimeClient=n,this.unsubscribeDebounceMs=0}get conversationId(){return"string"==typeof this.conversation?this.conversation:this.conversation.id}fetchInitial(e){return y(this,null,function*(){const t=this.realtimeClient.internalSubscribe(["me","conversations",this.conversationId,"messages"]);if("object"==typeof this.conversation)return E({lastChanged:e,snapshot:this.conversation,messageWindow:t});const n=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId],data:{},flags:{bypassCache:!0}});let s;if(n.ok)s=n.value.data;else if("server"===n.where&&404===n.value.status)s=null;else{if("server"!==n.where||403!==n.value.status||"NOT_A_PARTICIPANT"!==n.value.errorCode)return t.unsubscribe(),n;s=null}return E({lastChanged:e,snapshot:s,messageWindow:t})})}teardownNested(e){var t;null==(t=e.messageWindow)||t.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,function*(){return!0===(yield n.messageWindow.store.lastMessageChangedBetween(e,t))})}equal(e,t){return K(e.snapshot,t.snapshot)}loadNested(e,t){return y(this,null,function*(){var n;if(!t.snapshot)return E({snapshot:null,loadedAll:!0});const s=yield t.messageWindow.store.getDeep(e);if(!s.ok)return s;const r=s.value.snapshot,i=null!=(n=null==r?void 0:r[0])?n:null;return E({snapshot:H(p(d({},t.snapshot),{custom:H(t.snapshot.custom),welcomeMessages:H(t.snapshot.welcomeMessages),lastMessage:i}))})})}participantEdited(e,t){this.mutate(e,n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'participant.edited' event for a conversation that we thought didn't exist."),n):E({lastChanged:e,snapshot:Ve(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow}))}conversationEdited(e,t){this.mutate(e,n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'conversation.edited' event for a conversation that we thought didn't exist."),n):E({lastChanged:e,snapshot:Ve(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow}))}sideEdited(e,t){this.mutate(e,n=>null===n.value.snapshot?(console.warn("[TalkJS] Received a 'side.edited' event for a conversation that we thought didn't exist."),n):E({lastChanged:e,snapshot:Ve(n.value.snapshot,t.diff),messageWindow:n.value.messageWindow}))}sideCreated(e,t){this.mutate(e,n=>n.value.snapshot?n:E({lastChanged:e,snapshot:t.state,messageWindow:n.value.messageWindow}))}sideDeleted(e,t){this.mutate(e,t=>null===t.value.snapshot?t:E({lastChanged:e,snapshot:null,messageWindow:t.value.messageWindow}))}getFromCache(){return y(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok&&e.value.snapshot?E({status:200,data:e.value.snapshot}):M("NOT_IN_CACHE")})}}function Ve(e,t){const n=t;return{id:e.id,createdAt:e.createdAt,subject:Y(e.subject,n.subject),photoUrl:Y(e.photoUrl,n.photoUrl),welcomeMessages:Q(e.welcomeMessages,n.welcomeMessages),custom:V(e.custom,n.custom),lastMessageAt:Y(e.lastMessageAt,n.lastMessageAt),unreadMessageCount:Y(e.unreadMessageCount,n.unreadMessageCount),isUnread:Y(e.isUnread,n.isUnread),access:Y(e.access,n.access),notify:Y(e.notify,n.notify),readUntil:Y(e.readUntil,n.readUntil),everyoneReadUntil:Y(e.everyoneReadUntil,n.everyoneReadUntil),joinedAt:e.joinedAt}}class Ke extends pe{constructor(e,t,n,s,r){super(e,s,r),this.userId=t,this.realtimeClient=n,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return y(this,null,function*(){const t=this.realtimeClient.internalSubscribe(["users",this.userId]),n=yield this.realtimeClient.call({method:"GET",path:["users",this.userId,"online"],data:{},flags:{bypassCache:!0}});return n.ok||"server"!==n.where||404!==n.value.status||"USER_NOT_FOUND"!==n.value.errorCode?n.ok?E({lastChanged:e,user:t,data:n.value.data}):n:E({lastChanged:e,user:t,data:null})})}equal(e,t){return K(e.data,t.data)}teardownNested(e){e.user.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,function*(){return n.user.store.changedBetween(e,t)})}loadNested(e,t){return y(this,null,function*(){const n=yield t.user.store.getDeep(e);if(!n.ok)return n;const s=n.value.snapshot;return null===t.data||null===s?E({snapshot:null}):E({snapshot:H(p(d({},t.data),{user:s}))})})}userCreated(e,t){const n=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.data?(n.then(e=>{e.ok&&this.teardownNested(e.value)}),e):n)}userOnlineChanged(e,t){this.mutate(e,n=>null===n.value.data?n:E({lastChanged:e,user:n.value.user,data:t.diff}))}getFromCache(){return y(this,null,function*(){const e=yield this.mostRecentState.resultPromise;if(!e.ok)return M("NOT_IN_CACHE");if(null===e.value.data)return _({status:404,errorCode:"USER_NOT_FOUND",reasons:["No user with that ID exists"]});const t=e.value,{user:n}=t,s=f(t,["user"]);return E({status:200,data:d({},s.data)})})}}class Ze extends pe{constructor(e,t,n,s,r){super(e,s,r),this.participantData=t,this.realtimeClient=n,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return y(this,null,function*(){return E({lastChanged:e,participantData:this.participantData})})}teardownNested(e){e.participantData.unsubscribe()}anyChildChanged(e,t,n){return y(this,null,function*(){return n.participantData.store.changedBetween(e,t)})}equal(e,t){return!0}loadNested(e,t){return y(this,null,function*(){return t.participantData.store.getDeep(e)})}}class Xe{constructor(e,t,n){this.realtimeClient=n,this.convDataStores={},this.participantDataStores={},this.storeMap={},this.emitMutex=new ce,this.virtualSeqOffset=0,this.realPublishSeq=0,this.refetchOnNextNetworkLoss=!0,this.connection=new le(e,t,{onUpstreamRestarting:()=>{this.refetchOnNextNetworkLoss=!1},onReady:()=>{this.refetchOnNextNetworkLoss=!0},onResubscribeSent:()=>{if(this.virtualSeqOffset+=this.realPublishSeq,this.realPublishSeq=0,this.refetchOnNextNetworkLoss){this.virtualSeqOffset++;const e=this.virtualSeq;this.refetchAll(e),this.emitAll(e)}},onResubscribeError:(e,t)=>{var n;null==(n=this.storeMap[et(e)])||n.setError(t)},onPublish:(e,t)=>{this.realPublishSeq=e;const n=this.virtualSeq;for(const s of t)this.handlePublish(n,s);this.emitAll(n)}})}get virtualSeq(){return this.realPublishSeq+this.virtualSeqOffset}sync(){return y(this,null,function*(){yield this.connection.sync(),yield this.emitMutex.sync()})}refetchAll(e){Object.values(this.storeMap).forEach(t=>null==t?void 0:t.refetch(e))}emitAll(e){return this.emitMutex.runExclusive(()=>y(this,null,function*(){const t=Object.values(this.storeMap).map(t=>null==t?void 0:t.emit(e));yield Promise.all(t)}))}handlePublish(e,t){var n,s,r,i,a,o,l,c,u,h,d,p,f,m,g,v,b,y,w,k,S,C,T,I,x,E,M,_,A,N,D,R,O,P,j,$,U;switch(t.type){case"user.created":return null==(n=this.storeMap[`/users/${t.userId}`])||n.userCreated(e,t),null==(s=this.storeMap["/me/conversations"])||s.userCreated(e,t),void(null==(r=this.storeMap[`/users/${t.userId}/online`])||r.userCreated(e,t));case"user.edited":return void(null==(i=this.storeMap[`/users/${t.userId}`])||i.userEdited(e,t));case"side.created":return null==(a=this.convDataStores[t.conversationId])||a.sideCreated(e,t),Object.values(null!=(o=this.participantDataStores[t.conversationId])?o:{}).forEach(n=>n.sideCreated(e,t)),null==(l=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||l.sideCreated(e,t),null==(c=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||c.sideCreated(e,t),void(null==(u=this.storeMap["/me/conversations"])||u.sideCreated(e,t));case"side.edited":return null==(h=this.convDataStores[t.conversationId])||h.sideEdited(e,t),void(null==(d=this.storeMap["/me/conversations"])||d.sideEdited(e,t));case"side.deleted":return null==(p=this.convDataStores[t.conversationId])||p.sideDeleted(e,t),Object.values(null!=(f=this.participantDataStores[t.conversationId])?f:{}).forEach(n=>n.sideDeleted(e,t)),null==(m=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||m.sideDeleted(e,t),null==(g=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||g.sideDeleted(e,t),null==(v=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||v.sideDeleted(e,t),void(null==(b=this.storeMap["/me/conversations"])||b.sideDeleted(e,t));case"conversation.edited":return void(null==(y=this.convDataStores[t.conversationId])||y.conversationEdited(e,t));case"message.created":return void(null==(w=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||w.messageCreated(e,t));case"message.edited":return void(null==(k=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||k.messageEdited(e,t));case"message.deleted":return void(null==(S=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||S.messageDeleted(e,t));case"typing.available":return void(null==(C=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||C.typingAvailable(e,t));case"typing.changed":return void(null==(T=this.storeMap[`/me/conversations/${t.conversationId}/typing`])||T.typingChanged(e,t));case"conversation.cleared":return void(null==(I=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||I.conversationCleared(e,t));case"participant.edited":return null==(x=this.convDataStores[t.conversationId])||x.participantEdited(e,t),void(null==(M=null==(E=this.participantDataStores[t.conversationId])?void 0:E[t.userId])||M.participantEdited(e,t));case"participant.created":return null==(A=null==(_=this.participantDataStores[t.conversationId])?void 0:_[t.userId])||A.participantCreated(e,t),void(null==(N=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||N.participantCreated(e,t));case"participant.deleted":return null==(R=null==(D=this.participantDataStores[t.conversationId])?void 0:D[t.userId])||R.participantDeleted(e,t),void(null==(O=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||O.participantDeleted(e,t));case"user.online.changed":return void(null==(P=this.storeMap[`/users/${t.userId}/online`])||P.userOnlineChanged(e,t));case"virtual.conversations.loadedmore":return void(null==(j=this.storeMap["/me/conversations"])||j.loadedMore(e,t));case"virtual.messages.loadedmore":return void(null==($=this.storeMap[`/me/conversations/${t.conversationId}/messages`])||$.loadedMore(e,t));case"virtual.participants.loadedmore":return void(null==(U=this.storeMap[`/me/conversations/${t.conversationId}/participants`])||U.loadedMore(e,t))}}call(e){return y(this,arguments,function*({method:e,path:t,data:n,headers:s,flags:r}){var i;if(!0!==(null==r?void 0:r.bypassCache)&&"GET"===e){const e=et(t);if(e in this.storeMap){const t=e,n=this.storeMap[t];if(n&&"getFromCache"in n){yield this.sync();const e=yield n.getFromCache();if("NOT_IN_CACHE"!==e.value)return e}}else if(w(t,["me","conversations","*","messages","*"])){const e=this.storeMap[`/me/conversations/${t[2]}/messages`];if(e){yield this.sync();const n=yield e.getMessageFromCache(t[4]);if("NOT_IN_CACHE"!==n.value)return n}}else if(w(t,["me","conversations","*","participants","*"])){const e=null==(i=this.participantDataStores[t[2]])?void 0:i[t[4]];if(e){yield this.sync();const t=yield e.getFromCache();if("NOT_IN_CACHE"!==t.value)return t}}else if(w(t,["me","conversations","*"])){const e=this.convDataStores[t[2]];if(e){yield this.sync();const t=yield e.getFromCache();if("NOT_IN_CACHE"!==t.value)return t}}}return this.connection.call({method:e,path:t,data:n,headers:null!=s?s:{}})})}subscribe(e,t){const n=this.getOrCreateStore(e),s=I(),r=I();s.promise.catch(()=>{}),r.promise.catch(()=>{});const i={state:{type:"pending",latestSnapshot:void 0},connected:s.promise,terminated:r.promise,loadMore:e=>y(this,null,function*(){"loadMore"in n&&(yield n.loadMore(e))}),unsubscribe:()=>{}},a=n.listen(n=>{if(n.ok){const e=!("loadedAll"in n.value)||n.value.loadedAll,r={type:"active",latestSnapshot:n.value.snapshot,loadedAll:e};i.state=r,null==t||t(n.value.snapshot,e),s.resolve(r)}else if("pending"===i.state.type||"active"===i.state.type){if("server"===n.where){const t={type:"error",error:new Error(R(`Subscribe to ${e.join("/")}`,n.value))};return i.state=t,r.resolve(t),void s.reject("Subscription encountered an error during initial connection")}if("SESSION_DESTROYED"===n.value){const e={type:"error",error:new Error("Session was destroyed causing all subscriptions to be terminated")};return i.state=e,r.resolve(e),void s.reject("Subscription encountered an error during initial connection")}if("UNSUBSCRIBED"===n.value)return;if("TERMINATED"===n.value)return;n.value}});return i.unsubscribe=()=>{if("pending"===i.state.type||"active"===i.state.type){a();const e={type:"unsubscribed"};i.state=e,r.resolve(e),s.reject("Subscription was unsubscribed before connecting")}},i}onVirtualPublish(e){return y(this,null,function*(){this.virtualSeqOffset++;const t=this.virtualSeq;this.handlePublish(t,e),yield this.emitAll(t)})}getOrCreateStore(e){const t=et(e);if(t in this.storeMap)return this.storeMap[t];this.connection.subscribe(e).then(e=>{e.ok||n.setError(e)});const n=this.instantiateStore(e,()=>{delete this.storeMap[t],this.connection.unsubscribe(e)});return this.storeMap[t]=n,n}destroy(){this.storeMap={},this.convDataStores={},this.participantDataStores={},this.connection.destroy()}isConnected(){return this.connection.isConnected()}instantiateStore(e,t){if(w(e,["users","*"]))return new Ae(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});if(w(e,["me","conversations","*"]))return new $e(this.virtualSeq,this.subscribeConvData(e[2]),this.realtimeClient,this.emitMutex,{onTeardown:t});if(w(e,["me","conversations","*","messages"]))return new Oe(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(w(e,["me","conversations","*","participants"]))return new Ge(this.virtualSeq,t=>this.subscribeParticipantData(e[2],t),e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(w(e,["me","conversations","*","participants","*"]))return new Ze(this.virtualSeq,this.subscribeParticipantData(e[2],e[4]),this.realtimeClient,this.emitMutex,{onTeardown:t});if(w(e,["me","conversations","*","typing"]))return new qe(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t});if(w(e,["me","conversations"]))return new ze(this.virtualSeq,e=>this.subscribeConvData(e),this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(w(e,["users","*","online"]))return new Ke(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});throw"Unreachable"}subscribeConvData(e){const t="string"==typeof e?e:e.id;if(Object.hasOwnProperty.call(this.convDataStores,t)){const e=this.convDataStores[t];return{store:e,unsubscribe:e.registerInternalSubscription()}}const n=new Qe(this.virtualSeq,e,this.realtimeClient,this.emitMutex,{onTeardown:()=>{delete this.convDataStores[t]}});return this.convDataStores[t]=n,{store:n,unsubscribe:n.registerInternalSubscription()}}subscribeParticipantData(e,t){var n,s;const r="string"==typeof t?t:t.id,i=null==(n=this.participantDataStores[e])?void 0:n[r];if(i)return{store:i,unsubscribe:i.registerInternalSubscription()};const a=null!=(s=this.participantDataStores[e])?s:{},o=new Le(this.virtualSeq,e,t,this.realtimeClient,this.emitMutex,{onTeardown:()=>{delete a[r],0===Object.keys(a).length&&delete this.participantDataStores[e]}});return a[r]=o,this.participantDataStores[e]=a,{store:o,unsubscribe:o.registerInternalSubscription()}}}function et(e){return`/${e.join("/")}`}class tt{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get(){return y(this,null,function*(){const e=yield this._realtimeClient.getUser(this.brandedId);return xr("Get user "+this.id,e)})}set(e){return y(this,null,function*(){null===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,n="string"==typeof e.phone?[e.phone]:e.phone,s=yield this._realtimeClient.call({method:"PUT",path:["users",this.brandedId],data:p(d({},e),{email:t,phone:n})});D("Set user "+this.id,s)})}createIfNotExists(e){return y(this,null,function*(){void 0===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,n="string"==typeof e.phone?[e.phone]:e.phone,s=yield this._realtimeClient.call({method:"POST",path:["users",this.brandedId],data:p(d({},e),{email:t,phone:n})});(s.ok||"server"!==s.where||409!=s.value.status)&&D(`Create user ${this.id} if not exists`,s)})}subscribe(e){return this._realtimeClient.subscribe(["users",this.brandedId],e)}subscribeOnline(e){return this._realtimeClient.subscribe(["users",this.brandedId,"online"],e)}}function nt(e){const t="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let n=0;const s=[],r=e===n;n=e;const i=new Array(8);for(let o=7;o>=0;o--)i[o]=t.charAt(e%64),e=Math.floor(e/64);if(0!==e)throw new Error("We should have converted the entire timestamp.");let a=i.join("");if(r){let e;for(e=11;e>=0&&63===s[e];e--)s[e]=0;s[e]++}else for(let o=0;o<12;o++)s[o]=Math.floor(64*Math.random());for(let o=0;o<12;o++)a+=t.charAt(s[o]);if(20!=a.length)throw new Error("Length should be 20.");return a}const st=(e,t,n=void 0)=>e.reduce((e,s,r)=>e.concat((e=>{if("string"==typeof e)return t(e,n);switch(e.type){case"bold":case"italic":case"strikethrough":case"blockquote":case"bulletlist":case"bulletList":case"bulletpoint":case"bulletPoint":return[{type:e.type,children:st(e.children,t,e.type)}];case"link":return[{type:e.type,url:e.url,children:st(e.children,t,e.type)}];case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return[{type:e.type,action:e.action,params:e.params,children:st(e.children,t,e.type)}];case"mention":case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"suppressed":case"emoji":case"customemoji":case"customEmoji":return[e]}})(s)),[]);function rt(e,t){return n=>{const s=n;let r=0;const i=[];for(const a of ve(n,e)){a.index-r>0&&i.push(s.substring(r,a.index));const e=t(a);Array.isArray(e)?i.push(...e):i.push(e),r=a.index+a[0].length}return r<n.length&&i.push(n.substring(r)),i}}const it="’'()[]{}<>:,‒–—―…!.«»-‐?‘’“”;/⁄␠·&@*\\•^¤¢$€£¥₩₪†‡°¡¿¬#№%‰‱¶′§~¨_|¦⁂☞∴‽※".replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var at,ot=((at=ot||{})[at.italic=1]="italic",at[at.strikethrough=2]="strikethrough",at[at.bold=4]="bold",at);const lt=[0,1,2,3,4,5,6].map(e=>{const t=[];return 1&e||t.push(/_([^\s_].*?[^\s_])_|_([^\s_])_/),2&e||t.push(/~([^\s~].*?[^\s~])~|~([^\s~])~/),4&e||t.push(/\*([^\s*].*?[^\s*])\*|\*([^\s*])\*/),new RegExp(t.map(e=>e.source).join("|"),"g")}),ct={_:1,"*":4,"~":2};function ut(e){return ht(e,0)}function ht(e,t=0){const n=lt[t],s=n?function(e){const t=rt(dt.getOrCompute(e,()=>new RegExp(`(?:^|[\\s${it}])(?:${e.source})(?=[\\s${it}]|$)`,"g")),e=>{const t=e[0][1],n=e[1]||e[2]||e[3]||e[4]||e[5]||e[6];return[" ",{type:ot[ct[t]],children:[n]}]});return e=>{const[n,...s]=t(" "+e);return n.length>1&&s.unshift(n.substring(1)),s}}(n):()=>[e];return st(s(e),(e,n)=>"bold"===n||"italic"===n||"strikethrough"===n?ht(e,t|ot[n]):[e])}const dt=function(){const e=function(){try{return new WeakMap}catch(e){const t={has:()=>!1,get:()=>{},set:()=>t};return t}}();return{getOrCompute(t,n){if(e.has(t))return e.get(t);const s=n();return e.set(t,s),s}}}();var pt=function(e,t){return(pt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};function ft(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}pt(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var mt=function(){return mt=Object.assign||function(e){for(var t,n=1,s=arguments.length;n<s;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},mt.apply(this,arguments)};"function"==typeof SuppressedError&&SuppressedError;var gt=Object.prototype.hasOwnProperty;function vt(e){return"boolean"==typeof e}function bt(e,t){for(var n=e.length-1;n>=0;n--)!0===t(e[n])&&e.splice(n,1)}function yt(e){throw new Error("Unhandled case for value: '".concat(e,"'"))}var wt=/\s+/,kt=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.tagName=e.tagName||"",this.attrs=e.attrs||{},this.innerHTML=e.innerHtml||e.innerHTML||""}return e.prototype.setTagName=function(e){return this.tagName=e,this},e.prototype.getTagName=function(){return this.tagName},e.prototype.setAttr=function(e,t){return this.getAttrs()[e]=t,this},e.prototype.getAttr=function(e){return this.getAttrs()[e]},e.prototype.setAttrs=function(e){return Object.assign(this.getAttrs(),e),this},e.prototype.getAttrs=function(){return this.attrs},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,n=this.getClass(),s=n?n.split(wt):[],r=e.split(wt);t=r.shift();)-1===s.indexOf(t)&&s.push(t);return this.getAttrs().class=s.join(" "),this},e.prototype.removeClass=function(e){for(var t,n=this.getClass(),s=n?n.split(wt):[],r=e.split(wt);s.length&&(t=r.shift());){var i=s.indexOf(t);-1!==i&&s.splice(i,1)}return this.getAttrs().class=s.join(" "),this},e.prototype.getClass=function(){return this.getAttrs().class||""},e.prototype.hasClass=function(e){return-1!==(" "+this.getClass()+" ").indexOf(" "+e+" ")},e.prototype.setInnerHTML=function(e){return this.innerHTML=e,this},e.prototype.setInnerHtml=function(e){return this.setInnerHTML(e)},e.prototype.getInnerHTML=function(){return this.innerHTML||""},e.prototype.getInnerHtml=function(){return this.getInnerHTML()},e.prototype.toAnchorString=function(){var e=this.getTagName(),t=this.buildAttrsStr();return["<",e,t=t?" "+t:"",">",this.getInnerHtml(),"</",e,">"].join("")},e.prototype.buildAttrsStr=function(){var e=this.getAttrs(),t=[];for(var n in e)gt.call(e,n)&&t.push(n+'="'+e[n]+'"');return t.join(" ")},e}();function St(e){var t="";return e.scheme&&e.host&&(t+=e.scheme+"://"),e.host&&(t+=e.host),e.path&&(t+="/"+e.path),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t}function Ct(e,t,n){var s=t/2,r=Math.ceil(s),i=-1*Math.floor(s),a="";return i<0&&(a=e.substr(i)),e.substr(0,r)+n+a}var Tt=function(){function e(e){void 0===e&&(e={}),this.newWindow=!1,this.truncate={},this.className="",this.newWindow=e.newWindow||!1,this.truncate=e.truncate||{},this.className=e.className||""}return e.prototype.build=function(e){return new kt({tagName:"a",attrs:this.createAttrs(e),innerHtml:this.processAnchorText(e.getAnchorText())})},e.prototype.createAttrs=function(e){var t={href:e.getAnchorHref()},n=this.createCssClass(e);return n&&(t.class=n),this.newWindow&&(t.target="_blank",t.rel="noopener noreferrer"),this.truncate.length&&this.truncate.length<e.getAnchorText().length&&(t.title=e.getAnchorHref()),t},e.prototype.createCssClass=function(e){var t=this.className;if(t){for(var n=[t],s=e.getCssClassSuffixes(),r=0,i=s.length;r<i;r++)n.push(t+"-"+s[r]);return n.join(" ")}return""},e.prototype.processAnchorText=function(e){return this.doTruncate(e)},e.prototype.doTruncate=function(e){var t=this.truncate;if(!t.length)return e;var n,s,r,i,a=t.length,o=t.location;return"smart"===o?function(e,t,n){var s,r;if(null==n?(n="…",r=3,s=8):(r=n.length,s=n.length),e.length<=t)return e;var i,a,o,l=t-r,c=(i={},(o=(a=e).match(/^([a-z]+):\/\//i))&&(i.scheme=o[1],a=a.slice(o[0].length)),(o=a.match(/^(.*?)(?=(\?|#|\/|$))/i))&&(i.host=o[1],a=a.slice(o[0].length)),(o=a.match(/^\/(.*?)(?=(\?|#|$))/i))&&(i.path=o[1],a=a.slice(o[0].length)),(o=a.match(/^\?(.*?)(?=(#|$))/i))&&(i.query=o[1],a=a.slice(o[0].length)),(o=a.match(/^#(.*?)$/i))&&(i.fragment=o[1]),i);if(c.query){var u=c.query.match(/^(.*?)(?=(\?|#))(.*?)$/i);u&&(c.query=c.query.substr(0,u[1].length),e=St(c))}if(e.length<=t)return e;if(c.host&&(c.host=c.host.replace(/^www\./,""),e=St(c)),e.length<=t)return e;var h="";if(c.host&&(h+=c.host),h.length>=l)return c.host.length===t?(c.host.substr(0,t-r)+n).substr(0,l+s):Ct(h,l,n).substr(0,l+s);var d="";if(c.path&&(d+="/"+c.path),c.query&&(d+="?"+c.query),d){if((h+d).length>=l)return(h+d).length==t?(h+d).substr(0,t):(h+Ct(d,l-h.length,n)).substr(0,l+s);h+=d}if(c.fragment){var p="#"+c.fragment;if((h+p).length>=l)return(h+p).length==t?(h+p).substr(0,t):(h+Ct(p,l-h.length,n)).substr(0,l+s);h+=p}if(c.scheme&&c.host){var f=c.scheme+"://";if((h+f).length<l)return(f+h).substr(0,t)}if(h.length<=t)return h;var m="";return l>0&&(m=h.substr(-1*Math.floor(l/2))),(h.substr(0,Math.ceil(l/2))+n+m).substr(0,l+s)}(e,a):"middle"===o?function(e,t,n){if(e.length<=t)return e;var s,r;null==n?(n="…",s=8,r=3):(s=n.length,r=n.length);var i=t-r,a="";return i>0&&(a=e.substr(-1*Math.floor(i/2))),(e.substr(0,Math.ceil(i/2))+n+a).substr(0,i+s)}(e,a):(s=a,r=void 0,(n=e).length>s&&(null==r?(r="…",i=3):i=r.length,n=n.substring(0,s-i)+r),n)},e}(),It=function(){function e(e){this._=null,this.matchedText="",this.offset=0,this.tagBuilder=e.tagBuilder,this.matchedText=e.matchedText,this.offset=e.offset}return e.prototype.getMatchedText=function(){return this.matchedText},e.prototype.setOffset=function(e){this.offset=e},e.prototype.getOffset=function(){return this.offset},e.prototype.getCssClassSuffixes=function(){return[this.type]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}();function xt(e){return e>=65&&e<=90||e>=97&&e<=122}function Et(e){return e>=48&&e<=57}function Mt(e){return 34==e||39==e}function _t(e){return e<8232?e<160?e>=9&&e<=13||32==e:e<5760?160==e:5760==e||e>=8192&&e<=8202:e<8287?e>=8232&&e<=8233||8239==e:e<12288?8287==e:12288==e||65279==e}function At(e){return e<4800?e<2949?e<2451?e<1425?e<768?e<192?e<169?e<65?e>=48&&e<=57:e>=65&&e<=90||e>=97&&e<=122:e<181?e>=169&&e<=170||174==e:181==e||186==e:e<710?e<216?e>=192&&e<=214:e>=216&&e<=246||e>=248&&e<=705:e<748?e>=710&&e<=721||e>=736&&e<=740:748==e||750==e:e<910?e<895?e<886?e>=768&&e<=884:e>=886&&e<=887||e>=890&&e<=893:e<904?895==e||902==e:e>=904&&e<=906||908==e:e<1155?e<931?e>=910&&e<=929:e>=931&&e<=1013||e>=1015&&e<=1153:e<1369?e>=1155&&e<=1327||e>=1329&&e<=1366:1369==e||e>=1377&&e<=1415:e<1808?e<1552?e<1476?e<1471?e>=1425&&e<=1469:1471==e||e>=1473&&e<=1474:e<1488?e>=1476&&e<=1477||1479==e:e>=1488&&e<=1514||e>=1520&&e<=1522:e<1749?e<1568?e>=1552&&e<=1562:e>=1568&&e<=1641||e>=1646&&e<=1747:e<1770?e>=1749&&e<=1756||e>=1759&&e<=1768:e>=1770&&e<=1788||1791==e:e<2230?e<2042?e<1869?e>=1808&&e<=1866:e>=1869&&e<=1969||e>=1984&&e<=2037:e<2112?2042==e||e>=2048&&e<=2093:e>=2112&&e<=2139||e>=2208&&e<=2228:e<2406?e<2260?e>=2230&&e<=2237:e>=2260&&e<=2273||e>=2275&&e<=2403:e<2437?e>=2406&&e<=2415||e>=2417&&e<=2435:e>=2437&&e<=2444||e>=2447&&e<=2448:e<2693?e<2579?e<2519?e<2486?e<2474?e>=2451&&e<=2472:e>=2474&&e<=2480||2482==e:e<2503?e>=2486&&e<=2489||e>=2492&&e<=2500:e>=2503&&e<=2504||e>=2507&&e<=2510:e<2534?e<2524?2519==e:e>=2524&&e<=2525||e>=2527&&e<=2531:e<2565?e>=2534&&e<=2545||e>=2561&&e<=2563:e>=2565&&e<=2570||e>=2575&&e<=2576:e<2631?e<2613?e<2602?e>=2579&&e<=2600:e>=2602&&e<=2608||e>=2610&&e<=2611:e<2620?e>=2613&&e<=2614||e>=2616&&e<=2617:2620==e||e>=2622&&e<=2626:e<2649?e<2635?e>=2631&&e<=2632:e>=2635&&e<=2637||2641==e:e<2662?e>=2649&&e<=2652||2654==e:e>=2662&&e<=2677||e>=2689&&e<=2691:e<2821?e<2759?e<2730?e<2703?e>=2693&&e<=2701:e>=2703&&e<=2705||e>=2707&&e<=2728:e<2741?e>=2730&&e<=2736||e>=2738&&e<=2739:e>=2741&&e<=2745||e>=2748&&e<=2757:e<2784?e<2763?e>=2759&&e<=2761:e>=2763&&e<=2765||2768==e:e<2809?e>=2784&&e<=2787||e>=2790&&e<=2799:2809==e||e>=2817&&e<=2819:e<2887?e<2858?e<2831?e>=2821&&e<=2828:e>=2831&&e<=2832||e>=2835&&e<=2856:e<2869?e>=2858&&e<=2864||e>=2866&&e<=2867:e>=2869&&e<=2873||e>=2876&&e<=2884:e<2911?e<2902?e>=2887&&e<=2888||e>=2891&&e<=2893:e>=2902&&e<=2903||e>=2908&&e<=2909:e<2929?e>=2911&&e<=2915||e>=2918&&e<=2927:2929==e||e>=2946&&e<=2947:e<3517?e<3205?e<3046?e<2984?e<2969?e<2958?e>=2949&&e<=2954:e>=2958&&e<=2960||e>=2962&&e<=2965:e<2974?e>=2969&&e<=2970||2972==e:e>=2974&&e<=2975||e>=2979&&e<=2980:e<3014?e<2990?e>=2984&&e<=2986:e>=2990&&e<=3001||e>=3006&&e<=3010:e<3024?e>=3014&&e<=3016||e>=3018&&e<=3021:3024==e||3031==e:e<3142?e<3086?e<3072?e>=3046&&e<=3055:e>=3072&&e<=3075||e>=3077&&e<=3084:e<3114?e>=3086&&e<=3088||e>=3090&&e<=3112:e>=3114&&e<=3129||e>=3133&&e<=3140:e<3160?e<3146?e>=3142&&e<=3144:e>=3146&&e<=3149||e>=3157&&e<=3158:e<3174?e>=3160&&e<=3162||e>=3168&&e<=3171:e>=3174&&e<=3183||e>=3200&&e<=3203:e<3333?e<3274?e<3242?e<3214?e>=3205&&e<=3212:e>=3214&&e<=3216||e>=3218&&e<=3240:e<3260?e>=3242&&e<=3251||e>=3253&&e<=3257:e>=3260&&e<=3268||e>=3270&&e<=3272:e<3296?e<3285?e>=3274&&e<=3277:e>=3285&&e<=3286||3294==e:e<3313?e>=3296&&e<=3299||e>=3302&&e<=3311:e>=3313&&e<=3314||e>=3329&&e<=3331:e<3423?e<3389?e<3342?e>=3333&&e<=3340:e>=3342&&e<=3344||e>=3346&&e<=3386:e<3402?e>=3389&&e<=3396||e>=3398&&e<=3400:e>=3402&&e<=3406||e>=3412&&e<=3415:e<3458?e<3430?e>=3423&&e<=3427:e>=3430&&e<=3439||e>=3450&&e<=3455:e<3482?e>=3458&&e<=3459||e>=3461&&e<=3478:e>=3482&&e<=3505||e>=3507&&e<=3515:e<3804?e<3722?e<3570?e<3535?e<3520?3517==e:e>=3520&&e<=3526||3530==e:e<3544?e>=3535&&e<=3540||3542==e:e>=3544&&e<=3551||e>=3558&&e<=3567:e<3664?e<3585?e>=3570&&e<=3571:e>=3585&&e<=3642||e>=3648&&e<=3662:e<3716?e>=3664&&e<=3673||e>=3713&&e<=3714:3716==e||e>=3719&&e<=3720:e<3754?e<3737?e<3725?3722==e:3725==e||e>=3732&&e<=3735:e<3749?e>=3737&&e<=3743||e>=3745&&e<=3747:3749==e||3751==e:e<3776?e<3757?e>=3754&&e<=3755:e>=3757&&e<=3769||e>=3771&&e<=3773:e<3784?e>=3776&&e<=3780||3782==e:e>=3784&&e<=3789||e>=3792&&e<=3801:e<4176?e<3902?e<3872?e<3840?e>=3804&&e<=3807:3840==e||e>=3864&&e<=3865:e<3895?e>=3872&&e<=3881||3893==e:3895==e||3897==e:e<3974?e<3913?e>=3902&&e<=3911:e>=3913&&e<=3948||e>=3953&&e<=3972:e<4038?e>=3974&&e<=3991||e>=3993&&e<=4028:4038==e||e>=4096&&e<=4169:e<4688?e<4301?e<4256?e>=4176&&e<=4253:e>=4256&&e<=4293||4295==e:e<4348?4301==e||e>=4304&&e<=4346:e>=4348&&e<=4680||e>=4682&&e<=4685:e<4746?e<4698?e>=4688&&e<=4694||4696==e:e>=4698&&e<=4701||e>=4704&&e<=4744:e<4786?e>=4746&&e<=4749||e>=4752&&e<=4784:e>=4786&&e<=4789||e>=4792&&e<=4798:e<11035?e<7416?e<6176?e<5873?e<4992?e<4824?e<4802?4800==e:e>=4802&&e<=4805||e>=4808&&e<=4822:e<4888?e>=4824&&e<=4880||e>=4882&&e<=4885:e>=4888&&e<=4954||e>=4957&&e<=4959:e<5121?e<5024?e>=4992&&e<=5007:e>=5024&&e<=5109||e>=5112&&e<=5117:e<5761?e>=5121&&e<=5740||e>=5743&&e<=5759:e>=5761&&e<=5786||e>=5792&&e<=5866:e<6002?e<5920?e<5888?e>=5873&&e<=5880:e>=5888&&e<=5900||e>=5902&&e<=5908:e<5984?e>=5920&&e<=5940||e>=5952&&e<=5971:e>=5984&&e<=5996||e>=5998&&e<=6e3:e<6108?e<6016?e>=6002&&e<=6003:e>=6016&&e<=6099||6103==e:e<6155?e>=6108&&e<=6109||e>=6112&&e<=6121:e>=6155&&e<=6157||e>=6160&&e<=6169:e<6783?e<6512?e<6400?e<6272?e>=6176&&e<=6263:e>=6272&&e<=6314||e>=6320&&e<=6389:e<6448?e>=6400&&e<=6430||e>=6432&&e<=6443:e>=6448&&e<=6459||e>=6470&&e<=6509:e<6608?e<6528?e>=6512&&e<=6516:e>=6528&&e<=6571||e>=6576&&e<=6601:e<6688?e>=6608&&e<=6617||e>=6656&&e<=6683:e>=6688&&e<=6750||e>=6752&&e<=6780:e<7040?e<6832?e<6800?e>=6783&&e<=6793:e>=6800&&e<=6809||6823==e:e<6992?e>=6832&&e<=6846||e>=6912&&e<=6987:e>=6992&&e<=7001||e>=7019&&e<=7027:e<7245?e<7168?e>=7040&&e<=7155:e>=7168&&e<=7223||e>=7232&&e<=7241:e<7376?e>=7245&&e<=7293||e>=7296&&e<=7304:e>=7376&&e<=7378||e>=7380&&e<=7414:e<8450?e<8130?e<8025?e<7960?e<7424?e>=7416&&e<=7417:e>=7424&&e<=7669||e>=7675&&e<=7957:e<8008?e>=7960&&e<=7965||e>=7968&&e<=8005:e>=8008&&e<=8013||e>=8016&&e<=8023:e<8031?e<8027?8025==e:8027==e||8029==e:e<8118?e>=8031&&e<=8061||e>=8064&&e<=8116:e>=8118&&e<=8124||8126==e:e<8205?e<8150?e<8134?e>=8130&&e<=8132:e>=8134&&e<=8140||e>=8144&&e<=8147:e<8178?e>=8150&&e<=8155||e>=8160&&e<=8172:e>=8178&&e<=8180||e>=8182&&e<=8188:e<8305?e<8252?8205==e:8252==e||8265==e:e<8336?8305==e||8319==e:e>=8336&&e<=8348||e>=8400&&e<=8432:e<8579?e<8486?e<8469?e<8455?8450==e:8455==e||e>=8458&&e<=8467:e<8482?8469==e||e>=8473&&e<=8477:8482==e||8484==e:e<8495?e<8488?8486==e:8488==e||e>=8490&&e<=8493:e<8517?e>=8495&&e<=8505||e>=8508&&e<=8511:e>=8517&&e<=8521||8526==e:e<9410?e<9e3?e<8592?e>=8579&&e<=8580:e>=8592&&e<=8703||e>=8986&&e<=8987:e<9193?9e3==e||9167==e:e>=9193&&e<=9203||e>=9208&&e<=9210:e<9723?e<9654?9410==e||e>=9642&&e<=9643:9654==e||9664==e:e<10548?e>=9723&&e<=9726||e>=9728&&e<=10175:e>=10548&&e<=10549||e>=11013&&e<=11015:e<43259?e<12445?e<11688?e<11520?e<11264?e<11088?e>=11035&&e<=11036:11088==e||11093==e:e<11360?e>=11264&&e<=11310||e>=11312&&e<=11358:e>=11360&&e<=11492||e>=11499&&e<=11507:e<11568?e<11559?e>=11520&&e<=11557:11559==e||11565==e:e<11647?e>=11568&&e<=11623||11631==e:e>=11647&&e<=11670||e>=11680&&e<=11686:e<11744?e<11712?e<11696?e>=11688&&e<=11694:e>=11696&&e<=11702||e>=11704&&e<=11710:e<11728?e>=11712&&e<=11718||e>=11720&&e<=11726:e>=11728&&e<=11734||e>=11736&&e<=11742:e<12330?e<11823?e>=11744&&e<=11775:11823==e||e>=12293&&e<=12294:e<12353?e>=12330&&e<=12341||e>=12347&&e<=12349:e>=12353&&e<=12438||e>=12441&&e<=12442:e<42512?e<12951?e<12549?e<12449?e>=12445&&e<=12447:e>=12449&&e<=12538||e>=12540&&e<=12543:e<12704?e>=12549&&e<=12589||e>=12593&&e<=12686:e>=12704&&e<=12730||e>=12784&&e<=12799:e<19968?e<12953?12951==e:12953==e||e>=13312&&e<=19893:e<42192?e>=19968&&e<=40917||e>=40960&&e<=42124:e>=42192&&e<=42237||e>=42240&&e<=42508:e<42891?e<42623?e<42560?e>=42512&&e<=42539:e>=42560&&e<=42610||e>=42612&&e<=42621:e<42775?e>=42623&&e<=42725||e>=42736&&e<=42737:e>=42775&&e<=42783||e>=42786&&e<=42888:e<43072?e<42928?e>=42891&&e<=42926:e>=42928&&e<=42935||e>=42999&&e<=43047:e<43216?e>=43072&&e<=43123||e>=43136&&e<=43205:e>=43216&&e<=43225||e>=43232&&e<=43255:e<55243?e<43744?e<43488?e<43312?e<43261?43259==e:43261==e||e>=43264&&e<=43309:e<43392?e>=43312&&e<=43347||e>=43360&&e<=43388:e>=43392&&e<=43456||e>=43471&&e<=43481:e<43600?e<43520?e>=43488&&e<=43518:e>=43520&&e<=43574||e>=43584&&e<=43597:e<43642?e>=43600&&e<=43609||e>=43616&&e<=43638:e>=43642&&e<=43714||e>=43739&&e<=43741:e<43824?e<43785?e<43762?e>=43744&&e<=43759:e>=43762&&e<=43766||e>=43777&&e<=43782:e<43808?e>=43785&&e<=43790||e>=43793&&e<=43798:e>=43808&&e<=43814||e>=43816&&e<=43822:e<44012?e<43868?e>=43824&&e<=43866:e>=43868&&e<=43877||e>=43888&&e<=44010:e<44032?e>=44012&&e<=44013||e>=44016&&e<=44025:e>=44032&&e<=55203||e>=55216&&e<=55238:e<64848?e<64298?e<64112?e<55296?e>=55243&&e<=55291:e>=55296&&e<=57343||e>=63744&&e<=64109:e<64275?e>=64112&&e<=64217||e>=64256&&e<=64262:e>=64275&&e<=64279||e>=64285&&e<=64296:e<64320?e<64312?e>=64298&&e<=64310:e>=64312&&e<=64316||64318==e:e<64326?e>=64320&&e<=64321||e>=64323&&e<=64324:e>=64326&&e<=64433||e>=64467&&e<=64829:e<65296?e<65024?e<64914?e>=64848&&e<=64911:e>=64914&&e<=64967||e>=65008&&e<=65019:e<65136?e>=65024&&e<=65039||e>=65056&&e<=65071:e>=65136&&e<=65140||e>=65142&&e<=65276:e<65474?e<65345?e>=65296&&e<=65305||e>=65313&&e<=65338:e>=65345&&e<=65370||e>=65382&&e<=65470:e<65490?e>=65474&&e<=65479||e>=65482&&e<=65487:e>=65490&&e<=65495||e>=65498&&e<=65500}function Nt(e){return e<58?e<44?33==e:44==e||46==e:e<63?e>=58&&e<=59:63==e||94==e}function Dt(e){return e<91?40==e:91==e||123==e}function Rt(e){return e<93?41==e:93==e||125==e}var Ot=/^(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|travelersinsurance|vermögensberatung|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbah1a3hjkrd|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--mgbcpq6gpa1a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbc0a9azcg|xn--nqv7fs00ema|americanfamily|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq480n2rg|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|wolterskluwer|xn--cckwcxetd|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|xn--4dbrk0ce|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbgu82a|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--3bst00m|xn--3ds443g|xn--3hcrj9c|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|சிங்கப்பூர்|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nextdirect|properties|protection|prudential|realestate|republican|restaurant|schaeffler|tatamotors|technology|university|vlaanderen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--q7ce6a|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|institute|insurance|kuokgroup|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|pramerica|richardli|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--ngbrx|xn--nqv7f|xn--p1acf|xn--qxa6a|xn--tckwe|xn--vhquv|yodobashi|موريتانيا|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|builders|business|capetown|catering|catholic|cipriani|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|mckinsey|memorial|merckmsd|mortgage|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|softbank|software|stcgroup|supplies|training|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|banamex|bauhaus|bestbuy|booking|brother|capital|caravan|careers|channel|charity|chintai|citadel|clubmed|college|cologne|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|grocery|guitars|hamburg|hangout|hitachi|holiday|hosting|hotmail|hyundai|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lanxess|lasalle|latrobe|leclerc|limited|lincoln|markets|monster|netbank|netflix|network|neustar|okinawa|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|singles|staples|storage|support|surgery|systems|temasek|theater|theatre|tickets|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|yamaxun|youtube|zuerich|католик|البحرين|الجزائر|العليان|پاکستان|كاثوليك|இந்தியா|abbott|abbvie|africa|agency|airbus|airtel|alipay|alsace|alstom|amazon|anquan|aramco|author|bayern|beauty|berlin|bharti|bostik|boston|broker|camera|career|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hotels|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kindle|kosher|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|monash|mormon|moscow|museum|nagoya|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|pictet|quebec|racing|realty|reisen|repair|report|review|rogers|ryukyu|safety|sakura|sanofi|school|schule|search|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|walter|webcam|xihuan|yachts|yandex|zappos|москва|онлайн|ابوظبي|ارامكو|الاردن|المغرب|امارات|فلسطين|مليسيا|भारतम्|இலங்கை|ファッション|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|bosch|build|canon|cards|chase|cheap|cisco|citic|click|cloud|coach|codes|crown|cymru|dance|deals|delta|drive|dubai|earth|edeka|email|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|irish|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|loans|locus|lotte|lotto|mango|media|miami|money|movie|music|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|rugby|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|sport|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|ישראל|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|aero|akdn|ally|amex|arab|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|dvag|erni|fage|fail|fans|farm|fast|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kids|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|read|reit|rent|rest|rich|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scot|seat|seek|sexy|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|дети|сайт|بارت|بيتك|ڀارت|تونس|شبكة|عراق|عمان|موقع|भारत|ভারত|ভাৰত|ਭਾਰਤ|ભારત|ଭାରତ|ಭಾರತ|ලංකා|アマゾン|グーグル|クラウド|ポイント|组织机构|電訊盈科|香格里拉|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|ceo|cfa|cfd|com|cpa|crs|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gay|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|ibm|ice|icu|ifm|inc|ing|ink|int|ist|itv|jcb|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|llp|lol|lpl|ltd|man|map|mba|med|men|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|scb|sew|sex|sfr|ski|sky|soy|spa|srl|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|бел|ком|қаз|мкд|мон|орг|рус|срб|укр|հայ|קום|عرب|قطر|كوم|مصر|कॉम|नेट|คอม|ไทย|ລາວ|ストア|セール|みんな|中文网|亚马逊|天主教|我爱你|新加坡|淡马锡|飞利浦|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|ευ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|广东|微博|慈善|手机|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)$/,Pt=/https?:\/\//i,jt=new RegExp("^"+Pt.source,"i"),$t=/^(javascript|vbscript):/i,Ut=/^[A-Za-z][-.+A-Za-z0-9]*:(\/\/)?([^:/]*)/,Wt=/^(?:\/\/)?([^/#?:]+)/,qt=xt;function Lt(e){return xt(e)||Et(e)||43===e||45===e||46===e}var Bt=At;function Gt(e){return 95===e||Bt(e)}function Ft(e){return At(e)||((t=e)<91?t<47?t>=35&&t<=43||45==t:t<61?47==t:61==t||64==t:t<95?91==t||93==t:t<123?95==t:t>=123&&t<=126||10003==t)||Nt(e);var t}function Ht(e){return 47===e||63===e||35===e}function zt(e){return Ot.test(e.toLowerCase())}var Jt=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,Yt=/[:/?#]/,Qt=/^(https?:\/\/)?(?:www\.)?/i,Vt=/^\/\//,Kt=function(e){function t(t){var n=e.call(this,t)||this;return n.type="url",n.url="",n.urlMatchType="scheme",n.protocolRelativeMatch=!1,n.stripPrefix={scheme:!0,www:!0},n.stripTrailingSlash=!0,n.decodePercentEncoding=!0,n.protocolPrepended=!1,n.urlMatchType=t.urlMatchType,n.url=t.url,n.protocolRelativeMatch=t.protocolRelativeMatch,n.stripPrefix=t.stripPrefix,n.stripTrailingSlash=t.stripTrailingSlash,n.decodePercentEncoding=t.decodePercentEncoding,n}return ft(t,e),t.prototype.getType=function(){return"url"},t.prototype.getUrlMatchType=function(){return this.urlMatchType},t.prototype.getUrl=function(){var e=this.url;return this.protocolRelativeMatch||"scheme"===this.urlMatchType||this.protocolPrepended||(e=this.url="http://"+e,this.protocolPrepended=!0),e},t.prototype.getAnchorHref=function(){return this.getUrl().replace(/&/g,"&")},t.prototype.getAnchorText=function(){var e,t=this.getMatchedText();return this.protocolRelativeMatch&&(t=t.replace(Vt,"")),this.stripPrefix.scheme&&(t=t.replace(jt,"")),this.stripPrefix.www&&(t=(e=t).includes("www.")?e.replace(Qt,"$1"):e),this.stripTrailingSlash&&(t=function(e){return"/"===e.charAt(e.length-1)&&(e=e.slice(0,-1)),e}(t)),this.decodePercentEncoding&&(t=function(e){var t=e.replace(/%(?:22|26|27|3C|3E)/gi,function(e){return"%22"===e?""":"%26"===e?"&":"%27"===e?"'":"%3C"===e||"%3c"===e?"<":">"});if(t.includes("%"))try{return decodeURIComponent(t)}catch(n){}return t}(t)),t},t}(It),Zt=/^mailto:/i,Xt=At;function en(e){return Xt(e)||((t=e)<47?t<42?33==t||t>=35&&t<=39:t>=42&&t<=43||45==t:t<63?47==t||61==t:t<94?63==t:t>=94&&t<=96||t>=123&&t<=126);var t}var tn=function(e){function t(t){var n=e.call(this,t)||this;return n.type="email",n.email="",n.email=t.email,n}return ft(t,e),t.prototype.getType=function(){return"email"},t.prototype.getEmail=function(){return this.email},t.prototype.getAnchorHref=function(){return"mailto:"+this.email},t.prototype.getAnchorText=function(){return this.email},t}(It);function nn(e){return 95===e||At(e)}var sn=["twitter","facebook","instagram","tiktok","youtube"],rn=function(e){function t(t){var n=e.call(this,t)||this;return n.type="hashtag",n.serviceName="twitter",n.hashtag="",n.serviceName=t.serviceName,n.hashtag=t.hashtag,n}return ft(t,e),t.prototype.getType=function(){return"hashtag"},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getHashtag=function(){return this.hashtag},t.prototype.getAnchorHref=function(){var e=this.serviceName,t=this.hashtag;switch(e){case"twitter":return"https://twitter.com/hashtag/"+t;case"facebook":return"https://www.facebook.com/hashtag/"+t;case"instagram":return"https://instagram.com/explore/tags/"+t;case"tiktok":return"https://www.tiktok.com/tag/"+t;case"youtube":return"https://youtube.com/hashtag/"+t;default:yt(e)}},t.prototype.getAnchorText=function(){return"#"+this.hashtag},t.prototype.getCssClassSuffixes=function(){var t=e.prototype.getCssClassSuffixes.call(this),n=this.getServiceName();return n&&t.push(n),t},t}(It),an={twitter:/^@\w{1,15}$/,instagram:/^@[_\w]{1,30}$/,soundcloud:/^@[-a-z0-9_]{3,25}$/,tiktok:/^@[.\w]{1,23}[\w]$/,youtube:/^@[-.·\w]{3,30}$/};function on(e){return 45===e||46===e||95===e||xt(e)||Et(e)}var ln=["twitter","instagram","soundcloud","tiktok","youtube"],cn=function(e){function t(t){var n=e.call(this,t)||this;return n.type="mention",n.serviceName="twitter",n.mention="",n.mention=t.mention,n.serviceName=t.serviceName,n}return ft(t,e),t.prototype.getType=function(){return"mention"},t.prototype.getMention=function(){return this.mention},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getAnchorHref=function(){switch(this.serviceName){case"twitter":return"https://twitter.com/"+this.mention;case"instagram":return"https://instagram.com/"+this.mention;case"soundcloud":return"https://soundcloud.com/"+this.mention;case"tiktok":return"https://www.tiktok.com/@"+this.mention;case"youtube":return"https://youtube.com/@"+this.mention;default:yt(this.serviceName)}},t.prototype.getAnchorText=function(){return"@"+this.mention},t.prototype.getCssClassSuffixes=function(){var t=e.prototype.getCssClassSuffixes.call(this),n=this.getServiceName();return n&&t.push(n),t},t}(It),un=/[-. ()]/,hn=new RegExp("^".concat(/(?:(?:(?:(\+)?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-. ]?(?:\d[-. ]?){6,12}\d+))([,;]+[0-9]+#?)*/.source,"|").concat(/(0([1-9]-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/.source,"$"));function dn(e){return 45===e||46===e||32===e}function pn(e){return 44===e||59===e}var fn=function(e){function t(t){var n=e.call(this,t)||this;return n.type="phone",n.number="",n.plusSign=!1,n.number=t.number,n.plusSign=t.plusSign,n}return ft(t,e),t.prototype.getType=function(){return"phone"},t.prototype.getPhoneNumber=function(){return this.number},t.prototype.getNumber=function(){return this.getPhoneNumber()},t.prototype.getAnchorHref=function(){return"tel:"+(this.plusSign?"+":"")+this.number},t.prototype.getAnchorText=function(){return this.matchedText},t}(It),mn=function(){function e(e,t){this.charIdx=0,this.matches=[],this._stateMachines=[],this.schemeUrlMachinesCount=0,this.text=e,this.tagBuilder=t.tagBuilder,this.stripPrefix=t.stripPrefix,this.stripTrailingSlash=t.stripTrailingSlash,this.decodePercentEncoding=t.decodePercentEncoding,this.hashtagServiceName=t.hashtagServiceName,this.mentionServiceName=t.mentionServiceName}return Object.defineProperty(e.prototype,"stateMachines",{get:function(){return this._stateMachines},enumerable:!1,configurable:!0}),e.prototype.addMachine=function(e){this._stateMachines.push(e),hs(e)&&this.schemeUrlMachinesCount++},e.prototype.removeMachine=function(e){this._stateMachines=this._stateMachines.filter(function(t){return t!==e}),hs(e)&&this.schemeUrlMachinesCount--},e.prototype.hasSchemeUrlMachine=function(){return this.schemeUrlMachinesCount>0},e}();function gn(e,t,n){var s=e.charIdx;if(35===n)e.addMachine({type:2,startIdx:s,state:28,acceptStateReached:!1});else if(64===n)e.addMachine(function(e){return{type:3,startIdx:e,state:30,acceptStateReached:!1}}(s));else if(47===n)e.addMachine(cs(s,11));else if(43===n)e.addMachine(us(s,37));else if(40===n)e.addMachine(us(s,32));else{if(Et(n)&&(e.addMachine(us(s,38)),e.addMachine(function(e){return{type:0,startIdx:e,state:13,acceptStateReached:!1,matchType:2,octetsEncountered:1}}(s))),Xt(n)){var r="m"===t.toLowerCase()?15:22;e.addMachine(function(e,t){return{type:1,startIdx:e,state:t,acceptStateReached:!1}}(s,r))}qt(n)&&e.addMachine(ls(s,0)),At(n)&&e.addMachine(cs(s,5))}}function vn(e,t,n){58===n?t.state=2:45===n?t.state=1:Lt(n)||e.removeMachine(t)}function bn(e,t,n){var s=e.charIdx;45===n||(47===n?(e.removeMachine(t),e.addMachine(cs(s,11))):Lt(n)?t.state=0:e.removeMachine(t))}function yn(e,t,n){var s=e.charIdx;47===n?t.state=3:46===n?e.removeMachine(t):Bt(n)?(t.state=5,qt(n)&&e.addMachine(ls(s,0))):e.removeMachine(t)}function wn(e,t,n){47===n?t.state=4:Ft(n)?(t.state=10,t.acceptStateReached=!0):is(e,t)}function kn(e,t,n,s){47===s?(t.state=10,t.acceptStateReached=!0):Bt(s)?(t.state=5,t.acceptStateReached=!0):e.removeMachine(t)}function Sn(e,t,n){47===n?t.state=12:e.removeMachine(t)}function Cn(e,t,n){Bt(n)?t.state=5:e.removeMachine(t)}function Tn(e,t,n){46===n?t.state=7:45===n?t.state=6:58===n?t.state=8:Ht(n)?t.state=10:Gt(n)||is(e,t)}function In(e,t,n,s){45===s||(46===s?is(e,t):Bt(s)?t.state=5:is(e,t))}function xn(e,t,n,s){46===s?is(e,t):Bt(s)?(t.state=5,t.acceptStateReached=!0):is(e,t)}function En(e,t,n){46===n?t.state=14:58===n?t.state=8:Et(n)||(Ht(n)?t.state=10:At(n)?e.removeMachine(t):is(e,t))}function Mn(e,t,n){Et(n)?(t.octetsEncountered++,4===t.octetsEncountered&&(t.acceptStateReached=!0),t.state=13):is(e,t)}function _n(e,t,n){Et(n)?t.state=9:is(e,t)}function An(e,t,n){Et(n)||(Ht(n)?t.state=10:is(e,t))}function Nn(e,t,n){Ft(n)||is(e,t)}function Dn(e,t,n,s){"a"===n.toLowerCase()?t.state=16:Wn(e,t,s)}function Rn(e,t,n,s){"i"===n.toLowerCase()?t.state=17:Wn(e,t,s)}function On(e,t,n,s){"l"===n.toLowerCase()?t.state=18:Wn(e,t,s)}function Pn(e,t,n,s){"t"===n.toLowerCase()?t.state=19:Wn(e,t,s)}function jn(e,t,n,s){"o"===n.toLowerCase()?t.state=20:Wn(e,t,s)}function $n(e,t,n){58===n?t.state=21:Wn(e,t,n)}function Un(e,t,n){en(n)?t.state=22:e.removeMachine(t)}function Wn(e,t,n){46===n?t.state=23:64===n?t.state=24:en(n)?t.state=22:e.removeMachine(t)}function qn(e,t,n){46===n||64===n?e.removeMachine(t):en(n)?t.state=22:e.removeMachine(t)}function Ln(e,t,n){Bt(n)?t.state=25:e.removeMachine(t)}function Bn(e,t,n){46===n?t.state=27:45===n?t.state=26:Gt(n)||is(e,t)}function Gn(e,t,n){45===n||46===n?is(e,t):Gt(n)?t.state=25:is(e,t)}function Fn(e,t,n){46===n||45===n?is(e,t):Bt(n)?(t.state=25,t.acceptStateReached=!0):is(e,t)}function Hn(e,t,n){nn(n)?(t.state=29,t.acceptStateReached=!0):e.removeMachine(t)}function zn(e,t,n){nn(n)||is(e,t)}function Jn(e,t,n){on(n)?(t.state=31,t.acceptStateReached=!0):e.removeMachine(t)}function Yn(e,t,n){on(n)||(At(n)?e.removeMachine(t):is(e,t))}function Qn(e,t,n,s){Et(s)?t.state=38:(e.removeMachine(t),gn(e,n,s))}function Vn(e,t,n,s){Et(s)?t.state=33:e.removeMachine(t),gn(e,n,s)}function Kn(e,t,n){Et(n)?t.state=34:e.removeMachine(t)}function Zn(e,t,n){Et(n)?t.state=35:e.removeMachine(t)}function Xn(e,t,n){41===n?t.state=36:e.removeMachine(t)}function es(e,t,n,s){Et(s)?t.state=38:dn(s)?t.state=39:e.removeMachine(t)}function ts(e,t,n,s){var r=e.charIdx;t.acceptStateReached=!0,pn(s)?t.state=40:35===s?t.state=41:Et(s)||(40===s?t.state=32:dn(s)?t.state=39:(is(e,t),qt(s)&&e.addMachine(ls(r,0))))}function ns(e,t,n,s){Et(s)?t.state=38:40===s?t.state=32:(is(e,t),gn(e,n,s))}function ss(e,t,n){pn(n)||(35===n?t.state=41:Et(n)?t.state=38:is(e,t))}function rs(e,t,n){pn(n)?t.state=40:Et(n)?e.removeMachine(t):is(e,t)}function is(e,t){var n,s=e.matches,r=e.text,i=e.charIdx,a=e.tagBuilder,o=e.stripPrefix,l=e.stripTrailingSlash,c=e.decodePercentEncoding,u=e.hashtagServiceName,h=e.mentionServiceName;if(e.removeMachine(t),t.acceptStateReached){var d,p,f=t.startIdx,m=r.slice(t.startIdx,i);switch(m=function(e){for(var t={"(":0,"{":0,"[":0},n=0;n<e.length;n++){var s=e.charAt(n);Dt(i=e.charCodeAt(n))?t[s]++:Rt(i)&&t[os[s]]--}for(var r=e.length-1;r>=0;){var i;if(s=e.charAt(r),Rt(i=e.charCodeAt(r))){var a=os[s];if(!(t[a]<0))break;t[a]++,r--}else{if(!Nt(i))break;r--}}return e.slice(0,r+1)}(m),t.type){case 0:if(64===r.charCodeAt(t.startIdx-1))return;switch(t.matchType){case 0:var g=Pt.exec(m);if(g&&(f+=g.index,m=m.slice(g.index)),!function(e){if($t.test(e))return!1;var t=e.match(Ut);if(!t)return!1;var n=!!t[1],s=t[2];return!!n||!(-1===s.indexOf(".")||!/[A-Za-z]/.test(s))}(m))return;break;case 1:if(!function(e){var t=e.match(Wt);if(!t)return!1;var n=t[0].split(".");return!(n.length<2||!zt(n[n.length-1]))}(m))return;break;case 2:if(p=m.split(Yt,1)[0],!Jt.test(p))return;break;default:yt(t)}s.push(new Kt({tagBuilder:a,matchedText:m,offset:f,urlMatchType:as(t.matchType),url:m,protocolRelativeMatch:"//"===m.slice(0,2),stripPrefix:o,stripTrailingSlash:l,decodePercentEncoding:c}));break;case 1:zt(m.split(".").pop())&&s.push(new tn({tagBuilder:a,matchedText:m,offset:f,email:m.replace(Zt,"")}));break;case 2:m.length<=140&&s.push(new rn({tagBuilder:a,matchedText:m,offset:f,serviceName:u,hashtag:m.slice(1)}));break;case 3:n=m,an[h].test(n)&&s.push(new cn({tagBuilder:a,matchedText:m,offset:f,serviceName:h,mention:m.slice(1)}));break;case 4:if(("+"===(d=m=m.replace(/ +$/g,"")).charAt(0)||un.test(d))&&hn.test(d)){var v=m.replace(/[^0-9,;#]/g,"");s.push(new fn({tagBuilder:a,matchedText:m,offset:f,number:v,plusSign:"+"===m.charAt(0)}))}break;default:yt(t)}}}function as(e){switch(e){case 0:return"scheme";case 1:return"tld";case 2:return"ipV4";default:yt(e)}}var os={")":"(","}":"{","]":"["};function ls(e,t){return{type:0,startIdx:e,state:t,acceptStateReached:!1,matchType:0}}function cs(e,t){return{type:0,startIdx:e,state:t,acceptStateReached:!1,matchType:1}}function us(e,t){return{type:4,startIdx:e,state:t,acceptStateReached:!1}}function hs(e){return 0===e.type&&0===e.matchType}var ds=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.type=e.type||"tag",this.name=e.name||"",this.isOpening=!!e.isOpening,this.isClosing=!!e.isClosing},ps=new ds,fs=function(e,t){this.charIdx=0,this.state=0,this.currentDataIdx=0,this.currentTag=ps,this.html=e,this.callbacks=t};function ms(e,t){"<"===t&&$s(e)}function gs(e,t,n){"!"===t?e.state=13:"/"===t?(e.state=2,e.currentTag=new ds(mt(mt({},e.currentTag),{isClosing:!0}))):"<"===t?$s(e):xt(n)?(e.state=3,e.currentTag=new ds(mt(mt({},e.currentTag),{isOpening:!0}))):(e.state=0,e.currentTag=ps)}function vs(e,t,n){_t(n)?(e.currentTag=new ds(mt(mt({},e.currentTag),{name:Ws(e)})),e.state=4):"<"===t?$s(e):"/"===t?(e.currentTag=new ds(mt(mt({},e.currentTag),{name:Ws(e)})),e.state=12):">"===t?(e.currentTag=new ds(mt(mt({},e.currentTag),{name:Ws(e)})),Us(e)):xt(n)||Et(n)||":"===t||js(e)}function bs(e,t,n){">"===t?js(e):xt(n)?e.state=3:js(e)}function ys(e,t,n){var s;_t(n)||("/"===t?e.state=12:">"===t?Us(e):"<"===t?$s(e):"="===t||Mt(n)||(s=n)>=0&&s<=31||127==s?js(e):e.state=5)}function ws(e,t,n){_t(n)?e.state=6:"/"===t?e.state=12:"="===t?e.state=7:">"===t?Us(e):"<"===t?$s(e):Mt(n)&&js(e)}function ks(e,t,n){_t(n)||("/"===t?e.state=12:"="===t?e.state=7:">"===t?Us(e):"<"===t?$s(e):Mt(n)?js(e):e.state=5)}function Ss(e,t,n){_t(n)||('"'===t?e.state=8:"'"===t?e.state=9:/[>=`]/.test(t)?js(e):"<"===t?$s(e):e.state=10)}function Cs(e,t){'"'===t&&(e.state=11)}function Ts(e,t){"'"===t&&(e.state=11)}function Is(e,t,n){_t(n)?e.state=4:">"===t?Us(e):"<"===t&&$s(e)}function xs(e,t,n){_t(n)?e.state=4:"/"===t?e.state=12:">"===t?Us(e):"<"===t?$s(e):(e.state=4,e.charIdx--)}function Es(e,t){">"===t?(e.currentTag=new ds(mt(mt({},e.currentTag),{isClosing:!0})),Us(e)):js(e)}function Ms(e){var t=e.html,n=e.charIdx;"--"===t.slice(n,n+2)?(e.charIdx++,e.currentTag=new ds(mt(mt({},e.currentTag),{type:"comment"})),e.state=14):"DOCTYPE"===t.slice(n,n+7).toUpperCase()?(e.charIdx+=6,e.currentTag=new ds(mt(mt({},e.currentTag),{type:"doctype"})),e.state=20):js(e)}function _s(e,t){"-"===t?e.state=15:">"===t?js(e):e.state=16}function As(e,t){"-"===t?e.state=18:">"===t?js(e):e.state=16}function Ns(e,t){"-"===t&&(e.state=17)}function Ds(e,t){e.state="-"===t?18:16}function Rs(e,t){">"===t?Us(e):"!"===t?e.state=19:"-"===t||(e.state=16)}function Os(e,t){"-"===t?e.state=17:">"===t?Us(e):e.state=16}function Ps(e,t){">"===t?Us(e):"<"===t&&$s(e)}function js(e){e.state=0,e.currentTag=ps}function $s(e){e.state=1,e.currentTag=new ds({idx:e.charIdx})}function Us(e){var t=e.html.slice(e.currentDataIdx,e.currentTag.idx);t&&e.callbacks.onText(t,e.currentDataIdx);var n=e.currentTag;"comment"===n.type?e.callbacks.onComment(n.idx):"doctype"===n.type?e.callbacks.onDoctype(n.idx):(n.isOpening&&e.callbacks.onOpenTag(n.name,n.idx),n.isClosing&&e.callbacks.onCloseTag(n.name,n.idx)),js(e),e.currentDataIdx=e.charIdx+1}function Ws(e){var t=e.currentTag.idx+(e.currentTag.isClosing?2:1);return e.html.slice(t,e.charIdx).toLowerCase()}var qs=function(){function e(t){var n;void 0===t&&(t={}),this.version=e.version,this.urls={},this.email=!0,this.phone=!0,this.hashtag=!1,this.mention=!1,this.newWindow=!0,this.stripPrefix={scheme:!0,www:!0},this.stripTrailingSlash=!0,this.decodePercentEncoding=!0,this.truncate={length:0,location:"end"},this.className="",this.replaceFn=null,this.context=void 0,this.sanitizeHtml=!1,this.tagBuilder=null,this.urls=(null==(n=t.urls)&&(n=!0),vt(n)?{schemeMatches:n,tldMatches:n,ipV4Matches:n}:{schemeMatches:!vt(n.schemeMatches)||n.schemeMatches,tldMatches:!vt(n.tldMatches)||n.tldMatches,ipV4Matches:!vt(n.ipV4Matches)||n.ipV4Matches}),this.email=vt(t.email)?t.email:this.email,this.phone=vt(t.phone)?t.phone:this.phone,this.hashtag=t.hashtag||this.hashtag,this.mention=t.mention||this.mention,this.newWindow=vt(t.newWindow)?t.newWindow:this.newWindow,this.stripPrefix=function(e){return null==e&&(e=!0),vt(e)?{scheme:e,www:e}:{scheme:!vt(e.scheme)||e.scheme,www:!vt(e.www)||e.www}}(t.stripPrefix),this.stripTrailingSlash=vt(t.stripTrailingSlash)?t.stripTrailingSlash:this.stripTrailingSlash,this.decodePercentEncoding=vt(t.decodePercentEncoding)?t.decodePercentEncoding:this.decodePercentEncoding,this.sanitizeHtml=t.sanitizeHtml||!1;var s=this.mention;if(!1!==s&&-1===ln.indexOf(s))throw new Error("invalid `mention` cfg '".concat(s,"' - see docs"));var r,i=this.hashtag;if(!1!==i&&-1===sn.indexOf(i))throw new Error("invalid `hashtag` cfg '".concat(i,"' - see docs"));this.truncate="number"==typeof(r=t.truncate)?{length:r,location:"end"}:mt({length:Number.POSITIVE_INFINITY,location:"end"},r),this.className=t.className||this.className,this.replaceFn=t.replaceFn||this.replaceFn,this.context=t.context||this}return e.link=function(t,n){return new e(n).link(t)},e.parse=function(t,n){return new e(n).parse(t)},e.prototype.parse=function(e){var t=this,n=["a","style","script"],s=0,r=[];return function(e,t){for(var n=new fs(e,t),s=e.length;n.charIdx<s;){var r=e.charAt(n.charIdx),i=e.charCodeAt(n.charIdx);switch(n.state){case 0:ms(n,r);break;case 1:gs(n,r,i);break;case 2:bs(n,r,i);break;case 3:vs(n,r,i);break;case 4:ys(n,r,i);break;case 5:ws(n,r,i);break;case 6:ks(n,r,i);break;case 7:Ss(n,r,i);break;case 8:Cs(n,r);break;case 9:Ts(n,r);break;case 10:Is(n,r,i);break;case 11:xs(n,r,i);break;case 12:Es(n,r);break;case 13:Ms(n);break;case 14:_s(n,r);break;case 15:As(n,r);break;case 16:Ns(n,r);break;case 17:Ds(n,r);break;case 18:Rs(n,r);break;case 19:Os(n,r);break;case 20:Ps(n,r);break;default:yt(n.state)}n.charIdx++}var a,o;n.currentDataIdx<n.charIdx&&(o=(a=n).html.slice(a.currentDataIdx,a.charIdx),a.callbacks.onText(o,a.currentDataIdx),a.currentDataIdx=a.charIdx+1)}(e,{onOpenTag:function(e){n.indexOf(e)>=0&&s++},onText:function(e,n){if(0===s){var i=e.split(/( | |<|<|>|>|"|"|')/gi),a=n;i.forEach(function(e,n){if(n%2==0){var s=t.parseText(e,a);r.push.apply(r,function(e,t,n){if(n||2===arguments.length)for(var s,r=0,i=t.length;r<i;r++)!s&&r in t||(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}([],function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var s,r,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(s=i.next()).done;)a.push(s.value)}catch(o){r={error:o}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return a}(s),!1))}a+=e.length})}},onCloseTag:function(e){n.indexOf(e)>=0&&(s=Math.max(s-1,0))},onComment:function(){},onDoctype:function(){}}),r=this.compactMatches(r),r=this.removeUnwantedMatches(r)},e.prototype.compactMatches=function(e){e.sort(Ls);for(var t=0;t<e.length-1;){var n=e[t],s=n.getOffset(),r=n.getMatchedText().length;if(t+1<e.length&&e[t+1].getOffset()===s){var i=e[t+1].getMatchedText().length>r?t:t+1;e.splice(i,1)}else t++}return e},e.prototype.removeUnwantedMatches=function(e){return this.hashtag||bt(e,function(e){return"hashtag"===e.getType()}),this.email||bt(e,function(e){return"email"===e.getType()}),this.phone||bt(e,function(e){return"phone"===e.getType()}),this.mention||bt(e,function(e){return"mention"===e.getType()}),this.urls.schemeMatches||bt(e,function(e){return"url"===e.getType()&&"scheme"===e.getUrlMatchType()}),this.urls.tldMatches||bt(e,function(e){return"url"===e.getType()&&"tld"===e.getUrlMatchType()}),this.urls.ipV4Matches||bt(e,function(e){return"url"===e.getType()&&"ipV4"===e.getUrlMatchType()}),e},e.prototype.parseText=function(e,t){t=t||0;for(var n=function(e,t){for(var n=new mn(e,t);n.charIdx<n.text.length;n.charIdx++){var s=e.charAt(n.charIdx),r=e.charCodeAt(n.charIdx);if(0===n.stateMachines.length)gn(n,s,r);else{for(var i=n.stateMachines.length-1;i>=0;i--){var a=n.stateMachines[i];switch(a.state){case 11:Sn(n,a,r);break;case 12:Cn(n,a,r);break;case 0:vn(n,a,r);break;case 1:bn(n,a,r);break;case 2:yn(n,a,r);break;case 3:wn(n,a,r);break;case 4:kn(n,a,0,r);break;case 5:Tn(n,a,r);break;case 6:In(n,a,0,r);break;case 7:xn(n,a,0,r);break;case 13:En(n,a,r);break;case 14:Mn(n,a,r);break;case 8:_n(n,a,r);break;case 9:An(n,a,r);break;case 10:Nn(n,a,r);break;case 15:Dn(n,a,s,r);break;case 16:Rn(n,a,s,r);break;case 17:On(n,a,s,r);break;case 18:Pn(n,a,s,r);break;case 19:jn(n,a,s,r);break;case 20:$n(n,a,r);break;case 21:Un(n,a,r);break;case 22:Wn(n,a,r);break;case 23:qn(n,a,r);break;case 24:Ln(n,a,r);break;case 25:Bn(n,a,r);break;case 26:Gn(n,a,r);break;case 27:Fn(n,a,r);break;case 28:Hn(n,a,r);break;case 29:zn(n,a,r);break;case 30:Jn(n,a,r);break;case 31:Yn(n,a,r);break;case 32:Vn(n,a,s,r);break;case 33:Kn(n,a,r);break;case 34:Zn(n,a,r);break;case 35:Xn(n,a,r);break;case 36:es(n,a,0,r);break;case 37:Qn(n,a,s,r);break;case 38:ts(n,a,0,r);break;case 39:ns(n,a,s,r);break;case 40:ss(n,a,r);break;case 41:rs(n,a,r);break;default:yt(a.state)}}if(!n.hasSchemeUrlMachine()&&n.charIdx>0&&qt(r)){var o=n.text.charCodeAt(n.charIdx-1);qt(o)||n.addMachine(ls(n.charIdx,0))}}}for(var l=n.stateMachines.length-1;l>=0;l--)n.stateMachines.forEach(function(e){return is(n,e)});return n.matches}(e,{tagBuilder:this.getTagBuilder(),stripPrefix:this.stripPrefix,stripTrailingSlash:this.stripTrailingSlash,decodePercentEncoding:this.decodePercentEncoding,hashtagServiceName:this.hashtag,mentionServiceName:this.mention||"twitter"}),s=0,r=n.length;s<r;s++)n[s].setOffset(t+n[s].getOffset());return n},e.prototype.link=function(e){if(!e)return"";this.sanitizeHtml&&(e=e.replace(/</g,"<").replace(/>/g,">"));for(var t=this.parse(e),n=new Array(2*t.length+1),s=0,r=0,i=t.length;r<i;r++){var a=t[r];n.push(e.substring(s,a.getOffset())),n.push(this.createMatchReturnVal(a)),s=a.getOffset()+a.getMatchedText().length}return n.push(e.substring(s)),n.join("")},e.prototype.createMatchReturnVal=function(e){var t;return this.replaceFn&&(t=this.replaceFn.call(this.context,e)),"string"==typeof t?t:!1===t?e.getMatchedText():t instanceof kt?t.toAnchorString():e.buildTag().toAnchorString()},e.prototype.getTagBuilder=function(){var e=this.tagBuilder;return e||(e=this.tagBuilder=new Tt({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),e},e.version="4.1.5",e}();function Ls(e,t){return e.getOffset()-t.getOffset()}function Bs(e,t=e){return{type:"autolink",url:e,text:t}}const Gs=rt(/<!!mention:([^>\s]*?)\|(.*?)>/gm,([e,t,n])=>function(e,t){return{type:"mention",id:e,text:t}}(decodeURIComponent(t),n)),Fs=rt(/<!!customemoji:(.*?)>/gm,([e,t])=>function(e){return{type:"customemoji",text:e}}(t)),Hs=rt(/<((?:https?|mailto):.*?)\|(.*?)>/gi,([e,t,n])=>function(e,t=[]){return{type:"link",url:e,children:t}}(t,[n])),zs=rt(/<actionlink:([^|]+)[|]([^>]*)>/gi,([e,t,n])=>{const{action:s,params:r}=Ys(t);return function(e,t,n=[]){return{type:"actionlink",action:e,params:t,children:n}}(s,r,[n])}),Js=rt(/<actionbutton:([^|]+)[|]([^>]*)>/gi,([e,t,n])=>{const{action:s,params:r}=Ys(t);return function(e,t,n=[]){return{type:"actionbutton",action:e,params:t,children:n}}(s,r,[n])});function Ys(e){const t=e.indexOf("?");return-1===t?{action:e,params:{}}:{action:e.slice(0,t),params:Object.fromEntries(new URLSearchParams(e.slice(t)))}}const Qs=rt(/(?:^|\n)(?:\s*[-*+]\s+[^\n]+(?:\n|$))+/g,([e])=>function(e=[]){return{type:"bulletlist",children:e}}([e.startsWith("\n")?e.slice(1):e])),Vs=rt(/^\s*[-*+]\s+([^\n]+)(?:\n|$)/gm,([e,t])=>({type:"bulletpoint",children:[t]})),Ks=e=>{const t=/(?:^|[^-:/\w])([(+]?[0-9](?:[-_+ ().]?[0-9]){5,11}[0-9])(?:[^-:/\w]|$)/g,n=/^(\d{4})-(\d{4})$/;let s=0;const r=[];for(const i of ve(e,t)){const t=i[0],a=i[1],o=a.match(n);if(o&&Number(o[1])<Number(o[2]))continue;const l=t.startsWith(a)?i.index:i.index+1;l-s>0&&r.push(e.substring(s,l));const c=Bs("tel:"+a.replace(/[^0-9+]/g,""),a);r.push(c),s=l+a.length}return s<e.length&&r.push(e.substring(s)),r},Zs=e=>Hs(e).flatMap(e=>"string"==typeof e?Xs(e):["<",...Xs(e.url),...Xs("|"+e.children[0]+">")]),Xs=e=>{const t=qs.parse(e,{urls:!0,email:!0,phone:!1,hashtag:!1,mention:!1}),n=[];let s=0;for(const r of t){const t=r.getOffset(),i=r.getMatchedText(),a=i.length;let o=i;r instanceof tn?o="mailto:"+r.getEmail():r instanceof Kt&&(o=r.getUrl()),t>s&&n.push(e.substring(s,t)),n.push(Bs(o,i)),s=t+a}return s<e.length&&n.push(e.substring(s)),n},er=["Codeblock","Codespan","FormattedLink","Wikitext","Autolink","Actions","Mention","Mention","BulletPoint","CustomEmoji"];const tr=function(){const e=RegExp("[^\n]+\n?|\n","g");return t=>Array.from(t.match(e)||[])}();function nr(e,t={except:[]}){let n=function(e,t){let n=[e];return n=rr(n,t.multilineSteps),n=rr(n,[tr]),n=rr(n,t.singlelineSteps),n=ir(n),n}(e,function(e={except:[]}){var t;const n={multilineSteps:[],singlelineSteps:[]},s=null!=(t=e.except)?t:er.filter(t=>!e.only.includes(t));return s.includes("BulletPoint")||n.multilineSteps.push(Qs,Vs),s.includes("Mention")||n.singlelineSteps.push(Gs),s.includes("CustomEmoji")||n.singlelineSteps.push(Fs),s.includes("Codespan")||n.multilineSteps.push(rt(/```([^]+?)```/g,([e,t])=>({type:"codespan",text:t.replace(/<!!mention:.*?\|([^>]*)>/gim,"@$1").replace(/<!!customemoji:(.*?)>/gim,"$1")}))),s.includes("FormattedLink")||n.singlelineSteps.push(Hs),s.includes("Actions")||(n.singlelineSteps.push(zs),n.singlelineSteps.push(Js)),s.includes("Wikitext")||n.singlelineSteps.push(ut),s.includes("Autolink")||n.singlelineSteps.push(Zs,Ks),n}(t));return n=ar(n,!1),n}function sr(e){return nr(e,{except:["FormattedLink","Actions"]})}function rr(e,t){return t.reduce((e,t)=>st(e,t),e)}function ir(e){const t=[];let n=-1;for(const s of e)"string"==typeof s?"string"==typeof t[n]?t[n]+=s:t[++n]=s:t[++n]="children"in s?p(d({},s),{children:ir(s.children)}):s;return t}function ar(e,t){const n=[];let s=[];for(let r=0;r<e.length;r++){const i=e[r];if("string"==typeof i)s.push(i);else if("children"in i){s.length>0&&(n.push(s.join("")),s=[]);const e=ar(i.children,t||"link"===i.type||"actionbutton"===i.type||"actionlink"===i.type);n.push(p(d({},i),{children:e}))}else"autolink"===i.type&&t?s.push(i.text):(s.length>0&&(n.push(s.join("")),s=[]),n.push(i))}return s.length>0&&(n.push(s.join("")),s=[]),n}function or(e,t,n){return e.primary<t.primary?"ASC"===n.primaryOrder?"before":"after":e.primary>t.primary?"ASC"===n.primaryOrder?"after":"before":e.secondary<t.secondary?"ASC"===n.secondaryOrder?"before":"after":e.secondary>t.secondary?"ASC"===n.secondaryOrder?"after":"before":"equal"}function lr(e,t){return t>=e.length?e:H(e.slice(0,t))}class cr{constructor(e,t,n,s,r){this._onSnapshot=t,this._pageSize=n,this._maxPageSize=s,this._sort=r,this._windowStatus=void 0,this._loadMoreDeferred=void 0,this._connectedDefer=I(),this._connectedDefer.promise.catch(()=>{}),this._underlyingSubscription=e(this.handleSnapshot.bind(this)),this._underlyingSubscription.connected.catch(e=>this._connectedDefer.reject(e))}updateWindowStatusAndGetState(e,t){var n,s;if(null===e){const n={type:"active",latestSnapshot:e,loadedAll:t};return this._windowStatus=void 0,n}if(0===e.length){const n={type:"active",latestSnapshot:e,loadedAll:t};return this._windowStatus&&(this._windowStatus.lastState=n),n}if(void 0===this._windowStatus){const n=lr(e,this._pageSize),s=n[n.length-1],r=this._sort.getSortPointer(s),i=t?0:this._pageSize-n.length,a={type:"active",latestSnapshot:n,loadedAll:t&&e===n};return this._windowStatus={endPoint:r,loadingMore:i,lastState:a},a}const r=function(e,t,n,s){if(0===e.length)return 0;var r,i;r=t,i=e.length-1;const a=t=>{const r=e[t];return"after"===or(n.getSortPointer(r),s,n)};if(a(t=Math.max(0,Math.min(r,i)))){for(let e=t-1;e>=0;e--)if(!a(e))return e+1;return 0}for(let o=t+1;o<e.length;o++)if(a(o))return o;return e.length}(e,null!=(s=null==(n=this._windowStatus.lastState.latestSnapshot)?void 0:n.length)?s:this._pageSize,this._sort,this._windowStatus.endPoint),i=Math.min(r+this._windowStatus.loadingMore,e.length),a=function(e,t,n){if(e===t)return!1;if(null===e||null===t)return!0;if(e.length!==n)return!0;for(let s=0;s<n;s++)if(e[s]!==t[s])return!0;return!1}(this._windowStatus.lastState.latestSnapshot,e,i),o=t&&i===e.length,l=this._windowStatus.lastState.loadedAll!==o;if(!a&&!l)return this._windowStatus.lastState;const c=lr(e,i),u={type:"active",latestSnapshot:c,loadedAll:o};if(0===c.length)return u;const h=c.length-r,f=u.loadedAll?0:this._windowStatus.loadingMore-h;if(f===this._windowStatus.loadingMore)return this._windowStatus=p(d({},this._windowStatus),{lastState:u}),u;const m=c[c.length-1],g="after"===or(v=this._sort.getSortPointer(m),b=this._windowStatus.endPoint,this._sort)?v:b;var v,b;return this._windowStatus={endPoint:g,loadingMore:f,lastState:u},u}handleSnapshot(e,t){var n,s;const r=null==(n=this._windowStatus)?void 0:n.lastState,i=this.updateWindowStatusAndGetState(e,t);if(this._connectedDefer.resolve(i),i!==r&&(null==(s=this._onSnapshot)||s.call(this,i.latestSnapshot,i.loadedAll)),this._loadMoreDeferred&&void 0===this._windowStatus&&(this._loadMoreDeferred.resolve(),this._loadMoreDeferred=void 0),this._loadMoreDeferred&&this._windowStatus&&this._windowStatus.loadingMore<=0&&(this._loadMoreDeferred.resolve(),this._loadMoreDeferred=void 0),this._windowStatus&&this._windowStatus.loadingMore>0){const e=this._windowStatus.loadingMore;setTimeout(()=>this._underlyingSubscription.loadMore(e))}}get state(){const e=this._underlyingSubscription.state;return"active"===e.type&&null!==e?this._windowStatus?this._windowStatus.lastState:this.updateWindowStatusAndGetState(e.latestSnapshot,e.loadedAll):e}get connected(){return this._connectedDefer.promise}get terminated(){return this._underlyingSubscription.terminated}loadMore(){return y(this,arguments,function*(e=this._pageSize){var t,n,s;if(e<=0||!Number.isInteger(e))throw new Error("Invalid count: must be a positive integer.");if(e>this._maxPageSize)throw new Error(`Invalid count: cannot load more than ${this._maxPageSize} items at once.`);if(void 0===this._windowStatus)return Promise.resolve();if("active"!==this._underlyingSubscription.state.type)return Promise.resolve();const r=this._underlyingSubscription.state.latestSnapshot;if(null===r)return Promise.resolve();const i=this._underlyingSubscription.state.loadedAll,a=this.updateWindowStatusAndGetState(r,i),o=r.length-a.latestSnapshot.length,l=i?o:Number.POSITIVE_INFINITY,c=Math.min(e,l);if(this._windowStatus.loadingMore=Math.max(this._windowStatus.loadingMore,c),o>0){const e=this._windowStatus.lastState,n=this.updateWindowStatusAndGetState(r,i);n!==e&&(null==(t=this._onSnapshot)||t.call(this,n.latestSnapshot,n.loadedAll))}if(this._windowStatus.loadingMore<=0)return null==(n=this._loadMoreDeferred)||n.resolve(),void(this._loadMoreDeferred=void 0);const u=null!=(s=this._loadMoreDeferred)?s:I();this._loadMoreDeferred=u,yield this._underlyingSubscription.loadMore(this._windowStatus.loadingMore),yield u.promise})}unsubscribe(){return this._underlyingSubscription.unsubscribe()}}class ur extends cr{constructor(e,t,n){super(n=>e.subscribe(["me","conversations",t,"messages"],n),n,30,100,{getSortPointer:e=>({primary:e.createdAt,secondary:e.id}),primaryOrder:"DESC",secondaryOrder:"ASC"})}}class hr extends cr{constructor(e,t,n){super(n=>e.subscribe(["me","conversations",t,"participants"],n),n,10,50,{getSortPointer:e=>({primary:e.joinedAt,secondary:e.user.id}),primaryOrder:"DESC",secondaryOrder:"ASC"})}}class dr extends cr{constructor(e,t){super(t=>e.subscribe(["me","conversations"],t),t,20,30,{getSortPointer:e=>{var t,n;return{primary:null!=(n=null==(t=e.lastMessage)?void 0:t.createdAt)?n:e.createdAt,secondary:e.id}},primaryOrder:"DESC",secondaryOrder:"ASC"})}}class pr{constructor(e,t){this.id=e,this._realtimeClient=t,this.uselessObjForTypeCheck={subject:null,photoUrl:null,welcomeMessages:null,custom:null,access:null,notify:null}}get brandedId(){return this.id}get brandedUserId(){return this._realtimeClient.userId}participant(e){if("string"==typeof e){if(""===e)throw new Error(`Creating ParticipantRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.participant(this.brandedId,e)}if("brandedId"in e)return this._realtimeClient.refs.participant(this.brandedId,e.id);throw new Error(`Creating ParticipantRef failed because user "${e}" is not a string or a UserRef`)}message(e){if("string"!=typeof e)throw new Error(`Creating MessageRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating MessageRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.message(this.brandedId,e)}get(){return y(this,null,function*(){const e=this.subscribe(),t=yield e.connected.catch(()=>{throw new Error("GET Conversation failed, could not fetch conversation")});yield this._realtimeClient.sync();const n=e.state;if(e.unsubscribe(),"active"===n.type)return n.latestSnapshot;if("pending"===n.type)return t.latestSnapshot;if("unsubscribed"===n.type)return t.latestSnapshot;throw"error"===n.type?n.error:"Unreachable"})}set(e){return y(this,null,function*(){const t=this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedId],data:e}),n=this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedId,"participants",this.brandedUserId],data:e}),s=yield t;var r;!s.ok&&"server"===s.where&&403===s.value.status&&"UNAUTHORIZED_TO_EDIT"===s.value.errorCode&&(void 0===(r=e).subject&&void 0===r.photoUrl&&void 0===r.welcomeMessages&&null!==r.custom&&(void 0===r.custom||!Object.values(r.custom).some(e=>void 0!==e)))||D("Set conversation "+this.id,s);const i=yield n;!i.ok&&"server"===i.where&&403===i.value.status&&"UNAUTHORIZED_TO_EDIT_PARTICIPANT"===i.value.errorCode&&function(e){return void 0===e.access&&void 0===e.notify}(e)||D("Set your participation in conversation "+this.id,i)})}createIfNotExists(){return y(this,arguments,function*(e={}){const t=this._realtimeClient.call({method:"POST",path:["conversations",this.brandedId],data:e}),n=this._realtimeClient.call({method:"POST",path:["conversations",this.brandedId,"participants",this.brandedUserId],data:e}),s=yield t;(s.ok||"server"!==s.where||409!==s.value.status)&&D("Create conversation "+this.id,yield t);const r=yield n;(r.ok||"server"!==r.where||409!==r.value.status)&&D("Join conversation "+this.id,yield n)})}markAsRead(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"POST",path:["me","conversations",this.brandedId,"read"],data:{}});D(`Mark ${this.id} as read`,e)})}markAsUnread(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"POST",path:["me","conversations",this.brandedId,"unread"],data:{}});D(`Mark ${this.id} as unread`,e)})}send(e){return y(this,null,function*(){const t={content:fr(e),referencedMessageId:mr(e),custom:"string"==typeof e?void 0:e.custom,idempotencyKey:nt((new Date).getTime())},n=yield this._realtimeClient.call({method:"POST",path:["conversations",this.brandedId,"messages"],data:t}),s=D("Send message to conversation "+this.id,n);return this._realtimeClient.refs.message(this.brandedId,s.id)})}subscribeMessages(e){return new ur(this._realtimeClient,this.brandedId,e)}subscribeParticipants(e){return new hr(this._realtimeClient,this.brandedId,e)}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId],e)}subscribeTyping(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"typing"],e)}markAsTyping(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"POST",path:["me","conversations",this.brandedId,"typing"],data:{}});D(`Set user as typing in ${this.id}`,e)})}}function fr(e){return"string"==typeof e?[{type:"text",children:sr(e)}]:"text"in e?[{type:"text",children:sr(e.text)}]:e.content}function mr(e){if("string"==typeof e)return;const t=e.referencedMessage;return void 0!==t?"string"==typeof t?t:t.id:void 0}class gr{constructor(e,t,n){this.userId=e,this.conversationId=t,this._realtimeClient=n}get brandedUserId(){return this.userId}get brandedConversationId(){return this.conversationId}get(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"GET",path:["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],data:{}}),t=yield this._realtimeClient.call({method:"GET",path:["users",this.brandedUserId],data:{includePrivateFields:!1}}),[n,s]=yield Promise.all([e,t]);return(n.ok||"server"!==n.where||404!==n.value.status)&&(s.ok||"server"!==s.where||404!==s.value.status)?Me(D(`Get participant ${this.userId} in conversation ${this.conversationId}`,n),Ee(D(`Get user ${this.userId}`,s))):null})}set(){return y(this,arguments,function*(e={}){const t=yield this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:e});D(`Set participant ${this.userId} in conversation ${this.conversationId}`,t)})}edit(){return y(this,arguments,function*(e={}){const t=yield this._realtimeClient.call({method:"PATCH",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:e});D(`Edit participant ${this.userId} in conversation ${this.conversationId}`,t)})}createIfNotExists(){return y(this,arguments,function*(e={}){const t=yield this._realtimeClient.call({method:"POST",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:e});(t.ok||"server"!==t.where||409!==t.value.status)&&D(`Add participant ${this.userId} to conversation ${this.conversationId}`,t)})}delete(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"DELETE",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:{}});(e.ok||"server"!==e.where||404!==e.value.status)&&D(`Remove participant ${this.userId} from conversation ${this.conversationId}`,e)})}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],e)}}class vr{constructor(e,t,n,s){this.emoji=e,this.messageId=t,this.conversationId=n,this._realtimeClient=s}get brandedMessageId(){return this.messageId}get brandedConversationId(){return this.conversationId}add(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.emoji,this._realtimeClient.userId],data:{}});D(`Add ${this.emoji} reaction on message ${this.messageId} in conversation ${this.conversationId}`,e)})}remove(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"DELETE",path:["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.emoji,this._realtimeClient.userId],data:{}});(e.ok||"server"!==e.where||404!==e.value.status)&&D(`Remove ${this.emoji} reaction from message ${this.messageId} in conversation ${this.conversationId}`,e)})}}class br{constructor(e,t,n){this.id=e,this.conversationId=t,this._realtimeClient=n}get brandedId(){return this.id}get brandedConversationId(){return this.conversationId}reaction(e){if("string"!=typeof e)throw new Error(`Creating ReactionRef failed because emoji "${e}" is not a string`);if(""===e)throw new Error(`Creating ReactionRef failed because emoji "${e}" is an empty string`);return this._realtimeClient.refs.reaction(this.brandedConversationId,this.brandedId,e)}get(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"GET",path:["me","conversations",this.brandedConversationId,"messages",this.brandedId],data:{}});if(!e.ok&&"server"===e.where&&404===e.value.status)return null;if(!e.ok&&"server"===e.where&&403===e.value.status&&"NOT_A_PARTICIPANT"===e.value.errorCode)return null;const t=D("Get message "+this.id,e),n=yield this._realtimeClient.hydrateMessageData(t,this.brandedConversationId);return xr("Get message "+this.id,n)})}edit(e){return y(this,null,function*(){const t={content:yr(e),custom:"string"==typeof e?void 0:e.custom},n=yield this._realtimeClient.call({method:"PATCH",path:["conversations",this.brandedConversationId,"messages",this.brandedId],data:t});D(`Edit message ${this.id} in conversation ${this.conversationId}`,n)})}delete(){return y(this,null,function*(){const e=yield this._realtimeClient.call({method:"DELETE",path:["conversations",this.brandedConversationId,"messages",this.brandedId],data:{}});(e.ok||"server"!==e.where||404!==e.value.status)&&D(`Delete message ${this.id} in conversation ${this.conversationId}`,e)})}}function yr(e){return"string"==typeof e?[{type:"text",children:nr(e)}]:"text"in e&&e.text?[{type:"text",children:nr(e.text)}]:"content"in e&&e.content?e.content:void 0}const wr="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},kr=globalThis.FinalizationRegistry,Sr=void 0!==kr?kr:class{constructor(e){}register(e,t,n){}unregister(e){}};class Cr{constructor(e){this.client=e,this.users=new Map,this.conversations=new Map,this.participants=new Map,this.messages=new Map,this.reactions=new Map,this.registry=new Sr(({map:e,key:t})=>{e.delete(t)})}user(e){var t;const n=null==(t=this.users.get(e))?void 0:t.deref();if(n)return n;const s=H(new tt(e,this.client));return this.users.set(e,new wr(s)),this.registry.register(s,{map:this.users,key:e}),s}conversation(e){var t;const n=null==(t=this.conversations.get(e))?void 0:t.deref();if(n)return n;const s=H(new pr(e,this.client));return this.conversations.set(e,new wr(s)),this.registry.register(s,{map:this.conversations,key:e}),s}participant(e,t){var n;const s=`[${e}][${t}]`,r=null==(n=this.participants.get(s))?void 0:n.deref();if(r)return r;const i=H(new gr(t,e,this.client));return this.participants.set(s,new wr(i)),this.registry.register(i,{map:this.participants,key:s}),i}message(e,t){var n;const s=`[${e}][${t}]`,r=null==(n=this.messages.get(s))?void 0:n.deref();if(r)return r;const i=H(new br(t,e,this.client));return this.messages.set(s,new wr(i)),this.registry.register(i,{map:this.messages,key:s}),i}reaction(e,t,n){var s;const r=`[${e}][${t}][${n}]`,i=null==(s=this.reactions.get(r))?void 0:s.deref();if(i)return i;const a=H(new vr(n,t,e,this.client));return this.reactions.set(r,new wr(a)),this.registry.register(a,{map:this.reactions,key:r}),a}}class Tr{constructor(e,t,n){this.userId=t,this.refs=new Cr(this),this.alive=!0,this.connection=new Xe(e,n,this),n.onTokenRefreshFailed(()=>{this.destroy()})}call(e){return y(this,null,function*(){return this.alive?this.connection.call(e):M("SESSION_DESTROYED")})}subscribe(e,t){return this.connection.subscribe(e,t)}internalSubscribe(e){const t=this.connection.getOrCreateStore(e);return{store:t,unsubscribe:t.registerInternalSubscription()}}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}sync(){return y(this,null,function*(){yield this.connection.sync()})}hydrateMessageData(e,t){return y(this,null,function*(){const n=null===e.senderId?Promise.resolve(E(null)):this.getUser(e.senderId),s=null===e.referencedMessageId?Promise.resolve(E(null)):this.getReferencedMessage(t,e.referencedMessageId),r=yield n;if(!r.ok)return r;const i=yield s;if(!i.ok)return i;var a,o,l;return E((a=e,o=r.value,l=i.value,H({id:a.id,type:a.type,sender:o,referencedMessage:l,custom:H(a.custom),createdAt:a.createdAt,editedAt:a.editedAt,origin:a.origin,content:a.content,reactions:_e(a.reactions),plaintext:Ie(a.content,{})})))})}hydrateConvData(e,t){return y(this,null,function*(){const n=this.listMessages(e.id,{limit:1},t),s=yield this.call({method:"GET",path:["me","conversations",e.id],data:{},headers:t});if(!s.ok&&"server"===s.where&&404===s.value.status)return E(null);const r=D("Get conversation "+e.id,s),i=xr("Get last message in conversation "+e.id,yield n);var a,o;return E((a=r,o=0===i.length?null:i[0],H({id:a.id,subject:a.subject,photoUrl:a.photoUrl,welcomeMessages:H(a.welcomeMessages),custom:H(a.custom),createdAt:a.createdAt,joinedAt:a.joinedAt,lastMessageAt:a.lastMessageAt,unreadMessageCount:a.unreadMessageCount,isUnread:a.isUnread,access:a.access,notify:a.notify,lastMessage:o,readUntil:a.readUntil,everyoneReadUntil:a.everyoneReadUntil})))})}listMessages(e,t,n){return y(this,null,function*(){const s=yield this.call({method:"GET",path:["me","conversations",e,"messages"],data:t,headers:n});if(!s.ok)return Ir(s,"Listing messages in "+e);const r=s.value.data.data,i=yield Promise.all(r.map(t=>this.hydrateMessageData(t,e))),a=i.find(e=>!e.ok);return void 0===a||a.ok?E(i.map(({value:e})=>e)):a})}getReferencedMessage(e,t){return y(this,null,function*(){const n=yield this.call({method:"GET",path:["me","conversations",e,"messages",t],data:{}});if(!n.ok&&"server"===n.where&&404===n.value.status)return E(null);if(!n.ok&&"server"===n.where&&403===n.value.status&&"NOT_A_PARTICIPANT"===n.value.errorCode)return E(null);if(!n.ok)return Ir(n,`Fetching referenced message ${t} in conversation ${e}`);const s=n.value.data,r=yield this.getUser(s.senderId);if(!r.ok)return r;var i,a;return E((i=s,a=r.value,H({id:i.id,type:i.type,sender:a,referencedMessageId:i.referencedMessageId,custom:H(i.custom),createdAt:i.createdAt,editedAt:i.editedAt,origin:i.origin,content:i.content,reactions:_e(i.reactions),plaintext:Ie(i.content,{})})))})}getUser(e){return y(this,null,function*(){const t=yield this.call({method:"GET",path:["users",e],data:{includePrivateFields:!1}});return t.ok||"server"!==t.where||404!==t.value.status?t.ok?E(Ee(t.value.data)):Ir(t,"Get user "+e):E(null)})}}function Ir(e,t){return"server"===e.where?_(p(d({},e.value),{operation:t})):e}function xr(e,t){var n;if(t.ok)return t.value;throw"SESSION_DESTROYED"===t.value?new Error(`${e} failed because the session was destroyed`):new Error(R(null!=(n=t.value.operation)?n:e,t.value))}class Er{constructor(e,t,n){this.realtimeWsApiUrl=e,this.internalHttpApiUrl=t,this.restApiHttpUrl=n}getBokensUrl(e,t,n){return this.internalHttpApiUrl+`/${e}/bokens/${encodeURIComponent(t)}?signature=${encodeURIComponent(null!=n?n:"")}`}getRealtimeWsUrl(e,t,n,s,r){const i=encodeURIComponent(t);return this.realtimeWsApiUrl+`/${e}/realtime/${i}?talkjs-client-build=${null!=r?r:"standalone"}&talkjs-core=${n}&talkjs-client-id=${s}`}static fromHost(e){var t;const n=new Er("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");if(!e)return n;if("@currentHost"===e){if("undefined"==typeof location)throw new Error("You can only use @currentHost in a browser.");e=(null!=(t=window.top)?t:window).location.host}if(e.endsWith("talkjs.com")){const t=e.match(/^(?:\w+-)?([^.]+)\.talkjs\.com$/);if(t){const e=t[1];return["app","cdn","api","realtime"].includes(e)?n:new Er(`wss://realtime-${e}.talkjs.com/v1`,`https://app-${e}.talkjs.com/api/v0`,`https://api-${e}.talkjs.com/v1`)}return n}return e.includes("localhost")||e.includes("localtest.me")||/^\d+\.\d+\.\d+\.\d+(:\d+)?$/.test(e)?new Er(`ws://${e}/public_api/v1`,`http://${e}/api/v0`,`http://${e}/public_api/v1`):new Er(`wss://${e}/public_api/v1`,`https://${e}/api/v0`,`https://${e}/public_api/v1`)}}function Mr({method:e,url:t,data:n,options:s,attempts:r,shouldRetry:i,authProvider:a,errorTracker:o,abortSignal:l}){var c;(!r||r<=0)&&(r=1);const u={"x-talkjs-client-build":"jssdk-dev","x-talkjs-client-date":"2026-02-24T08:38:41.193Z"};return n instanceof FormData||(u["Content-Type"]=null!=(c=null==s?void 0:s.contentType)?c:"application/json"),T(r,()=>y(null,null,function*(){if(a){const e=yield a.getToken();u.Authorization=`Bearer ${e}`}return fetch(t,{method:e,headers:u,body:n,signal:l}).then(e=>{if(e.ok)return e;throw e})}),{initialDelay:.2,log:void 0,shouldRetry:n=>y(null,null,function*(){return a&&401===n.status?(null==o||o.log(`401 error from ${e} ${t}, ${yield a.getToken()}`),a.invalidateAndRefresh(),!0):i?i(n):!("object"==typeof n&&"status"in n&&n.status>=400&&n.status<500)})}).catch(n=>{if(Math.random()<.1&&!t.toString().startsWith("https://capture.trackjs.com")){const s=`Network Error for ${e} ${t}`;"undefined"!=typeof window&&(n instanceof Response?n.clone().text().then(e=>null==o?void 0:o.log(`${s} ${n.status} ${e} (10% logged)`)):null==o||o.log(`${s} ${n} (10% logged)`)),console.error("[TalkJS]",s)}throw n})}class _r{constructor(e){var t,r,i,a;v(this,n),v(this,s),this._timeCreated=Date.now(),b(this,n,null!=(r=null==(t=globalThis.document)?void 0:t.referrer)?r:""),b(this,s,(null!=(a=null==(i=globalThis.location)?void 0:i.href)?a:globalThis.HermesInternal)?"React Native Hermes":""),this._trackJSData={customer:{application:"",correlationId:"",sessionId:"",token:"",userId:"",version:"dev-2026-02-24T08:38:41.193Z"},entry:"direct",environment:{age:Date.now()-this._timeCreated,dependencies:{},originalUrl:g(this,s),referrer:g(this,n),userAgent:window.navigator.userAgent},metadata:[],nav:[],network:[],url:g(this,s),stack:"",timestamp:(new Date).toISOString(),version:"dev-2026-02-24T08:38:41.193Z",throttled:0},this._url=`https://capture.trackjs.com/capture?token=${e}`,this._trackJSData.customer.token=e}setData({appId:e,meId:t,sessionId:n}){this._trackJSData.customer.userId=e,this._trackJSData.customer.sessionId=`${e}/${t}`,this._trackJSData.customer.correlationId=n}log(e){return y(this,null,function*(){try{const t=p(d({},this._trackJSData),{message:e});yield Mr({method:"POST",url:this._url,data:JSON.stringify(t),options:{contentType:"text/plain"}})}catch(t){console.error("[TalkJS] Failed when sending an error report. Error: ",t)}})}}n=new WeakMap,s=new WeakMap;const Ar={log:e=>Promise.resolve(),setData:e=>{}};class Nr{constructor(e,t={}){this._onSubscription=t,this._handlers={};for(const n in e)Object.hasOwnProperty.call(e,n)&&(this._handlers[n]=[])}emit(e,t){for(const s of this._handlers[e])try{s(t)}catch(n){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,n)}}emitAsync(e,t){return y(this,null,function*(){try{const n=this._handlers[e].map(e=>e(t));yield Promise.all(n)}catch(n){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,n)}})}supports(e){return e in this._handlers}on(e,t){var n,s;if(!this.supports(e))throw new Error(`Unknown event type '${String(e)}'`);null==(s=(n=this._onSubscription)[e])||s.call(n),this._handlers[e].push(t)}off(e,t){if(!Object.hasOwnProperty.call(this._handlers,e))throw new Error(`Unknown event type '${String(e)}'`);const n=this._handlers[e].indexOf(t);-1!==n&&this._handlers[e].splice(n,1)}removeAllListeners(){for(const e in this._handlers)this._handlers[e]=[]}handles(e){return this._handlers[e].length>0}subscribe(e,t){return this.on(e,t),{unsubscribe:()=>this.off(e,t)}}}class Dr{constructor(e){this.handlers=e,this.tokenResult=null,this.pendingToken=null}getTokenResult(){return y(this,null,function*(){if(this.tokenResult)return this.tokenResult;if(this.pendingToken)return this.pendingToken.promise;const e=I();return this.pendingToken=e,this.handlers.onNeedToken(),e.promise})}getCachedTokenResult(){return this.tokenResult?this.tokenResult:void 0}setTokenResult(e){this.pendingToken&&(this.pendingToken.resolve(e),this.pendingToken=null),this.tokenResult=e,this.handlers.onChange(e)}refreshToken(){this.pendingToken||(this.pendingToken=I(),this.handlers.onNeedToken())}invalidateAndRefresh(){this.tokenResult=null,this.refreshToken()}}class Rr{constructor(e,t,n,s){this.apiUrls=e,this.appId=t,this.userId=n,this.signature=s,this.inner=new Dr({onChange:e=>{e.ok?this.eventEmitter.emit("tokenChanged",e.value):this.emitTokenRefreshFailed(e.value)},onNeedToken:()=>y(this,null,function*(){if(this._usingBokens&&!this.signature&&!this._calledBokens&&(yield new Promise(e=>setTimeout(e,1))),this._usingBokens)yield this.sendBokenRequest().then(e=>this.inner.setTokenResult(E(e))).catch(e=>this.inner.setTokenResult(_(e)));else if(this.onNeedToken)this.onNeedToken();else{const e=M("Cannot refresh token, no `onNeedToken` provided.");this.inner.setTokenResult(e)}})}),this._usingBokens=!0,this._calledBokens=!1,this.onNeedToken=void 0,this.eventEmitter=new Nr({tokenChanged(e){},tokenRefreshFailed(e){},tokenAccepted(e){}}),this.sessionExpiryWarningTimeoutId=void 0;const r="undefined"!=typeof window&&e.restApiHttpUrl.includes("api.talkjs.com");this.errorTracker=r?new _r("970cd0be0fb74630b75c8451051299dc"):Ar}get usingBokens(){return this._usingBokens}getToken(){return y(this,null,function*(){return Pr(yield this.inner.getTokenResult())})}getCachedToken(){const e=this.inner.getCachedTokenResult();if(void 0!==e)return Pr(e)}checkCanSetAuth(){if(this._calledBokens)throw new Error("[TalkJS] Cannot switch to JWT authentication once connected to TalkJS servers. To use JWTs, call `setToken` or set `onNeedToken` before triggering any requests or mounting any components. We recommend setting up authentication in your app's entry point (App.jsx, main.js, or similar) so it runs first.")}setToken(e){this.checkCanSetAuth(),setTimeout(()=>this.checkJwt(e),200),this._usingBokens=!1,this.inner.setTokenResult(E(e))}setTokenError(e){this._usingBokens=!1,this.inner.setTokenResult(M(e))}refreshToken(){this.inner.refreshToken()}invalidateAndRefresh(){this.inner.invalidateAndRefresh()}setOnNeedToken(e){this.checkCanSetAuth(),this._usingBokens=!1,this.onNeedToken=e}onTokenChanged(e){return this.eventEmitter.on("tokenChanged",e),()=>{this.eventEmitter.off("tokenChanged",e)}}onTokenRefreshFailed(e){return this.eventEmitter.on("tokenRefreshFailed",e),()=>{this.eventEmitter.off("tokenRefreshFailed",e)}}emitTokenRefreshFailed(e){this.eventEmitter.emit("tokenRefreshFailed",e)}onTokenAccepted(e){return this.eventEmitter.on("tokenAccepted",e),()=>{this.eventEmitter.off("tokenAccepted",e)}}emitTokenAccepted(e){this.eventEmitter.emit("tokenAccepted",e)}clearScheduledRefresh(){this.sessionExpiryWarningTimeoutId&&clearTimeout(this.sessionExpiryWarningTimeoutId)}scheduleRefresh(e){if(this.clearScheduledRefresh(),null===e)return;const t=void 0!==this.onNeedToken;e<120&&!t?console.warn(`[TalkJS] TalkJS will stop working in ${e} seconds due to auth token expiry. Token expires in ${e} seconds, and cannot be refreshed because no \`onNeedToken\` callback was provided. Non-refreshable tokens are recommended to expire at least 24 hours in the future.`):e<120&&t?console.warn(`[TalkJS] TalkJS auth token will expire and need to be refreshed in ${e} seconds. Refreshable JWTs are recommended to expire at least 30 minutes in the future, to improve performance and reduce unnecessary refreshes.`):e<3300&&!t&&console.warn(`[TalkJS debug] TalkJS will stop working in ${Math.round(e/60)} minutes due to auth token expiry. Non-refreshable tokens are recommended to expire at least 24 hours in the future. Alternatively, set \`onNeedToken\` with a callback that will run whenever a new token is needed.`);const n=e>600?e-300:e/2,s=Math.min(1728e6,1e3*n);this.sessionExpiryWarningTimeoutId=setTimeout(()=>{void 0!==this.onNeedToken&&this.refreshToken()},s)}checkJwt(e){!function(e){if(!("string"==typeof e||e instanceof String)){if(void 0===e)throw"Token was undefined";throw"Token must be a string, got: "+e}}(e);const t=[];let n,s,r;if("string"==typeof e?n=e:t.push(`Token type is ${typeof e} instead of a string.`),n)try{const e=function(e){const t=e.split(".");if(3!==t.length)throw"Token does not contain exactly two `.`. Check that you generated your JWT correctly. It should be `<header>.<payload>.<signature>`.";return{header:Or(t[0]),payload:Or(t[1])}}(n);s=e.header,r=e.payload}catch(i){t.push(i)}if(s){const e=this.checkJwtHeader(s);t.push(...e)}if(r){const e=this.checkJwtPayload(r);t.push(...e)}if(t.length)if(this.usingBokens)this.errorTracker.log(`JWT Errors detected by AuthProvider when using bokens: ${t.join("\n")}`);else{console.warn("[TalkJS] Authentication token appears to be generated incorrectly. Will still attempt to authenticate, but TalkJS may not work as expected. See below for a description of any problems and how to fix them.");const n=t.length>1;t.forEach((e,t)=>{const s=n?`Reason ${t+1}:`:"Reason:";console.warn(`[TalkJS] ${s} ${e}`)}),console.warn(`[TalkJS]: Authentication token: "${e}"`)}}checkJwtHeader(e){const t=[],n=e.alg;return void 0===n?t.push('Token header must contain `"alg": "HS256"`, but no `alg` was specified.'):"string"!=typeof n?t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):"HS256"!==n&&t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was set to "${n}" instead. HS256 is the only supported algorithm.`),t}checkJwtPayload(e){const t=[],n=e.iss;void 0===n?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was missing.`):"string"!=typeof n?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):n!==this.appId&&t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was set to "${n}" instead.`);const s=e.sub;void 0===s?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was missing.`):"string"!=typeof s?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was ${typeof s} instead of a string. Make sure you wrap the value in "".`):s!==this.userId&&t.push(`Token payload must contain a \`sub\` claim set to your userId ID (${this.userId}), but \`sub\` was set to "${s}" instead.`);const r=e.tokenType;void 0===r?t.push('Token payload must contain a `"tokenType": "user"` claim, but no `tokenType` was specified.'):"string"!=typeof r?t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was ${typeof r} instead of a string. Make sure you wrap the value in "".`):"user"!==r&&t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was set to "${r}" instead.`);const i=e.exp;void 0===i||("number"!=typeof i?t.push(`Token payload contains an \`exp\` claim, but \`exp\` was ${typeof r} instead of a number. If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Don't wrap the value in "".`):i<1e9?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01.`):i>1e11?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`):i<(new Date).getTime()/1e3&&t.push(`Token payload contains an \`exp\` claim, but \`exp\` (${i}, representing ${new Date(1e3*i).toLocaleDateString()}) appears to be in the past, meaning the token will be rejected. This error can also happen if your device's clock is set incorrectly, in which case the token will still work.`));const a=e.nbf;return void 0===a||("number"!=typeof a?t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` was ${typeof r} instead of a number. If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01.`):a>1e11&&t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` is very large (${a}, representing ${new Date(1e3*a).toLocaleDateString()}). If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`)),t}sendBokenRequest(){return y(this,null,function*(){this._calledBokens=!0;let e=0;const t=this.apiUrls.getBokensUrl(this.appId,this.userId,this.signature),n=yield Mr({method:"GET",url:t,attempts:1e4,shouldRetry:t=>{if(t instanceof Error)return!0;if(401===t.status)throw"Check that you provided a valid signature.";if(404===t.status)throw"Check that you specified the correct App ID.";if(429===t.status||502===t.status)return!0;if(t.status>=400&&t.status<500)throw`Unexpected HTTP ${t.status} response when fetching auth token. Check that you configured the session correctly.`;if(e++,e>=5)throw`Unexpected HTTP ${t.status} response when fetching auth token, retrying did not help.`;return!0},errorTracker:this.errorTracker});return(yield n.json()).boken})}}function Or(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(n)}catch(t){throw`Could not base64-decode and JSON-parse token section: ${e}. Check that you base-64 encoded the section correctly.`}}function Pr(e){if(e.ok)return e.value;throw e.value}const jr=new class{constructor(){this.registry={}}getOrCreate(e){const t=this.key(e),n=this.registry[t];if(n)return n;const s=new $r(e);return this.registry[t]=s,s}deregister(e,t){const n=this.key({appId:e,userId:t});delete this.registry[n]}key({appId:e,userId:t}){return`${e}:${t}`}};class $r{constructor(e){this._onNeedToken=void 0,function(e){function t(e,t){if(!e)throw new Error("[TalkJS] TalkSession: "+t)}t(e&&"object"==typeof e,"Expected an object argument in `getTalkSession`."),t(e.appId&&"string"==typeof e.appId,"The `appId` property of the `getTalkSession` options is required and it must be a non-empty string."),t("string"==typeof e.userId,"The `userId` property of the `getTalkSession` options is required and it must be a string."),void 0!==e.token&&t(e.token&&"string"==typeof e.token,"The `token` property of the `getTalkSession` options must be a non-empty string."),void 0!==e.tokenFetcher&&t("function"==typeof e.tokenFetcher,"The `tokenFetcher` property of the `getTalkSession` options must be a function.")}(e);const{appId:t,userId:n,token:s,tokenFetcher:r,signature:i}=e;this._appId=t,this._apiUrls=e.apiUrls?new Er(e.apiUrls.realtimeWsApiUrl,e.apiUrls.internalHttpApiUrl,e.apiUrls.restApiHttpUrl):Er.fromHost(e.host),this._authProvider=new Rr(this._apiUrls,t,n,i),s&&this._authProvider.setToken(s),r&&this._authProvider.setOnNeedToken(()=>y(this,null,function*(){try{const e=yield r();this._authProvider.setToken(e)}catch(e){this._authProvider.setTokenError(`${e}`)}}));const a=Math.random().toString().split(".")[1];this._realtimeClient=new Tr(this._apiUrls.getRealtimeWsUrl(t,n,"1.8.2",a,e.clientBuild),n,this._authProvider),this.currentUser=this.user(n),this._terminationReason=I(),this._terminationReason.promise.then(e=>{console.error(`[TalkJS] ${e}`)}),function(e,t){return y(this,null,function*(){return Mr({method:"GET",url:`${t}/${e}`}).then(e=>y(null,null,function*(){return 200===e.status||404!==e.status&&(console.warn(`[TalkJS] Received unexpected ${e.status} status code when validating app ID. Assuming that the app ID is valid.`),!0)})).catch(e=>{if("string"!=typeof e&&"status"in e){const t=e;return 200===t.status||404!==t.status&&(console.warn(`[TalkJS] Received unexpected ${t.status} status code when validating app ID. Assuming that the app ID is valid.`),!0)}return console.warn("[TalkJS] Encountered network issues when validating app ID. Assuming that the app ID is valid."),!0})})}(this._appId,this._apiUrls.internalHttpApiUrl).then(e=>{e||this.terminate(new Error(`The app ID ${this._appId} does not exist. Make sure you are using the correct app ID as found on the TalkJS dashboard. App IDs are case-sensitive.`))}),this._authProvider.onTokenRefreshFailed(e=>{this.terminate(new Error(`Could not authenticate, cannot recover automatically: ${e}`))})}setToken(e){this._authProvider.setToken(e)}get onNeedToken(){return this._onNeedToken}set onNeedToken(e){this._onNeedToken=e,void 0===e?this._authProvider.setOnNeedToken(void 0):this._authProvider.setOnNeedToken(()=>{try{e()}catch(t){console.error("[TalkJS] error when calling `onNeedToken` - your auth token will expire soon.",t)}})}onError(e){const t=I();return Promise.race([t.promise,this._terminationReason.promise]).then(t=>{"UNSUBSCRIBED"!==t&&e(t)}),{unsubscribe:()=>t.resolve("UNSUBSCRIBED")}}user(e){if("string"!=typeof e)throw new Error(`Creating UserRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating UserRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.user(e)}conversation(e){if("string"!=typeof e)throw new Error(`Creating ConversationRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating ConversationRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.conversation(e)}subscribeConversations(e){return new dr(this._realtimeClient,e)}searchMessages(e){let t;return{setQuery:n=>t&&t.searchString===n?t.currentState:(t&&t.cancel(),n&&""!==n?(t=new Wr(e,n,`${this._apiUrls.restApiHttpUrl}/${this._appId}/me/messages/search`,e=>y(this,null,function*(){const[t,n]=yield Promise.all([this.conversation(e.conversationId).get(),this._realtimeClient.hydrateMessageData(e,e.conversationId)]);return null===t?M("Message belongs to nonexistent conversation"):n.ok?E({conversation:t,message:n.value}):n}),this._authProvider),t.loadMore(3)):(t=void 0,null==e||e([],"loadedAll"),Promise.resolve({results:[],loadedAll:!0}))),loadMore:e=>t?t.loadMore(null!=e?e:10):Promise.resolve({results:[],loadedAll:!0})}}searchConversations(e){let t;return{setQuery:n=>t&&t.searchString===n?t.currentState:(t&&t.cancel(),n&&""!==n?(t=new Wr(e,n,`${this._apiUrls.restApiHttpUrl}/${this._appId}/me/conversations/search`,e=>y(this,null,function*(){const t=yield this._realtimeClient.hydrateConvData(e);if(!t.ok)return t;const n=t.value;return null===n?_({status:404,errorCode:"CONVERSATION_NOT_FOUND",reasons:["No conversation with that ID was found"]}):E(n)}),this._authProvider),t.loadMore(3)):(t=void 0,null==e||e([],"loadedAll"),Promise.resolve({results:[],loadedAll:!0}))),loadMore:e=>t?t.loadMore(null!=e?e:10):Promise.resolve({results:[],loadedAll:!0})}}terminate(e){jr.deregister(this._appId,this.currentUser.id),this._terminationReason.resolve(e),this._realtimeClient.destroy()}_isConnected(){return this._realtimeClient.isConnected()}uploadFile(e,t){return Ur(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,t)}uploadImage(e,t){return Ur(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,d({subtype:"image"},t))}uploadVideo(e,t){return Ur(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,d({subtype:"video"},t))}uploadAudio(e,t){return Ur(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,d({subtype:"audio"},t))}uploadVoice(e,t){return Ur(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,d({subtype:"voice"},t))}}function Ur(e,t,n,s,r){return y(this,arguments,function*(e,t,n,s,{subtype:r,filename:i,width:a,height:o,duration:l}){D("Upload file",yield n.call({method:"POST",path:["files","validate"],data:{filename:i,filesize:s.size}}));const c=new FormData;return c.set("file",s,i),void 0!==r&&c.set("subtype",r),void 0!==a&&c.set("width",a.toString()),void 0!==o&&c.set("height",o.toString()),void 0!==l&&c.set("duration",l.toString()),Mr({method:"POST",url:e,data:c,authProvider:t,errorTracker:t.errorTracker}).then(e=>e.json()).then(e=>e.fileToken).catch(e=>y(null,null,function*(){if(e instanceof Response){const t=yield e.json(),n=`Unexpected response when uploading file, status code ${e.status} ${t.errorCode}, ${t.reasons}`;throw new Error(n)}throw e}))})}class Wr{constructor(e,t,n,s,r){this.onResults=e,this.searchString=t,this.baseUrl=n,this.hydrateData=s,this.authProvider=r,this.error=void 0,this.lastCompletedQueryState={results:[],loadedAll:!1},this.currentCursor=void 0,this.cancelQuery=()=>{},null==e||e([],"searching")}get currentState(){return this.loadingDeferred?this.loadingDeferred.promise:Promise.resolve(this.lastCompletedQueryState)}cancel(){this.cancelQuery()}buildUrl(e){const t=new URL(this.baseUrl);return void 0===this.currentCursor&&t.searchParams.append("searchString",encodeURIComponent(this.searchString)),void 0!==this.currentCursor&&t.searchParams.append("cursor",this.currentCursor),t.searchParams.append("limit",e.toString()),t.toString()}loadMore(e){return y(this,null,function*(){var t,n;if(this.error)throw this.error;if(this.loadingDeferred)return this.loadingDeferred.promise;if(this.lastCompletedQueryState.loadedAll)return Promise.resolve(this.lastCompletedQueryState);this.loadingDeferred=I(),this.loadingDeferred.promise.catch(()=>{});const s=new AbortController;this.cancelQuery=()=>{s.abort()};const r=this.buildUrl(e),i=[],a=yield this._performSearch(r,s,e=>{const t=this.hydrateData(e);i.push(t),void 0!==this.onResults&&Promise.all(i).then(e=>{const t=N(e),n=H([...this.lastCompletedQueryState.results,...t]);this.onResults(n,"searching")})}),o=a.ok?a.value:void 0;if(yield Promise.all(i).then(e=>{var t;const n=N(e),s=H([...this.lastCompletedQueryState.results,...n]),r=void 0===o;this.lastCompletedQueryState=H({results:s,loadedAll:r}),this.currentCursor=o;const i=r?"loadedAll":"canLoadMore";null==(t=this.onResults)||t.call(this,s,i)}),a.ok)return null==(t=this.loadingDeferred)||t.resolve(this.lastCompletedQueryState),this.loadingDeferred=void 0,this.lastCompletedQueryState;throw null==(n=this.loadingDeferred)||n.reject(a.value),this.loadingDeferred=void 0,this.error=a.value,a.value})}_performSearch(e,t,n){return y(this,null,function*(){let s;return Mr({method:"GET",url:e,authProvider:this.authProvider,errorTracker:this.authProvider.errorTracker,abortSignal:t.signal}).then(e=>y(this,null,function*(){if(!e.body)return _("Search response was missing body");const t=e.body.getReader(),r=new TextDecoder;let i="",a=!0;const o=(e,t)=>{if(a)a=!1;else try{if(e.startsWith("]")){const t=`{"data":[${e}`,n=JSON.parse(t);return void(s=n.cursor)}let n=e;n.startsWith(",")&&(n=n.slice(1)),t(JSON.parse(n))}catch(n){console.warn("[TalkJS] Error during search, received unexpected data, ignoring. Some search results may be missing.")}};for(;;){const{done:e,value:s}=yield t.read();if(e)break;i+=r.decode(s,{stream:!0});const a=i.split("\n");i=a.pop()||"";for(const t of a)o(t,n)}i+=r.decode();const l=i.split("\n");for(const e of l)o(e,n);return E(s)})).catch(e=>y(this,null,function*(){if(e instanceof DOMException&&"AbortError"===e.name)return E(void 0);if(e instanceof Response){const t=yield e.clone().json();return _(R("Search",{status:e.status,errorCode:t.errorCode,reasons:t.reasons}))}return _(e)}))})}}exports.getTalkSession=function(e){if(!e)throw new Error("[TalkJS] Must provide an options object to `getTalkSession`");return e.forceCreateNew?new $r(e):jr.getOrCreate(e)},exports.registerPolyfills=function({WebSocket:e}){O=e};
|
|
1
|
+
"use strict";var e,t,s,n,r=Object.defineProperty,i=Object.defineProperties,a=Object.getOwnPropertyDescriptors,o=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,c=Object.prototype.propertyIsEnumerable,u=e=>{throw TypeError(e)},d=(e,t,s)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,h=(e,t)=>{for(var s in t||(t={}))l.call(t,s)&&d(e,s,t[s]);if(o)for(var s of o(t))c.call(t,s)&&d(e,s,t[s]);return e},p=(e,t)=>i(e,a(t)),f=(e,t)=>{var s={};for(var n in e)l.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&o)for(var n of o(e))t.indexOf(n)<0&&c.call(e,n)&&(s[n]=e[n]);return s},g=(e,t,s)=>t.has(e)||u("Cannot "+s),m=(e,t,s)=>(g(e,t,"read from private field"),s?s.call(e):t.get(e)),v=(e,t,s)=>t.has(e)?u("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),y=(e,t,s,n)=>(g(e,t,"write to private field"),n?n.call(e,s):t.set(e,s),s),b=(e,t,s)=>new Promise((n,r)=>{var i=e=>{try{o(s.next(e))}catch(ft){r(ft)}},a=e=>{try{o(s.throw(e))}catch(ft){r(ft)}},o=e=>e.done?n(e.value):Promise.resolve(e.value).then(i,a);o((s=s.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=Symbol("*"),k=w,C=w,S=w,I=w;function T(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(t[s]!==w&&e[s]!==t[s])return!1;return!0}function x(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}function E(e,t){return e*(1-t+2*Math.random()*t)}const M=()=>!0;function R(e,t,s){return b(this,arguments,function*(e,t,{initialDelay:s,maxDelay:n,log:r,shouldRetry:i=M}){return t().catch(a=>b(null,null,function*(){if(0===e)throw a;if(!(yield i(a)))throw a;const o=1e3*s*1.2,l=E(n?Math.min(1e3*n,o):o,.05);return x(l).then(()=>R(e-1,t,{initialDelay:l/1e3,maxDelay:n,log:r,shouldRetry:i}))}))})}function A(){const e={},t=new Promise(function(t,s){e.resolve=t,e.reject=s});return e.promise=t,e}class _{constructor(e,t,s){this.layer=e,this.states=t,this.transitions=s,this._state=t[0]}get state(){return this._state}transition(e){const t=this.transitions[e];if(!t)return;if(!this.canTransition(e))return;const s=this.state;this._state=t.to,t.afterTransition({from:s,to:this.state})}canTransition(e){const t=this.transitions[e];return!!t&&("ANY"===t.from||t.from.includes(this.state))}}function N(e){return{ok:!0,value:e}}function D(e){return{ok:!1,where:"client",value:e}}function O(e){return{ok:!1,where:"server",value:e}}function P(){const e={},t=new Promise(t=>{e.ok=e=>b(null,null,function*(){return t(N(e))}),e.clientErr=e=>t(D(e)),e.serverErr=e=>t(O(e)),e.resolve=e=>t(e)});return e.promise=t,e}function j(e){return e.filter(e=>e.ok).map(e=>e.value)}function U(e,t){if(t.ok)return t.value.data;if("SESSION_DESTROYED"===t.value)throw new Error(`${e} failed because the session was destroyed`);if("server"===t.where)throw new Error($(e,t.value));throw"unreachable"}function $(e,t){let s;return s=Array.isArray(t.reasons)?t.reasons.join():JSON.stringify(t.reasons),`${e} failed, got status ${t.status} ${t.errorCode}, reasons: ${s}`}let W=null;class q{constructor(e,t){this.realtimeUrl=e,this.handlers=t,this.socket=null,this.stateMachine=new _("ReconnectingSocket",["STOPPED","CONNECTING","READY","DISCONNECTED","TERMINATED"],{startWs:{from:["STOPPED","DISCONNECTED"],to:"CONNECTING",afterTransition:()=>{const e=new(function(){if(W)return W;if(globalThis.WebSocket)return globalThis.WebSocket;throw new Error("Missing WebSocket implementation")}())(this.realtimeUrl+"&talkjs-time="+Date.now());this.socket=e,e.addEventListener("open",()=>{this.socket===e&&this.stateMachine.transition("onOpen")}),e.addEventListener("close",()=>{this.socket===e&&this.stateMachine.transition("onClose")}),e.addEventListener("message",t=>{this.socket===e&&this.handlers.onMessage(t)})}},onOpen:{from:["CONNECTING"],to:"READY",afterTransition:()=>{this.handlers.onOpen()}},onClose:{from:["CONNECTING","READY"],to:"DISCONNECTED",afterTransition:e=>b(this,[e],function*({from:e}){"READY"===e&&this.handlers.onClose(),this.socket=null;const t=E(1e4,.5);setTimeout(()=>{"DISCONNECTED"===this.stateMachine.state&&this.stateMachine.transition("startWs")},t)})},stopWs:{from:["CONNECTING","DISCONNECTED","READY"],to:"STOPPED",afterTransition:({from:e})=>{"READY"===e&&this.handlers.onClose();const t=this.socket;this.socket=null,null==t||t.close(1e3)}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{const e=this.socket;this.socket=null,null==e||e.close(1e3)}}})}stopWs(){this.stateMachine.transition("stopWs")}startWs(){this.stateMachine.transition("startWs")}send(e){return"READY"===this.stateMachine.state?(this.socket.send(e),N(void 0)):D("SOCKET_NOT_READY")}terminate(){const e=this.socket;this.stateMachine.canTransition("onClose")&&this.stateMachine.transition("onClose"),e&&("terminate"in e?e.terminate():e.close(1e3))}destroy(){this.stateMachine.transition("destroy")}}class L{constructor(e,t){this.handlers=t,this.socket=new q(e,{onOpen:()=>this.handlers.onOpen(),onClose:()=>this.handlers.onClose(),onMessage:e=>this.onWebSocketMessage(e)})}call(e,t){const s=`/${t.path.map(e=>encodeURIComponent(e)).join("/")}`,n=JSON.stringify([e,t.method,s,t.data,t.headers]);return this.socket.send(n)}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.socket.destroy()}terminate(){this.socket.terminate()}onWebSocketMessage(e){try{const t=JSON.parse(e.data);if("PUBLISH"===t[1]){const e=t[0],s=JSON.stringify([e,"ACK"]);this.socket.send(s);const n=t.slice(2),r=[];n.forEach(e=>{"session.expired"===e.type?this.handlers.onAuthExpired():"upstream.restarting"===e.type?this.handlers.onUpstreamRestarting():r.push(e)}),r.length>0&&this.handlers.onPublish(e,r)}else{const e=t[0],s=t[1],n=t[2];this.handlers.onResponse(e,s,n)}}catch(t){}}}class B{constructor(e){this.delayMs=e,this.timeout=void 0}schedule(e){this.stop(),this.timeout=setTimeout(()=>{void 0!==this.timeout&&(this.stop(),e())},this.delayMs)}stop(){void 0!==this.timeout&&(clearTimeout(this.timeout),this.timeout=void 0)}}const G="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class F{constructor(){this.i=-1}next(){return this.i++,this.i}reset(){this.i=-1}}class H{constructor(e,t){this.handlers=t,this.seqCounter=new F,this.responseHandlers={},this.heartbeats=new z(this),this.socket=new L(e,{onUpstreamRestarting:()=>{this.heartbeats.serverActive(),this.handlers.onUpstreamRestarting()},onOpen:()=>{this.heartbeats.clientActive(),this.heartbeats.serverActive(),this.handlers.onReady()},onClose:()=>{this.heartbeats.stop(),Object.values(this.responseHandlers).forEach(e=>{e.clientErr("WEBSOCKET_DISCONNECTED")}),this.responseHandlers={},this.seqCounter.reset(),this.handlers.onNotReady()},onResponse:(e,t,s)=>{this.heartbeats.serverActive(),this.onResponse(e,t,s)},onPublish:(e,t)=>{this.heartbeats.serverActive(),this.handlers.onPublish(e,t),this.heartbeats.clientActive()},onAuthExpired:()=>{this.heartbeats.serverActive(),this.handlers.onAuthExpired()}})}sync(){return b(this,null,function*(){yield new Promise(e=>G(()=>e()));const e=Object.values(this.responseHandlers).map(e=>e.promise.catch(()=>{}));return Promise.all(e)})}call(e){const t=this.seqCounter.next(),s=P();this.responseHandlers[t]=s;const n=this.socket.call(t,e);return n.ok||(s.resolve(n),delete this.responseHandlers[t]),this.heartbeats.clientActive(),s.promise}onResponse(e,t,s){return b(this,null,function*(){const n=this.responseHandlers[e];n&&(200===t?n.ok({status:t,data:s}):n.serverErr({status:t,errorCode:s.errorCode,reasons:s.reasons}),delete this.responseHandlers[e])})}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.heartbeats.stop(),Object.values(this.responseHandlers).forEach(e=>{e.clientErr("WEBSOCKET_DISCONNECTED")}),this.responseHandlers={},this.socket.destroy()}terminate(){this.socket.terminate()}}class z{constructor(e){this.connection=e,this.clientInactivityTimer=new B(25e3),this.serverInactivityTimer=new B(1e4),this.serverTimeoutTimer=new B(5e3)}clientActive(){this.clientInactivityTimer.schedule(()=>{this.sendHeartbeat()})}serverActive(){this.serverTimeoutTimer.stop(),this.serverInactivityTimer.schedule(()=>{this.sendHeartbeat(),this.serverTimeoutTimer.schedule(()=>{this.connection.terminate()})})}stop(){this.clientInactivityTimer.stop(),this.serverInactivityTimer.stop(),this.serverTimeoutTimer.stop()}sendHeartbeat(){this.connection.call({method:"GET",path:["ping"],data:{},headers:{}}).catch(()=>{})}}class J{constructor(e,t,s){this.authProvider=t,this.handlers=s,this.stateMachine=new _("AuthenticatedConnection",["WAITING_FOR_WS","LOGGING_IN","RENEWING_SESSION","READY","TERMINATED"],{logIn:{from:["WAITING_FOR_WS"],to:"LOGGING_IN",afterTransition:()=>b(this,null,function*(){yield this.renewSession()})},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>b(this,null,function*(){this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>b(this,null,function*(){yield this.renewSession()})},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>b(this,null,function*(){this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},authenticated:{from:["LOGGING_IN","RENEWING_SESSION"],to:"READY",afterTransition:({from:e})=>{"LOGGING_IN"===e&&this.handlers.onReady()}},authExpired:{from:["READY","RENEWING_SESSION"],to:"LOGGING_IN",afterTransition:()=>b(this,null,function*(){this.handlers.onNotReady(),this.authProvider.invalidateAndRefresh(),yield this.renewSession()})},wsDisconnected:{from:["READY","LOGGING_IN","RENEWING_SESSION"],to:"WAITING_FOR_WS",afterTransition:({from:e})=>{"READY"!==e&&"RENEWING_SESSION"!==e||this.handlers.onNotReady(),this.authProvider.clearScheduledRefresh()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{this.authProvider.clearScheduledRefresh(),this.connection.destroy()}}}),this.connection=new H(e,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onReady:()=>this.stateMachine.transition("logIn"),onNotReady:()=>{this.stateMachine.transition("wsDisconnected")},onAuthExpired:()=>{this.stateMachine.transition("authExpired")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}}),t.onTokenChanged(()=>{"READY"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauth")})}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){const t=this.connection.call(e);return t.then(e=>{e.ok||"server"!==e.where||401!==e.value.status||"READY"!==this.stateMachine.state&&"RENEWING_SESSION"!==this.stateMachine.state||this.stateMachine.transition("authExpired")}),t}stopWs(){this.connection.stopWs()}startWs(){this.connection.startWs(),this.authProvider.getToken().catch(()=>{})}destroy(){this.stateMachine.transition("destroy")}renewSession(){return b(this,null,function*(){let e;try{const t=this.authProvider.getCachedToken();e=t||(yield this.authProvider.getToken())}catch(r){return}const t=yield this.connection.call({method:"POST",path:["session","renew"],data:{token:e},headers:{}});if(!t.ok&&"client"===t.where)return;const s=t.value;if(s.status,200===s.status){const t=s.data.expiresInSeconds;return void(null!==t&&t<120?(console.warn(`[TalkJS] Authenticated with a token that expires in ${t}s. Treating it as already expired and refreshing. Newly generated tokens should last at least 10 minutes.`),"LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed")):(this.authProvider.scheduleRefresh(t),this.authProvider.emitTokenAccepted(e),this.stateMachine.canTransition("authenticated")&&this.stateMachine.transition("authenticated")))}if(401===s.status)return void("LOGGING_IN"===this.stateMachine.state?this.stateMachine.transition("logInFailed"):"RENEWING_SESSION"===this.stateMachine.state&&this.stateMachine.transition("scheduledReauthFailed"));if(400===s.status)return void this.authProvider.emitTokenRefreshFailed($("Authentication",s));if(402===s.status)return void this.authProvider.emitTokenRefreshFailed($("Authentication",s));const n=5e3*Math.random()+5e3;setTimeout(()=>{this.call({method:"POST",path:["session","renew"],data:{token:e},headers:{}}).catch(()=>{})},n)})}}class Y{constructor(e,t,s){this.handlers=s,this.stateMachine=new _("StopStartConnection",["STOPPED","WAITING_FOR_WS","READY","TERMINATED"],{unexpectedDisconnect:{from:["READY"],to:"WAITING_FOR_WS",afterTransition:()=>{this.inactivityTimer.stop(),this.handlers.onNotReady()}},stop:{from:["WAITING_FOR_WS","READY"],to:"STOPPED",afterTransition:()=>{this.connection.stopWs(),this.inactivityTimer.stop(),this.handlers.onNotReady()}},start:{from:["STOPPED"],to:"WAITING_FOR_WS",afterTransition:()=>{this.connection.startWs()}},ready:{from:["WAITING_FOR_WS"],to:"READY",afterTransition:()=>{this.pendingCalls=0,this.activeSubscriptions=0,this.inactivityTimer.schedule(()=>{this.stateMachine.transition("stop")}),this.handlers.onReady()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{this.inactivityTimer.stop(),this.connection.destroy()}}}),this.pendingCalls=0,this.activeSubscriptions=0,this.inactivityTimer=new B(3e3),this.connection=new J(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("ready")},onNotReady:()=>{"READY"===this.stateMachine.state&&this.stateMachine.transition("unexpectedDisconnect")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}get inactive(){return 0===this.pendingCalls&&0===this.activeSubscriptions}sync(){return b(this,null,function*(){return this.connection.sync()})}ensureStarted(){this.stateMachine.canTransition("start")&&this.stateMachine.transition("start")}call(e){return b(this,null,function*(){this.inactivityTimer.stop(),this.pendingCalls++,this.logTrace("Called",e.path,e.data);const t=yield this.connection.call(e);return this.pendingCalls--,this.logTrace("Received",e.path,e.data),"SUBSCRIBE"===e.method&&t.ok?(this.activeSubscriptions++,this.logTrace("Subscribed",e.path,e.data)):"UNSUBSCRIBE"===e.method&&t.ok&&(this.activeSubscriptions--,this.logTrace("Unsubscribed",e.path,e.data)),this.inactive&&this.inactivityTimer.schedule(()=>{this.stateMachine.transition("stop")}),t})}destroy(){this.stateMachine.transition("destroy")}isConnected(){return"READY"===this.stateMachine.state}logTrace(e,t,s){}}class V{constructor(e,t,s){this.handlers=s,this.stateMachine=new _("QueuedConnection",["NOT_READY","PROCESSING_QUEUE","READY","TERMINATED"],{processQueue:{from:["NOT_READY"],to:"PROCESSING_QUEUE",afterTransition:()=>{this.sendQueuedCalls()}},ready:{from:["PROCESSING_QUEUE"],to:"READY",afterTransition:()=>{this.handlers.onReady()}},notReady:{from:["PROCESSING_QUEUE","READY"],to:"NOT_READY",afterTransition:()=>{Object.values(this.subscribeQueue).forEach(e=>e.deferred.ok({status:200,data:{}})),this.subscribeQueue={},this.handlers.onSubscriptionsLost()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{for(var e;this.callQueue.length;){const t=null==(e=this.callQueue.shift())?void 0:e.deferred;null==t||t.clientErr("SESSION_DESTROYED")}this.connection.destroy()}}}),this.subscribeQueue={},this.callQueue=[],this.connection=new Y(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("processQueue")},onNotReady:()=>{this.stateMachine.transition("notReady")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return"READY"===this.stateMachine.state?this.connection.call(e):("NOT_READY"===this.stateMachine.state&&this.connection.ensureStarted(),"SUBSCRIBE"===e.method||"UNSUBSCRIBE"===e.method?this._subscribe(e):this._call(e))}_subscribe(e){const t=e.path.join("/"),s=this.subscribeQueue[t];if(s&&s.params.method===e.method)return s.deferred.promise;s&&s.params.method!==e.method&&(s.deferred.ok({status:200,data:{}}),delete this.subscribeQueue[t]);const n={deferred:P(),params:e};return this.subscribeQueue[t]=n,n.deferred.promise}_call(e){const t={deferred:P(),params:e};return this.callQueue.push(t),t.deferred.promise}dequeue(){for(const e in this.subscribeQueue){const t=this.subscribeQueue[e];return delete this.subscribeQueue[e],t}return this.callQueue.shift()}destroy(){this.stateMachine.transition("destroy")}sendQueuedCalls(){return b(this,null,function*(){let e=0;for(;"PROCESSING_QUEUE"===this.stateMachine.state;){e++;const t=this.dequeue();if(!t)return void this.stateMachine.transition("ready");this.connection.call(t.params).then(e=>{t.deferred.resolve(e)}),e>50&&(yield new Promise(e=>setTimeout(e,100)))}})}isConnected(){return"READY"===this.stateMachine.state||"PROCESSING_QUEUE"===this.stateMachine.state}}function Q(e){return Object.freeze(e)}function K(e){return Q(e.map(e=>function(e){switch(e.type){case"text":return Object.freeze({type:"text",children:Z(e.children)});case"file":case"location":return Object.freeze(e)}}(e)))}function Z(e){return Q(e.map(e=>function(e){if("string"==typeof e)return e;switch(e.type){case"bold":case"italic":case"strikethrough":case"bulletList":case"bulletPoint":case"link":case"actionLink":case"actionButton":return Object.freeze(p(h({},e),{children:Z(e.children)}));case"mention":case"autoLink":case"codeSpan":case"customEmoji":return Object.freeze(e)}}(e)))}function X(e,t){return void 0===t?e:t}function ee(e,t){return void 0===t?e:Q(t)}function te(e,t){if(void 0===t)return e;if(null===t)return Q({});const s=h({},e);for(const n in t){const e=t[n];null===e?delete s[n]:s[n]=e}return Q(s)}function se(e,t){if(e===t)return!0;if(!e||!t)return!1;if("object"!=typeof e||"object"!=typeof t)return!1;if(e.constructor!==t.constructor)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!se(e[s],t[s]))return!1}else{const s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(const n of s){if(!Object.hasOwnProperty.call(t,n))return!1;if(!se(e[n],t[n]))return!1}}return!0}const ne="undefined"!=typeof window&&null!=(t=window.queueMicrotask)?t:setTimeout;class re{constructor(e,t,s){this.headers=e,this.clearPendingBatch=t,this.sendCalls=s,this.sent=!1,ne(()=>this.send())}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class ie extends re{constructor(e,t,s){super(t,s,()=>{this.sendSubscribe(),this.sendGet()}),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e){return ie.isCorrectBatchTypeFor(e)&&se(this.headers,e.headers)}static isCorrectBatchTypeFor(e){const t=T(e.path,["users",S]),s="GET"===e.method||"SUBSCRIBE"===e.method;return t&&s}push(e){const t=e.path[1],s=P();return"GET"===e.method?this.getCalls.push({userId:t,deferred:s}):this.subscribeCalls.push({userId:t,deferred:s}),1e3!==this.getCalls.length&&1e3!==this.subscribeCalls.length||this.send(),s.promise}sendGet(){return b(this,null,function*(){if(0===this.getCalls.length)return;const e=[...new Set(this.getCalls.map(e=>e.userId))],t=yield this.connection.call({method:"GET",path:["users"],data:{ids:e,includePrivateFields:!1},headers:this.headers});if(t.ok)for(const s of this.getCalls){const e=t.value.data[s.userId];e?s.deferred.ok({status:200,data:e}):s.deferred.serverErr({status:404,errorCode:"NOT_FOUND",reasons:["No user with that ID exists"]})}else this.getCalls.forEach(e=>e.deferred.resolve(t))})}sendSubscribe(){if(0===this.subscribeCalls.length)return;const e=[...new Set(this.subscribeCalls.map(e=>e.userId))];this.connection.call({method:"SUBSCRIBE",path:["users"],data:{ids:e},headers:this.headers}).then(e=>this.subscribeCalls.forEach(t=>t.deferred.resolve(e)))}}class ae extends re{constructor(e,t,s,n){super(s,n,()=>this.sendMutate()),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e){return!(!ae.isCorrectBatchTypeFor(e)||e.path[1]!==this.conversationId||!se(this.headers,e.headers))}static isCorrectBatchTypeFor(e){return!(!T(e.path,["conversations",k,"participants",S])||"PUT"!==e.method&&"POST"!==e.method&&"PATCH"!==e.method)}push(e){const t=e.path[3],s=P();return this.calls.push({action:{id:t,method:e.method,params:e.data},deferred:s}),100===this.calls.length&&this.send(),s.promise}sendMutate(){return b(this,null,function*(){const e=this.calls.map(e=>e.action),t=yield this.connection.call({method:"POST",path:["conversations",this.conversationId,"participants"],data:{actions:e},headers:this.headers});if(!t.ok)return void this.calls.forEach(e=>e.deferred.resolve(t));const s=t.value.data.responses;for(let n=0;n<s.length;n++){const e=this.calls[n].deferred,t=s[n];200===t.status?e.ok(p(h({},t),{data:{}})):e.serverErr(t)}})}}class oe{constructor(e,t,s){this.pendingBatch=null,this.connection=new V(e,t,s)}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return b(this,null,function*(){var t;if(null==(t=this.pendingBatch)?void 0:t.canPush(e))return this.pendingBatch.push(e);this.pendingBatch&&this.pendingBatch.send();const s=this.createEmptyBatchFor(e);return s?(this.pendingBatch=s,s.push(e)):this.connection.call(e)})}destroy(){var e;this.connection.destroy(),null==(e=this.pendingBatch)||e.destroy()}isConnected(){return this.connection.isConnected()}createEmptyBatchFor(e){var t,s;if(ie.isCorrectBatchTypeFor(e))return new ie(this.connection,null!=(t=e.headers)?t:{},()=>this.pendingBatch=null);if(ae.isCorrectBatchTypeFor(e)){const t=e.path[1];return new ae(t,this.connection,null!=(s=e.headers)?s:{},()=>this.pendingBatch=null)}return null}}const le={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class ce{constructor(e,t,s){this.throttler=new ue,this.alive=!0,this.connection=new oe(e,t,s)}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return b(this,null,function*(){let t=0;for(;this.alive;){const s=yield this.connection.call(e);if((s.ok||"client"!==s.where||"SOCKET_NOT_READY"!==s.value)&&(s.ok||"server"!==s.where||500!==s.value.status)||t++,10===t)return s;if(s.ok||"client"!==s.where){const e=s.value,t=e.status,n=le[t];if("RESOLVE"===n)return this.throttler.resetDelay(),s;if("RETRY"===n)continue;if("DELAY"===n){yield this.throttler.wait();continue}return console.warn("[TalkJS] Unexpected status code",t),e}if("SESSION_DESTROYED"===s.value)return D("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==s.value&&("SOCKET_NOT_READY"!==s.value?s.value:yield this.throttler.wait())}return D("SESSION_DESTROYED")})}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class ue{constructor(){this.initialDelayMs=200,this.exponentialFactor=1.2,this.maxDelayMs=3e4,this.currentDelayMs=this.initialDelayMs,this.lastCall=0}getCurrentDelay(){return this.currentDelayMs}wait(){const e=(new Date).getTime(),t=E(this.currentDelayMs,.05),s=this.lastCall+t,n=Math.max(0,s-e);return this.lastCall=e+n,this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs),x(n)}resetDelay(){this.currentDelayMs=this.initialDelayMs}}function de(e){return e.map(e=>encodeURIComponent(e)).join()}class he{constructor(){this.paths={}}add(e){this.paths[de(e)]=e}delete(e){delete this.paths[de(e)]}has(e){return Object.hasOwnProperty.call(this.paths,de(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach(t=>e(t))}}class pe{constructor(e,t,s){this.handlers=s,this.targetSubscriptions=new he,this.connection=new ce(e,t,{onUpstreamRestarting:()=>this.handlers.onUpstreamRestarting(),onSubscriptionsLost:()=>{this.targetSubscriptions.forEach(e=>{this.resubscribe(e)}),this.handlers.onResubscribeSent()},onReady:()=>this.handlers.onReady(),onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}sync(){return b(this,null,function*(){return this.connection.sync()})}call(e){return this.connection.call(e)}subscribe(e){return b(this,null,function*(){return this.targetSubscriptions.add(e),this.connection.call({method:"SUBSCRIBE",path:e,data:{},headers:{}})})}unsubscribe(e){return b(this,null,function*(){return this.targetSubscriptions.delete(e),this.connection.call({method:"UNSUBSCRIBE",path:e,data:{},headers:{}})})}resubscribe(e){return b(this,null,function*(){const t=yield this.connection.call({method:"SUBSCRIBE",path:e,data:{},headers:{}});t.ok||this.handlers.onResubscribeError(e,t)})}destroy(){this.targetSubscriptions.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class fe{constructor(){this.prev=Promise.resolve()}runExclusive(e){return b(this,null,function*(){const t=this.prev.then(()=>e());return this.prev=t,t})}sync(){return b(this,null,function*(){return this.runExclusive(()=>{})})}}class ge{constructor(e){this.initialised=!1,this.getPointer=void 0,this.pendingStates=[e],e.resultPromise.then(()=>this.initialised=!0)}get pendingPointer(){if(0!==this.pendingStates.length)return this.pendingStates[this.pendingStates.length-1]}get mostRecentState(){var e;return null!=(e=this.pendingPointer)?e:this.getPointer}canAppendState(e){var t,s;const n=null==(t=this.getPointer)?void 0:t.seq;if(void 0!==n&&e<=n)return!1;const r=null==(s=this.pendingPointer)?void 0:s.seq;return!(void 0!==r&&e<r)}set(e){if(!this.canAppendState(e.seq))throw"Appending in the past";this.pendingStates.push(e)}mutate(e,t){if(!this.initialised)return;if(!this.canAppendState(e))throw"Mutating in the past";const s=this.mostRecentState.resultPromise.then(e=>e.ok?t(e):e);this.pendingStates.push({seq:e,resultPromise:s})}get(e){for(;this.pendingStates.length>0&&(void 0===this.getPointer||this.pendingStates[0].seq<=e);)this.getPointer=this.pendingStates.shift();return this.getPointer}}class me extends ge{constructor(e,t){super(e),this.onTeardown=t,this._error=null,this._lastGoodState=Promise.resolve(void 0),this.registerNewState(e.resultPromise)}get error(){return this._error}get lastGoodState(){return this._lastGoodState}mutate(e,t){super.mutate(e,t),this.registerNewState(this.mostRecentState.resultPromise)}set(e){super.set(e),this.registerNewState(this.mostRecentState.resultPromise)}registerNewState(e){const t=this.lastGoodState;this._lastGoodState=e.then(e=>e.ok?e.value:t),e.then(e=>{e.ok||this.setError(e)})}setError(e){var t;this._error||(this._error=e,null==(t=this.onTeardown)||t.call(this,e),this.lastGoodState.then(e=>{void 0!==e&&this.teardownNested(e)}))}}class ve extends me{constructor(e,t){const s=new Promise(e=>setTimeout(e)).then(()=>this.fetchInitial(e));super({seq:e,resultPromise:s},t.onTeardown),this.initialSeq=e,this.getDeepMutex=new fe,this.lastDeep=void 0}refetchInitial(e){return b(this,null,function*(){const t=this.mostRecentState.resultPromise,s=this.fetchInitial(e),[n,r]=yield Promise.all([t,s]);return void 0!==n&&n.ok&&r.ok&&this.equal(n.value,r.value)?n:r})}refetch(e){if(null!==this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.set(t)}changedBetween(e,t){return b(this,null,function*(){if(e>=t)return!1;const s=this.get(t),n=yield s.resultPromise;return!!n.ok&&(n.value.lastChanged>Math.max(this.initialSeq,e)&&n.value.lastChanged<=t||(yield this.anyChildChanged(e,t,n.value)))})}getDeep(e){return b(this,null,function*(){return this.getDeepMutex.runExclusive(()=>b(this,null,function*(){var t;if(null!==this.error)return this.error;const s=null==(t=this.lastDeep)?void 0:t.seq;if(e===s)return this.lastDeep.deep;if(void 0!==s){if(e<s)throw`Trying to load seq ${e} when we have previously loaded seq ${s}`;if(!(yield this.changedBetween(s,e)))return this.lastDeep.seq=e,this.lastDeep.deep}const n=this.get(e).resultPromise,r=n.then(t=>t.ok?this.loadNested(e,t.value):t);this.lastDeep={seq:e,shallow:n,deep:r};const i=yield r;return null!==this.error?this.error:(i.ok||this.setError(i),i)}))})}}class ye extends ve{constructor(e,t,s){super(e,s),this.emitMutex=t,this.externallyIdleTimer=new be,this.externallyIdle=!0,this.internallyIdleTimer=new be,this.internallyIdle=!0,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive(()=>b(this,null,function*(){yield this.emit(e)}))}registerInternalSubscription(){this.internallyIdleTimer.stop(),this.internallyIdle=!1,this.referencedByOtherStores++;let e=!0;return()=>{e&&(e=!1,this.referencedByOtherStores--,0===this.referencedByOtherStores&&this.internallyIdleTimer.restart(()=>{this.internallyIdle=!0,this.tryFullyUnsubscribe()},this.unsubscribeDebounceMs),this.tryFullyUnsubscribe())}}get onlyUsedInternally(){return 0===this.listeners.length}listen(e){this.externallyIdleTimer.stop(),this.externallyIdle=!1,this.listeners.push(e),void 0!==this.lastEmitResult&&e(this.lastEmitResult);let t=!0;return()=>{t&&(t=!1,this.listeners=this.listeners.filter(t=>t!==e),0===this.listeners.length&&this.externallyIdleTimer.restart(()=>{this.externallyIdle=!0,this.tryFullyUnsubscribe()},this.unsubscribeDebounceMs))}}tryFullyUnsubscribe(){this.externallyIdle&&this.internallyIdle&&this.setError(D("UNSUBSCRIBED"))}emit(e){return b(this,null,function*(){var t;if(this.lastEmitSeq&&this.lastEmitSeq>=e)return;if(!1===(null==(t=this.lastEmitResult)?void 0:t.ok))return;this.lastEmitSeq=e;const s=yield this.getDeep(e);s!==this.lastEmitResult&&(this.lastEmitResult=s,this.listeners.forEach(e=>e(s)))})}}class be{constructor(){this.timerId=void 0}restart(e,t){void 0!==this.timerId&&clearTimeout(this.timerId),this.timerId=setTimeout(()=>e(),t)}stop(){clearTimeout(this.timerId)}}var we,ke={};function Ce(e,t){const s=t.lastIndex;let n;const r=[];for(;null!==(n=t.exec(e));)r.push(n),""===n[0]&&(t.lastIndex+=1);return t.lastIndex=s,r}function Se(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1");return decodeURIComponent(t)}function Ie(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(we)return ke;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}we=1,Object.defineProperty(ke,"__esModule",{value:!0}),ke.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},ke.decode=function(e){return decodeURIComponent(Array.from(atob(e),t).join(""))}}(),(e=>{function t(e,t){(function(e,t){switch(t){case"undefined":return void 0===e;case String:return"string"==typeof e||e instanceof String;case Boolean:return"boolean"==typeof e||e instanceof Boolean;case Number:return"number"==typeof e||e instanceof Number;default:return e instanceof t}})(e,t)||(t.name,String(e))}e.defined=function(e){},e.has=function(e,t){e[t]},e.is=t,e.equals=function(e,t){},e.oneOf=function(e,t){t.includes(e)||JSON.stringify(t)},e.isArray=function(e,s){t(e,Array),e&&e.length>0&&t(e[0],s)},e.optional=function(e,s){void 0!==e&&t(e,s)},e.falsy=function(e){},e.never=function(e){}})(Ie||(Ie={}));const Te=Ie,xe=/^\/.*[^\\]\/[im]*$/;function Ee(e){return!!xe.test(e)&&!Me(e).test("")}function Me(e){const t=e.match(/^\/(.*[^\\])\/(.*)$/);if(!t)throw new Error(`Expected ${e} to be a (non-empty) regex`);let s=t[2]||"";return s=s.replace(/[^im]/g,"")+"g",new RegExp(t[1],s)}class Re{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:s,allowedMatches:n,forbiddenMatches:r,forbiddenWords:i,suppressLinks:a,suppressEmailAddresses:o,suppressPhoneNumbers:l,replacement:c}){if(Te.oneOf(e,["all","otherOnly","off"]),this.mode=e,this.suppressLinks=!1!==a,this.suppressEmailAddresses=!1!==o,this.suppressPhoneNumbers=!1!==l,this.allowedHostnames=t||[],this.allowedPhoneNrs=(s||[]).filter(e=>e).map(e=>e.replace(/[^0-9]/g,"")),this.allowedMatches=(n||[]).filter(Ee).map(e=>Me(e)),this.forbiddenMatches=(r||[]).filter(Ee).map(e=>Me(e)),i){const e=i.split("\n").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0&&!e.startsWith("#")).map(e=>e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1"));e.length&&this.forbiddenMatches.push(new RegExp(`\\b(${e.join("|")})\\b`,"gi"))}Te(()=>this.allowedMatches.every(e=>e.flags.includes("g")),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),Te(()=>this.forbiddenMatches.every(e=>e.flags.includes("g")),"All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"),c=null==c?void 0:c.trim(),this.replacement=c&&c.length>0?c:void 0}shouldSuppress({isContentBySender:e}){return"all"===this.mode||"otherOnly"===this.mode&&!e}}function Ae(e,t){return e.map(e=>function(e,t){if("text"===e.type)return _e(e.children,function(e){var t,s,n,r,i,a,o,l,c,u,d,h,p,f;let g="";return e.t&&(g=`(${e.t("CONTACT_INFORMATION_HIDDEN")})`),{formattedLinks:null!=(t=e.formattedLinks)?t:"plaintext",markup:null!=(s=e.markup)&&s,useFallbackMentions:null!=(n=e.useFallbackMentions)&&n,sameTabLinkRules:null!=(r=e.sameTabLinkRules)?r:[],enableEmojiImageFallback:null!=(i=e.enableEmojiImageFallback)&&i,highlight:null!=(a=e.highlight)?a:[],highlightFromWordBeginnings:null!=(o=e.highlightFromWordBeginnings)&&o,contactInfo:null!=(l=e.contactInfo)&&l,suppression:null!=(c=e.suppression)?c:new Re({mode:"off"}),contactInfoHiddenText:null!=(h=null!=(d=e.contactInfoHiddenText)?d:null==(u=e.suppression)?void 0:u.replacement)?h:g,customEmojiUrls:null!=(p=e.customEmojiUrls)?p:{},enableActions:null==(f=e.enableActions)||f}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${Se(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${Se(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${Se(e.url)}`;if("file"===e.type&&"voice"===e.subtype){const t=e.duration;return void 0===t?"🎙️":`🎙️ (${Math.floor(t/60)}:${Math.floor(t%60).toString().padStart(2,"0")})`}return"file"===e.type?(e.subtype,`📎 ${Se(e.url)}`):"location"===e.type?"📍":""}(e,t)).join("\n\n")}function _e(e,t){return e.flatMap(e=>{if("string"==typeof e)return e;switch(e.type){case"blockquote":case"bold":case"italic":case"strikethrough":case"link":case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return _e(e.children,t);case"bulletlist":case"bulletList":return"\n"+_e(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+_e(e.children,t)+"\n";case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"emoji":case"customemoji":case"customEmoji":return e.text;case"suppressed":return t.contactInfoHiddenText;case"mention":return`@${e.text}`}}).join("")}function Ne(e){return Q({id:e.id,name:e.name,custom:Q(e.custom),locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage})}function De(e,t){return Q({user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt})}function Oe(e){const t=Object.entries(e);return t.sort(([e,t],[s,n])=>{const r=t.createdAt-n.createdAt;return 0!==r?r:e.localeCompare(s)}),Q(t.map(([e,t])=>({emoji:e,count:t.count,currentUserReacted:t.currentUserReacted})))}class Pe extends ye{constructor(e,t,s,n,r){super(e,n,r),this.userId=t,this.realtimeClient=s,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return b(this,null,function*(){const t=yield this.realtimeClient.call({method:"GET",path:["users",this.userId],data:{includePrivateFields:!1},flags:{bypassCache:!0}});return t.ok?N({snapshot:Ne(t.value.data),lastChanged:e}):"server"===t.where&&404===t.value.status?N({snapshot:null,lastChanged:e}):t})}equal(e,t){return se(e.snapshot,t.snapshot)}loadNested(e,t){return b(this,null,function*(){return N(t)})}userCreated(e,t){this.mutate(e,s=>null!==s.value.snapshot?s:N({snapshot:Ne(t.state),lastChanged:e}))}userEdited(e,t){this.mutate(e,s=>{const n=s.value.snapshot;return null===n?(console.warn("[TalkJS] Received a 'used edited' event for a user that we thought didn't exist."),s):N({snapshot:{id:n.id,name:X(n.name,t.diff.name),custom:te(n.custom,t.diff.custom),locale:X(n.locale,t.diff.locale),photoUrl:X(n.photoUrl,t.diff.photoUrl),role:X(n.role,t.diff.role),welcomeMessage:X(n.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})})}getFromCache(){return b(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.snapshot?O({status:404,errorCode:"USER_NOT_FOUND",reasons:["That user does not exist yet"]}):N({status:200,data:{id:e.value.snapshot.id,name:e.value.snapshot.name,custom:e.value.snapshot.custom,locale:e.value.snapshot.locale,photoUrl:e.value.snapshot.photoUrl,role:e.value.snapshot.role,welcomeMessage:e.value.snapshot.welcomeMessage}}):D("NOT_IN_CACHE")})}teardownNested(e){}anyChildChanged(e,t,s){return b(this,null,function*(){return!1})}}class je extends ve{constructor(e,t,s,n){super(e,{}),this.conversationId=t,this.message=s,this.realtimeClient=n}get messageId(){return"string"==typeof this.message?this.message:this.message.id}fetchInitial(e){return b(this,null,function*(){let t;if("object"==typeof this.message)t=this.message;else{const e=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId,"messages",this.message],data:{},flags:{bypassCache:!0}});if(!e.ok)return e;t=e.value.data}const s=null===t.senderId?null:this.realtimeClient.internalSubscribe(["users",t.senderId]),n={};return Object.entries(t.reactions).forEach(([e,{createdAt:t}])=>{n[e]=t}),N({lastChanged:e,sender:s,data:{id:t.id,type:t.type,custom:Q(t.custom),createdAt:t.createdAt,editedAt:t.editedAt,referencedMessageId:t.referencedMessageId,origin:t.origin,plaintext:Ae(t.content,{}),content:K(t.content),reactions:Oe(t.reactions),reactionsCreatedAt:n}})})}refetch(e){throw"Do not call refetch on message data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return se(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){var n;const r=null==(n=s.sender)?void 0:n.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))})}loadNested(e,t){return b(this,null,function*(){var s,n,r;const i=yield null==(n=null==(s=t.sender)?void 0:s.store)?void 0:n.getDeep(e);if(!1===(null==i?void 0:i.ok))return i;if(null===t.data)return N({snapshot:null});const a=null==i?void 0:i.value;return N({snapshot:Q({sender:null!=(r=null==a?void 0:a.snapshot)?r:null,id:t.data.id,type:t.data.type,custom:Q(t.data.custom),createdAt:t.data.createdAt,editedAt:t.data.editedAt,origin:t.data.origin,plaintext:t.data.plaintext,content:t.data.content,referencedMessageId:t.data.referencedMessageId,reactions:t.data.reactions})})})}messageEdited(e,t){this.mutate(e,s=>{if(null===s.value.data)return s;const n=s.value.data.content,r=(i=n,void 0===(a=t.diff.content)?i:K(a));var i,a;const o=n===r?s.value.data.plaintext:Ae(r,{}),{reactions:l,reactionsCreatedAt:c}=function(e,t,s){const n=function(e,t){if(void 0===t)return e;if(null===t)return{};if(Object.values(t).every(e=>null!==e&&void 0===e.createdAt))return e;const s=h({},e);return Object.entries(t).forEach(([t,n])=>{null===n?delete s[t]:s[t]=t in e?X(e[t],n.createdAt):n.createdAt}),s}(t,s);let r=function(e,t){if(void 0===t)return e;if(null===t)return[];if(Object.values(t).every(e=>null!==e&&void 0===e.count&&void 0===e.currentUserReacted))return e;const s=e.map(e=>{const s=t[e.emoji];return void 0===s?e:Q(null===s?p(h({},e),{count:0}):{emoji:e.emoji,count:X(e.count,s.count),currentUserReacted:X(e.currentUserReacted,s.currentUserReacted)})}).filter(e=>e.count>0),n=new Set(s.map(e=>e.emoji));for(const r in t){const e=t[r];e&&!n.has(r)&&s.push(Q({emoji:r,count:e.count,currentUserReacted:e.currentUserReacted}))}return s}(e,s);return n!==t&&(r=[...r],r.sort((e,t)=>{const s=n[e.emoji]-n[t.emoji];return 0!==s?s:e.emoji.localeCompare(t.emoji)})),r=Q(r),{reactions:r,reactionsCreatedAt:n}}(s.value.data.reactions,s.value.data.reactionsCreatedAt,t.diff.reactions);return N({lastChanged:e,sender:s.value.sender,data:{id:s.value.data.id,type:s.value.data.type,createdAt:s.value.data.createdAt,origin:s.value.data.origin,referencedMessageId:s.value.data.referencedMessageId,editedAt:X(s.value.data.editedAt,t.diff.editedAt),custom:te(s.value.data.custom,t.diff.custom),plaintext:o,content:r,reactions:l,reactionsCreatedAt:c}})})}messageDeleted(e,t){this.mutate(e,s=>null===s.value.data?s:this.messageId===t.messageId?(this.teardownNested(s.value),N({lastChanged:e,sender:null,data:null})):s.value.data.referencedMessageId===t.messageId?N({lastChanged:e,sender:s.value.sender,data:{id:s.value.data.id,type:s.value.data.type,createdAt:s.value.data.createdAt,origin:s.value.data.origin,referencedMessageId:null,editedAt:s.value.data.editedAt,custom:s.value.data.custom,plaintext:s.value.data.plaintext,content:s.value.data.content,reactions:s.value.data.reactions,reactionsCreatedAt:s.value.data.reactionsCreatedAt}}):s)}getFromCache(){return b(this,null,function*(){var e;const t=yield this.mostRecentState.resultPromise;if(!t.ok)return D("NOT_IN_CACHE");if(null===t.value.data)return O({status:404,errorCode:"MESSAGE_NOT_FOUND",reasons:["No message with that ID exists"]});const s=t.value,{sender:n}=s,r=f(s,["sender"]).data,{reactions:i,reactionsCreatedAt:a}=r,o=f(r,["reactions","reactionsCreatedAt"]),l={};return i.forEach(({emoji:e,count:t,currentUserReacted:s})=>{const n=e;l[n]={count:t,createdAt:a[n],currentUserReacted:s}}),N({status:200,data:p(h({},o),{senderId:null!=(e=null==n?void 0:n.store.userId)?e:null,reactions:l})})})}}class Ue extends ve{constructor(e,t,s,n){super(e,{}),this.createdAt=t,this.dataStore=s,this.referencedDataStore=n}get messageId(){return this.dataStore.messageId}fetchInitial(e){return b(this,null,function*(){return N({lastChanged:e,dataStore:this.dataStore,referencedDataStore:this.referencedDataStore})})}refetch(e){throw"Do not call refetch on message stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return!0}teardownNested(e){}anyChildChanged(e,t,s){return b(this,arguments,function*(e,t,{dataStore:s,referencedDataStore:n}){return!0===(yield s.changedBetween(e,t))||!0===(yield null==n?void 0:n.changedBetween(e,t))})}loadNested(e,t){return b(this,null,function*(){var s,n,r;const i=yield t.dataStore.getDeep(e);if(!i.ok)return i;const a=i.value;if(null===a.snapshot)return N({snapshot:null});const o=yield null==(s=t.referencedDataStore)?void 0:s.getDeep(e);if(o&&!o.ok)return o;const l=null!=(n=null==o?void 0:o.value)?n:null,c=null!=(r=null==l?void 0:l.snapshot)?r:null;return N({snapshot:Q({id:a.snapshot.id,type:a.snapshot.type,sender:a.snapshot.sender,custom:Q(a.snapshot.custom),createdAt:a.snapshot.createdAt,editedAt:a.snapshot.editedAt,referencedMessage:c,origin:a.snapshot.origin,plaintext:a.snapshot.plaintext,content:a.snapshot.content,reactions:a.snapshot.reactions})})})}}class $e extends ye{constructor(e,t,s,n,r){super(e,n,r),this.conversationId=t,this.realtimeClient=s,this.handlers=r,this.unsubscribeDebounceMs=1e4,this.pendingLoadMore=void 0}listen(e){return this.onlyUsedInternally&&this.mostRecentState.resultPromise.then(e=>{if(e.ok&&null!==e.value.inWindow){const t=30-e.value.inWindow.length;t>0&&this.loadMore(t)}}),super.listen(e)}fetchInitial(e){return b(this,null,function*(){const t=this.onlyUsedInternally?1:30,s=yield We({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return s.ok?null===s.value.messages?N({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}):qe({seq:e,messages:s.value.messages,cursor:s.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):s})}teardownNested(e){if(e.stores){const t=D("TERMINATED");Object.values(e.stores).forEach(e=>e.setError(t)),e.inWindow.forEach(e=>e.setError(t))}}anyChildChanged(e,t,s){return b(this,null,function*(){for(const n in s.stores){const r=s.stores[n];if(!0===(yield null==r?void 0:r.changedBetween(e,t)))return!0}return!1})}lastMessageChangedBetween(e,t){return b(this,null,function*(){if(e>=t)return!1;const s=yield this.get(t).resultPromise;if(!s.ok)return!1;if(s.value.lastMessageChanged>e)return!0;if(null===s.value.stores)return!1;const n=s.value.inWindow[0];return void 0!==n&&!0===(yield n.changedBetween(e,t))})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!se(Object.keys(e.stores),Object.keys(t.stores))&&!!se(e.inWindow.map(e=>e.messageId),t.inWindow.map(e=>e.messageId))&&se(e.windowEnd,t.windowEnd)}loadNested(e,t){return b(this,null,function*(){if(null===t.stores)return N({snapshot:null,loadedAll:!0});const s=yield Promise.all(t.inWindow.map(t=>t.getDeep(e))),n=s.find(e=>!e.ok);return n||N({snapshot:Q(s.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot)),loadedAll:null===t.windowEnd})})}loadMore(e=30){return b(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=A();this.pendingLoadMore=t.promise;const s=yield this.mostRecentState.resultPromise;if(!s.ok){if("client"===s.where)throw t.reject(s.value),this.pendingLoadMore=void 0,s.value;{const e=$("Loading more messages",s.value);throw t.reject(s.value),this.pendingLoadMore=void 0,e}}if(null===s.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const n=s.value.windowEnd.cursor,r=yield We({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.messages.loadedMore",conversationId:this.conversationId,data:r})})}loadedMore(e,t){this.mutate(e,s=>null===s.value.windowEnd?s:t.data.ok?null===t.data.value.messages?(console.warn("[TalkJS] When loading more messages, the conversation no longer existed. We should have been told about this."),s):qe({seq:e,prevState:s.value,messages:t.data.value.messages,cursor:t.data.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):t.data)}messageCreated(e,t){this.mutate(e,s=>{if(null===s.value.stores)return console.warn("[TalkJS] Received a 'message.created' event for a nonexistent conversation."),s;if(s.value.windowEnd&&t.state.createdAt<s.value.windowEnd.oldestMessageTs)return s;if(Object.hasOwnProperty.call(s.value.stores,t.state.id))return s;const n=h({},s.value.stores),r=new je(e,this.conversationId,t.state,this.realtimeClient);n[t.state.id]=r;const i=t.state.referencedMessageId;let a;null===i?a=null:i in n?a=n[i]:(a=new je(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new Ue(e,t.state.createdAt,r,a),l=[...s.value.inWindow,o];l.sort((e,t)=>t.createdAt-e.createdAt);const c=l[0].messageId===t.messageId?e:s.value.lastMessageChanged;return N({lastChanged:e,lastMessageChanged:c,stores:n,inWindow:l,windowEnd:s.value.windowEnd})})}messageEdited(e,t){this.mutate(e,s=>{var n;return null===s.value.stores?(console.warn("[TalkJS] Received a 'message.edited' event for a nonexistent conversation."),s):(null==(n=s.value.stores[t.messageId])||n.messageEdited(e,t),s)})}messageDeleted(e,t){this.mutate(e,s=>{if(null===s.value.stores)return console.warn("[TalkJS] Received a 'message.deleted' event for a conversation that we thought didn't exist."),s;if(Object.values(s.value.stores).forEach(s=>s.messageDeleted(e,t)),void 0===s.value.stores[t.messageId])return s;const n=h({},s.value.stores);delete n[t.messageId];const r=s.value.inWindow.filter(e=>e.messageId!==t.messageId);if(t.newLastMessage&&0===r.length){const s=new je(e,this.conversationId,t.newLastMessage,this.realtimeClient);n[s.messageId]=s;const i=t.newLastMessage.referencedMessageId;let a;null===i?a=null:i in n?a=n[i]:(a=new je(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new Ue(e,t.newLastMessage.createdAt,s,a);r.push(o)}const i=void 0!==t.newLastMessage?e:s.value.lastMessageChanged;return N({lastChanged:e,lastMessageChanged:i,stores:n,inWindow:r,windowEnd:s.value.windowEnd})})}conversationCleared(e,t){this.mutate(e,t=>{var s;return 0===(null==(s=t.value.inWindow)?void 0:s.length)&&null===t.value.windowEnd?t:(this.teardownNested(t.value),N({lastChanged:e,lastMessageChanged:e,stores:{},inWindow:[],windowEnd:null}))})}sideCreated(e,t){const s=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.stores?(s.then(e=>{e.ok&&this.teardownNested(e.value)}),e):s)}sideDeleted(e,t){this.mutate(e,t=>null===t.value.stores?t:(this.teardownNested(t.value),N({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null})))}getMessageFromCache(e){return b(this,null,function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return D("NOT_IN_CACHE");if(null===t.value.stores)return D("NOT_IN_CACHE");const s=t.value.stores[e];return void 0===s?D("NOT_IN_CACHE"):s.getFromCache()})}}function We(e){return b(this,arguments,function*({cursor:e,realtimeClient:t,conversationId:s,count:n}){const r={limit:n,cursor:e},i=yield t.call({method:"GET",path:["me","conversations",s,"messages"],data:r,flags:{bypassCache:!0}});if(i.ok){const{data:e,cursor:t}=i.value.data;return N({messages:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?N({messages:null,nextCursor:null}):i})}function qe({seq:e,prevState:t,messages:s,cursor:n,conversationId:r,realtimeClient:i}){var a,o,l,c;const u=t?h({},t.stores):{};for(const h of s)if(void 0===u[h.id]){const t=new je(e,r,h,i);u[t.messageId]=t}for(const h of s){const t=h.referencedMessageId;if(t&&void 0===u[t]){const s=new je(e,r,t,i);u[s.messageId]=s}}const d=t?[...t.inWindow]:[];for(const h of s)d.push(new Ue(e,h.createdAt,u[h.id],h.referencedMessageId?u[h.referencedMessageId]:null));d.sort((e,t)=>t.createdAt-e.createdAt);const p=(null==(o=null==(a=null==t?void 0:t.inWindow)?void 0:a[0])?void 0:o.messageId)===(null==(l=null==d?void 0:d[0])?void 0:l.messageId)&&null!=(c=null==t?void 0:t.lastMessageChanged)?c:e;return N(null===n?{lastChanged:e,lastMessageChanged:p,stores:u,inWindow:d,windowEnd:null}:{lastChanged:e,lastMessageChanged:p,stores:u,inWindow:d,windowEnd:{cursor:n,oldestMessageTs:s[s.length-1].createdAt}})}class Le extends ye{constructor(e,t,s,n,r){super(e,n,r),this.convData=t,this.realtimeClient=s,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return b(this,null,function*(){return N({lastChanged:e,convData:this.convData})})}teardownNested(e){e.convData.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){return s.convData.store.changedBetween(e,t)})}equal(e,t){return!0}loadNested(e,t){return b(this,null,function*(){return t.convData.store.getDeep(e)})}getFromCache(){return b(this,null,function*(){return this.convData.store.getFromCache()})}}function Be(e,t){for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t(e[s],s)}function Ge(e,t){return function(e){let s={};return Be(e,(e,n)=>{const[r,i]=(([e,s])=>[e,t(s,e)])([n,e],0);s[r]=i}),s}(e)}class Fe extends ye{constructor(e,t,s,n,r){super(e,n,r),this.conversationId=t,this.realtimeClient=s,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return b(this,null,function*(){const t=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId,"typing"],data:{},flags:{bypassCache:!0}});if(!t.ok&&"server"===t.where&&404===t.value.status)return N({data:null,lastChanged:e});if(!t.ok&&"server"===t.where&&403===t.value.status&&"NOT_A_PARTICIPANT"===t.value.errorCode)return N({data:null,lastChanged:e});if(!t.ok)return t;const s=t.value.data;return s.many?N({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e}):N({data:s,userSubscriptions:Ge(s.usersTyping,(e,t)=>this.realtimeClient.internalSubscribe(["users",t])),lastChanged:e})})}equal(e,t){return se(e.data,t.data)}loadNested(e,t){return b(this,null,function*(){if(null===t.data)return N({snapshot:null,lastChanged:t.lastChanged});if(t.data.many)return N({snapshot:Q({many:!0}),lastChanged:t.lastChanged});const s=Object.entries(t.data.usersTyping).sort(([e,t],[s,n])=>t-n).map(([e,t])=>e).map(s=>t.userSubscriptions[s].store.getDeep(e)),n=yield Promise.all(s),r=n.find(e=>!e.ok);if(r)return r;const i=n.map(e=>e.value),a=i.map(e=>e.snapshot),o=i.map(e=>e.lastChanged),l=Math.max(t.lastChanged,...o);return N({snapshot:Q({users:Q(a),many:!1}),lastChanged:l})})}typingAvailable(e,t){this.mutate(e,()=>N({data:t.state,userSubscriptions:t.state.many?{}:Ge(t.state.usersTyping,(e,t)=>this.realtimeClient.internalSubscribe(["users",t])),lastChanged:e}))}typingChanged(e,t){this.mutate(e,s=>{if(null===s.value.data)return s;if(void 0===t.diff.many){if(!0===s.value.data.many)return s;const n=h({},s.value.data.usersTyping),r=h({},s.value.userSubscriptions);return Be(t.diff.usersTyping,(e,t)=>{var s;"number"==typeof e?(n[t]=e,r[t]=this.realtimeClient.internalSubscribe(["users",t])):null===e&&(delete n[t],null==(s=r[t])||s.unsubscribe(),delete r[t])}),N({data:{usersTyping:n,many:!1},userSubscriptions:r,lastChanged:e})}if(!0===t.diff.many)return s.value.data.many?s:N({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e});if(!1===t.diff.many){if(!1===s.value.data.many)return s;const n=Ge(t.diff.usersTyping,(e,t)=>this.realtimeClient.internalSubscribe(["users",t]));return N({data:t.diff,userSubscriptions:n,lastChanged:e})}throw t.diff,"Unreachable"})}sideDeleted(e,t){this.mutate(e,t=>null===t.value.data?t:N({data:null,lastChanged:e}))}teardownNested(e){e.data&&Be(e.userSubscriptions,e=>e.unsubscribe())}anyChildChanged(e,t,s){return b(this,null,function*(){var n;if(null===s.data)return!1;for(const r in s.userSubscriptions){const i=s.userSubscriptions[r];if(!0===(yield null==(n=null==i?void 0:i.store)?void 0:n.changedBetween(e,t)))return!0}return!1})}}class He extends ye{constructor(e,t,s,n,r,i){super(e,r,i),this.conversationId=t,this.participant=s,this.realtimeClient=n,this.unsubscribeDebounceMs=0}get userId(){return"string"==typeof this.participant?this.participant:this.participant.id}fetchInitial(e){return b(this,null,function*(){const t=this.realtimeClient.internalSubscribe(["users",this.userId]);if("object"==typeof this.participant)return N({lastChanged:e,user:t,data:this.participant});const s=yield ze(this.conversationId,this.userId,this.realtimeClient);return s.ok?N({lastChanged:e,user:t,data:s.value}):(t.unsubscribe(),s)})}refetch(e){throw"Do not call refetch on participant data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){var s,n,r,i;return(null==(n=null==(s=e.user)?void 0:s.store)?void 0:n.userId)===(null==(i=null==(r=t.user)?void 0:r.store)?void 0:i.userId)&&se(e.data,t.data)}teardownNested(e){e.user.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){var n;if(null===s.data)return!1;const r=null==(n=s.user)?void 0:n.store;return!0===(yield null==r?void 0:r.changedBetween(e,t))})}loadNested(e,t){return b(this,null,function*(){if(null===t.data)return N({snapshot:null});const s=yield t.user.store.getDeep(e);if(!1===s.ok)return s;const n=s.value.snapshot;return N({snapshot:De(t.data,n)})})}participantCreated(e,t){this.mutate(e,s=>null!==s.value.data?s:N({lastChanged:e,user:s.value.user,data:t.state}))}participantEdited(e,t){this.mutate(e,s=>null===s.value.data?s:N({lastChanged:e,user:s.value.user,data:{id:s.value.data.id,access:X(s.value.data.access,t.diff.access),notify:X(s.value.data.notify,t.diff.notify),joinedAt:s.value.data.joinedAt}}))}participantDeleted(e,t){this.mutate(e,t=>null===t.value.data?t:N({lastChanged:e,user:t.value.user,data:null}))}sideCreated(e,t){const s=ze(this.conversationId,this.userId,this.realtimeClient);this.mutate(e,t=>b(this,null,function*(){if(null!==t.value.data)return t;const n=yield s;return n.ok?N({lastChanged:e,user:t.value.user,data:n.value}):(this.teardownNested(t.value),n)}))}sideDeleted(e,t){this.mutate(e,t=>null===t.value.data?t:N({lastChanged:e,user:t.value.user,data:null}))}getFromCache(){return b(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.data?O({status:404,errorCode:"PARTICIPANT_NOT_FOUND",reasons:["No participant with that ID exists"]}):N({status:200,data:e.value.data}):D("NOT_IN_CACHE")})}}function ze(e,t,s){return b(this,null,function*(){const n=yield s.call({method:"GET",path:["me","conversations",e,"participants",t],data:{},flags:{bypassCache:!0}});return n.ok?N(n.value.data):"server"===n.where&&404===n.value.status||"server"===n.where&&403===n.value.status&&"NOT_A_PARTICIPANT"===n.value.errorCode?N(null):n})}class Je extends ye{constructor(e,t,s,n,r,i){super(e,r,i),this.getParticipantDataStore=t,this.conversationId=s,this.realtimeClient=n,this.handlers=i,this.unsubscribeDebounceMs=3e4,this.pendingLoadMore=void 0}fetchInitial(e){return b(this,null,function*(){const t=yield Ye({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:10});return t.ok?null===t.value.participants?N({lastChanged:e,stores:null,windowEnd:null}):Ve({seq:e,participants:t.value.participants,cursor:t.value.nextCursor,getParticipantDataStore:this.getParticipantDataStore}):t})}teardownNested(e){null!==e.stores&&Object.values(e.stores).forEach(e=>e.unsubscribe())}anyChildChanged(e,t,s){return b(this,null,function*(){var n;for(const r in s.stores){const i=s.stores[r];if(!0===(yield null==(n=null==i?void 0:i.store)?void 0:n.changedBetween(e,t)))return!0}return!1})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!se(Object.keys(e.stores),Object.keys(t.stores))&&se(e.windowEnd,t.windowEnd)}loadNested(e,t){return b(this,null,function*(){if(null===t.stores)return N({snapshot:null,loadedAll:!0});const s=yield Promise.all(Object.values(t.stores).map(t=>t.store.getDeep(e))),n=s.find(e=>!e.ok);if(n)return n;const r=s.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot);return r.sort((e,t)=>t.joinedAt-e.joinedAt),N({snapshot:Q(r),loadedAll:null===t.windowEnd})})}loadMore(e=10){return b(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=A();this.pendingLoadMore=t.promise;const s=yield this.mostRecentState.resultPromise;if(!s.ok){if("client"===s.where)throw t.reject(s.value),this.pendingLoadMore=void 0,s.value;{const e=$("Loading more participants",s.value);throw t.reject(e),this.pendingLoadMore=void 0,e}}if(null===s.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const n=s.value.windowEnd.cursor,r=yield Ye({count:e,cursor:n,conversationId:this.conversationId,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.participants.loadedMore",conversationId:this.conversationId,data:r})})}loadedMore(e,t){this.mutate(e,s=>null===s.value.windowEnd?s:t.data.ok?null===t.data.value.participants?(console.warn("[TalkJS] When loading more participants, the conversation no longer existed. We should have been told about this."),s):Ve({seq:e,prevStores:s.value.stores,participants:t.data.value.participants,cursor:t.data.value.nextCursor,getParticipantDataStore:this.getParticipantDataStore}):t.data)}participantCreated(e,t){const s=this.getParticipantDataStore(t.state);this.mutate(e,n=>{let r=n.value.stores;return null===r&&(console.warn("[TalkJS] Received a 'participant.created' event when we thought the conversation didn't exist."),r={}),Object.hasOwnProperty.call(r,t.userId)?(s.unsubscribe(),n):N({lastChanged:e,stores:p(h({},r),{[t.userId]:s}),windowEnd:n.value.windowEnd})})}participantDeleted(e,t){this.mutate(e,s=>{var n;if(!Object.hasOwnProperty.call(s.value.stores,t.userId))return s;const r=h({},s.value.stores);return null==(n=r[t.userId])||n.unsubscribe(),delete r[t.userId],N({lastChanged:e,stores:r,windowEnd:s.value.windowEnd})})}sideCreated(e,t){const s=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.stores?(s.then(e=>{e.ok&&this.teardownNested(e.value)}),e):s)}sideDeleted(e,t){this.mutate(e,t=>null===t.value.stores?t:(this.teardownNested(t.value),N({lastChanged:e,stores:null,windowEnd:null})))}}function Ye(e){return b(this,arguments,function*({cursor:e,realtimeClient:t,conversationId:s,count:n}){const r={limit:n,cursor:e},i=yield t.call({method:"GET",path:["me","conversations",s,"participants"],data:r,flags:{bypassCache:!0}});if(i.ok){const{data:e,cursor:t}=i.value.data;return N({participants:e,nextCursor:t})}return!i.ok&&"server"===i.where&&404===i.value.status||!i.ok&&"server"===i.where&&403===i.value.status&&"NOT_A_PARTICIPANT"===i.value.errorCode?N({participants:null,nextCursor:null}):i})}function Ve({seq:e,prevStores:t,participants:s,cursor:n,getParticipantDataStore:r}){const i=t?h({},t):{};for(const a of s)void 0===i[a.id]&&(i[a.id]=r(a));return N(null===n?{lastChanged:e,stores:i,windowEnd:null}:{lastChanged:e,stores:i,windowEnd:{cursor:n,oldestParticipantTs:s[s.length-1].joinedAt}})}class Qe extends ye{constructor(e,t,s,n,r){super(e,n,r),this.getConvDataStore=t,this.realtimeClient=s,this.handlers=r,this.unsubscribeDebounceMs=1e4,this.pendingLoadMore=void 0}fetchInitial(e){return b(this,null,function*(){const t=yield Ke({realtimeClient:this.realtimeClient,count:20});return t.ok?null===t.value.conversations?N({lastChanged:e,stores:null,windowEnd:null}):Ze({seq:e,conversations:t.value.conversations,cursor:t.value.nextCursor,getConvDataStore:this.getConvDataStore}):t})}teardownNested(e){null!==e.stores&&Object.values(e.stores).forEach(e=>e.unsubscribe())}anyChildChanged(e,t,s){return b(this,null,function*(){var n;for(const r in s.stores){const i=s.stores[r];if(!0===(yield null==(n=null==i?void 0:i.store)?void 0:n.changedBetween(e,t)))return!0}return!1})}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!se(Object.keys(e.stores),Object.keys(t.stores))&&se(e.windowEnd,t.windowEnd)}loadNested(e,t){return b(this,null,function*(){if(null===t.stores)return N({snapshot:Q([]),loadedAll:!0});const s=yield Promise.all(Object.values(t.stores).map(t=>t.store.getDeep(e))),n=s.find(e=>!e.ok);if(n)return n;const r=s.filter(e=>null!==e.value.snapshot).map(e=>e.value.snapshot);return r.sort((e,t)=>{var s,n,r,i;const a=null!=(n=null==(s=e.lastMessage)?void 0:s.createdAt)?n:e.joinedAt;return(null!=(i=null==(r=t.lastMessage)?void 0:r.createdAt)?i:t.joinedAt)-a}),N({snapshot:Q(r),loadedAll:null===t.windowEnd})})}loadMore(e=20){return b(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=A();this.pendingLoadMore=t.promise;const s=yield this.mostRecentState.resultPromise;if(!s.ok){if("client"===s.where)throw t.reject(s.value),this.pendingLoadMore=void 0,s.value;{const e=$("Loading more conversations",s.value);throw t.reject(e),this.pendingLoadMore=void 0,e}}if(null===s.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const n=s.value.windowEnd.cursor,r=yield Ke({count:e,cursor:n,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.conversations.loadedMore",data:r})})}loadedMore(e,t){this.mutate(e,s=>null===s.value.windowEnd?s:t.data.ok?null===t.data.value.conversations?(console.warn("[TalkJS] When loading more conversations, the user stopped existing, which should be impossible."),s):Ze({seq:e,prevStores:s.value.stores,conversations:t.data.value.conversations,cursor:t.data.value.nextCursor,getConvDataStore:this.getConvDataStore}):t.data)}userCreated(e,t){this.mutate(e,e=>null!==e.value.stores?e:N({lastChanged:e.value.lastChanged,stores:{},windowEnd:null}))}sideCreated(e,t){const s=this.getConvDataStore(t.state);this.mutate(e,n=>{let r=n.value.stores;return null===r&&(console.warn("[TalkJS] Received a 'side.created' event when we thought your user didn't exist."),r={}),Object.hasOwnProperty.call(r,t.conversationId)?(s.unsubscribe(),n):N({lastChanged:e,stores:p(h({},r),{[t.conversationId]:s}),windowEnd:n.value.windowEnd})})}sideDeleted(e,t){this.mutate(e,s=>{var n;if(!Object.hasOwnProperty.call(s.value.stores,t.conversationId))return s;const r=h({},s.value.stores);return null==(n=r[t.conversationId])||n.unsubscribe(),delete r[t.conversationId],N({lastChanged:e,stores:r,windowEnd:s.value.windowEnd})})}sideEdited(e,t){const s=t.diff.lastMessageAt;void 0!==s&&this.mutate(e,n=>{var r;if(null===n.value.stores)return console.warn("[TalkJS] Received a 'side.edited' event when we thought your user didn't exist."),n;if(null===n.value.windowEnd)return n;const i=Object.hasOwnProperty.call(n.value.stores,t.conversationId);if(i&&s<n.value.windowEnd.oldestMessageTs){const s=h({},n.value.stores);return null==(r=s[t.conversationId])||r.unsubscribe(),delete s[t.conversationId],N({lastChanged:e,stores:s,windowEnd:n.value.windowEnd})}if(!i&&s>=n.value.windowEnd.oldestMessageTs){const s=this.getConvDataStore(t.conversationId);return N({lastChanged:e,stores:p(h({},n.value.stores),{[t.conversationId]:s}),windowEnd:n.value.windowEnd})}return n})}}function Ke(e){return b(this,arguments,function*({cursor:e,realtimeClient:t,count:s}){const n={limit:s,cursor:e},r=yield t.call({method:"GET",path:["me","conversations"],data:n,flags:{bypassCache:!0}});if(r.ok){const{data:e,cursor:t}=r.value.data;return N({conversations:e,nextCursor:t})}return r.ok||"server"!==r.where||404!==r.value.status||"USER_NOT_FOUND"!==r.value.errorCode?r:N({conversations:null,nextCursor:null})})}function Ze({seq:e,prevStores:t,conversations:s,cursor:n,getConvDataStore:r}){const i=t?h({},t):{};for(const a of s)void 0===i[a.id]&&(i[a.id]=r(a));return N(null===n?{lastChanged:e,stores:i,windowEnd:null}:{lastChanged:e,stores:i,windowEnd:{cursor:n,oldestMessageTs:Math.min(...s.map(e=>e.lastMessageAt))}})}class Xe extends ye{constructor(e,t,s,n,r){super(e,n,r),this.conversation=t,this.realtimeClient=s,this.unsubscribeDebounceMs=0}get conversationId(){return"string"==typeof this.conversation?this.conversation:this.conversation.id}fetchInitial(e){return b(this,null,function*(){const t=this.realtimeClient.internalSubscribe(["me","conversations",this.conversationId,"messages"]);if("object"==typeof this.conversation)return N({lastChanged:e,snapshot:this.conversation,messageWindow:t});const s=yield this.realtimeClient.call({method:"GET",path:["me","conversations",this.conversationId],data:{},flags:{bypassCache:!0}});let n;if(s.ok)n=s.value.data;else if("server"===s.where&&404===s.value.status)n=null;else{if("server"!==s.where||403!==s.value.status||"NOT_A_PARTICIPANT"!==s.value.errorCode)return t.unsubscribe(),s;n=null}return N({lastChanged:e,snapshot:n,messageWindow:t})})}teardownNested(e){var t;null==(t=e.messageWindow)||t.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){return!0===(yield s.messageWindow.store.lastMessageChangedBetween(e,t))})}refetch(e){throw"Do not call refetch on conversation data stores, it can return outdated data. Destroy and remake them instead"}equal(e,t){return se(e.snapshot,t.snapshot)}loadNested(e,t){return b(this,null,function*(){var s;if(!t.snapshot)return N({snapshot:null,loadedAll:!0});const n=yield t.messageWindow.store.getDeep(e);if(!n.ok)return n;const r=n.value.snapshot,i=null!=(s=null==r?void 0:r[0])?s:null;return N({snapshot:Q(p(h({},t.snapshot),{custom:Q(t.snapshot.custom),welcomeMessages:Q(t.snapshot.welcomeMessages),lastMessage:i}))})})}participantEdited(e,t){this.mutate(e,s=>null===s.value.snapshot?(console.warn("[TalkJS] Received a 'participant.edited' event for a conversation that we thought didn't exist."),s):N({lastChanged:e,snapshot:et(s.value.snapshot,t.diff),messageWindow:s.value.messageWindow}))}conversationEdited(e,t){this.mutate(e,s=>null===s.value.snapshot?(console.warn("[TalkJS] Received a 'conversation.edited' event for a conversation that we thought didn't exist."),s):N({lastChanged:e,snapshot:et(s.value.snapshot,t.diff),messageWindow:s.value.messageWindow}))}sideEdited(e,t){this.mutate(e,s=>null===s.value.snapshot?(console.warn("[TalkJS] Received a 'side.edited' event for a conversation that we thought didn't exist."),s):N({lastChanged:e,snapshot:et(s.value.snapshot,t.diff),messageWindow:s.value.messageWindow}))}sideCreated(e,t){this.mutate(e,s=>s.value.snapshot?s:N({lastChanged:e,snapshot:t.state,messageWindow:s.value.messageWindow}))}sideDeleted(e,t){this.mutate(e,t=>null===t.value.snapshot?t:N({lastChanged:e,snapshot:null,messageWindow:t.value.messageWindow}))}getFromCache(){return b(this,null,function*(){const e=yield this.mostRecentState.resultPromise;return e.ok&&e.value.snapshot?N({status:200,data:e.value.snapshot}):D("NOT_IN_CACHE")})}}function et(e,t){const s=t;return{id:e.id,createdAt:e.createdAt,subject:X(e.subject,s.subject),photoUrl:X(e.photoUrl,s.photoUrl),welcomeMessages:ee(e.welcomeMessages,s.welcomeMessages),custom:te(e.custom,s.custom),lastMessageAt:X(e.lastMessageAt,s.lastMessageAt),unreadMessageCount:X(e.unreadMessageCount,s.unreadMessageCount),isUnread:X(e.isUnread,s.isUnread),access:X(e.access,s.access),notify:X(e.notify,s.notify),readUntil:X(e.readUntil,s.readUntil),everyoneReadUntil:X(e.everyoneReadUntil,s.everyoneReadUntil),joinedAt:e.joinedAt}}class tt extends ye{constructor(e,t,s,n,r){super(e,n,r),this.userId=t,this.realtimeClient=s,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return b(this,null,function*(){const t=this.realtimeClient.internalSubscribe(["users",this.userId]),s=yield this.realtimeClient.call({method:"GET",path:["users",this.userId,"online"],data:{},flags:{bypassCache:!0}});return s.ok||"server"!==s.where||404!==s.value.status||"USER_NOT_FOUND"!==s.value.errorCode?s.ok?N({lastChanged:e,user:t,data:s.value.data}):s:N({lastChanged:e,user:t,data:null})})}equal(e,t){return se(e.data,t.data)}teardownNested(e){e.user.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){return s.user.store.changedBetween(e,t)})}loadNested(e,t){return b(this,null,function*(){const s=yield t.user.store.getDeep(e);if(!s.ok)return s;const n=s.value.snapshot;return null===t.data||null===n?N({snapshot:null}):N({snapshot:Q(p(h({},t.data),{user:n}))})})}userCreated(e,t){const s=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.data?(s.then(e=>{e.ok&&this.teardownNested(e.value)}),e):s)}userOnlineChanged(e,t){this.mutate(e,s=>null===s.value.data?s:N({lastChanged:e,user:s.value.user,data:t.diff}))}getFromCache(){return b(this,null,function*(){const e=yield this.mostRecentState.resultPromise;if(!e.ok)return D("NOT_IN_CACHE");if(null===e.value.data)return O({status:404,errorCode:"USER_NOT_FOUND",reasons:["No user with that ID exists"]});const t=e.value,{user:s}=t,n=f(t,["user"]);return N({status:200,data:h({},n.data)})})}}class st extends ye{constructor(e,t,s,n,r){super(e,n,r),this.participantData=t,this.realtimeClient=s,this.unsubscribeDebounceMs=3e4}fetchInitial(e){return b(this,null,function*(){return N({lastChanged:e,participantData:this.participantData})})}teardownNested(e){e.participantData.unsubscribe()}anyChildChanged(e,t,s){return b(this,null,function*(){return s.participantData.store.changedBetween(e,t)})}equal(e,t){return!0}loadNested(e,t){return b(this,null,function*(){return t.participantData.store.getDeep(e)})}}class nt extends ye{constructor(e,t,s,n,r,i,a){super(e,i,a),this.conversationId=t,this.messageId=s,this.emoji=n,this.realtimeClient=r,this.handlers=a,this.unsubscribeDebounceMs=1e4,this.pendingLoadMore=void 0}fetchInitial(e){return b(this,null,function*(){const t=yield rt({realtimeClient:this.realtimeClient,conversationId:this.conversationId,messageId:this.messageId,emoji:this.emoji,count:30});return t.ok?null===t.value.reactions?N({lastChanged:e,reactions:null,windowEnd:null}):it({seq:e,reactions:t.value.reactions,cursor:t.value.nextCursor,realtimeClient:this.realtimeClient}):t})}teardownNested(e){null!==e.reactions&&Object.values(e.reactions).forEach(({user:e})=>e.unsubscribe())}anyChildChanged(e,t,s){return b(this,null,function*(){var n,r;for(const i in s.reactions){const a=s.reactions[i];if(!0===(yield null==(r=null==(n=null==a?void 0:a.user)?void 0:n.store)?void 0:r.changedBetween(e,t)))return!0}return!1})}equal(e,t){if(null===e.reactions&&null===t.reactions)return!0;if(null===e.reactions||null===t.reactions)return!1;if(!se(Object.keys(e.reactions),Object.keys(t.reactions)))return!1;if(!se(e.windowEnd,t.windowEnd))return!1;for(const s in e.reactions){const n=s;if(e.reactions[n].createdAt!==t.reactions[n].createdAt)return!1}return!0}loadNested(e,t){return b(this,null,function*(){if(null===t.reactions)return N({snapshot:null,loadedAll:!0});const s=yield Promise.all(Object.values(t.reactions).map(t=>t.user.store.getDeep(e).then(e=>({user:e,createdAt:t.createdAt})))),n=s.find(e=>!e.user.ok);if(n)return n.user;const r=s.filter(e=>null!==e.user.value.snapshot).map(e=>({user:e.user.value.snapshot,createdAt:e.createdAt})).map(e=>Q(e));return r.sort((e,t)=>e.createdAt-t.createdAt),N({snapshot:Q(r),loadedAll:null===t.windowEnd})})}loadMore(e=30){return b(this,null,function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=A();this.pendingLoadMore=t.promise;const s=yield this.mostRecentState.resultPromise;if(!s.ok){if("client"===s.where)throw t.reject(s.value),this.pendingLoadMore=void 0,s.value;{const e=$("Loading more user reactions",s.value);throw t.reject(e),this.pendingLoadMore=void 0,e}}if(null===s.value.windowEnd)return t.resolve(),void(this.pendingLoadMore=void 0);const n=s.value.windowEnd.cursor,r=yield rt({count:e,cursor:n,conversationId:this.conversationId,messageId:this.messageId,emoji:this.emoji,realtimeClient:this.realtimeClient});t.resolve(),this.pendingLoadMore=void 0,yield this.handlers.onLoadedMore({type:"virtual.reactions.loadedMore",conversationId:this.conversationId,messageId:this.messageId,emoji:this.emoji,data:r})})}loadedMore(e,t){this.mutate(e,s=>null===s.value.windowEnd?s:t.data.ok?null===t.data.value.reactions?(console.warn("[TalkJS] When loading more user reactions, the message was no longer visible. We should have been told about this."),s):it({seq:e,prevReactions:s.value.reactions,reactions:t.data.value.reactions,cursor:t.data.value.nextCursor,realtimeClient:this.realtimeClient}):t.data)}reactionAdded(e,t){const s=this.realtimeClient.internalSubscribe(["users",t.userId]);this.mutate(e,n=>{let r=n.value.reactions;return null===r&&(console.warn("[TalkJS] Received a 'reaction.added' event when we thought the message didn't exist."),r={}),Object.hasOwnProperty.call(r,t.userId)?(s.unsubscribe(),n):N({lastChanged:e,reactions:p(h({},r),{[t.userId]:{user:s,createdAt:t.createdAt}}),windowEnd:n.value.windowEnd})})}reactionRemoved(e,t){this.mutate(e,s=>{var n,r;if(!Object.hasOwnProperty.call(s.value.reactions,t.userId))return s;const i=h({},s.value.reactions);return null==(r=null==(n=i[t.userId])?void 0:n.user)||r.unsubscribe(),delete i[t.userId],N({lastChanged:e,reactions:i,windowEnd:s.value.windowEnd})})}sideOrMessageCreated(e,t){const s=this.fetchInitial(e);this.mutate(e,e=>null!==e.value.reactions?(s.then(e=>{e.ok&&this.teardownNested(e.value)}),e):s)}sideOrMessageDeleted(e,t){this.mutate(e,t=>null===t.value.reactions?t:(this.teardownNested(t.value),N({lastChanged:e,reactions:null,windowEnd:null})))}}function rt(e){return b(this,arguments,function*({cursor:e,realtimeClient:t,conversationId:s,messageId:n,emoji:r,count:i}){const a={limit:i,cursor:e},o=yield t.call({method:"GET",path:["me","conversations",s,"messages",n,"reactions",r],data:a,flags:{bypassCache:!0}});if(o.ok){const{data:e,cursor:t}=o.value.data;return N({reactions:e,nextCursor:t})}return!o.ok&&"server"===o.where&&404===o.value.status||!o.ok&&"server"===o.where&&403===o.value.status&&"NOT_A_PARTICIPANT"===o.value.errorCode?N({reactions:null,nextCursor:null}):o})}function it({seq:e,prevReactions:t,reactions:s,cursor:n,realtimeClient:r}){const i=t?h({},t):{};for(const a of s)void 0===i[a.userId]&&(i[a.userId]={user:r.internalSubscribe(["users",a.userId]),createdAt:a.createdAt});return N(null===n?{lastChanged:e,reactions:i,windowEnd:null}:{lastChanged:e,reactions:i,windowEnd:{cursor:n,maxCreatedAt:s[s.length-1].createdAt}})}class at{constructor(){this.children=new Map}}class ot{constructor(){this.root=new at}set(e,t){this._set(e,t)}setVirtual(e,t){this._set(e,t)}_set(e,t){let s=this.root;for(const n of e)s.children.has(n)||s.children.set(n,new at),s=s.children.get(n);s.value=t}delete(...e){return this._delete(this.root,e,0)}deleteVirtual(...e){return this._delete(this.root,e,0)}_delete(e,t,s){if(s===t.length)return void 0!==e.value&&(e.value=void 0,!0);const n=t[s],r=e.children.get(n);if(!r)return!1;const i=this._delete(r,t,s+1);return i&&void 0===r.value&&0===r.children.size&&e.children.delete(n),i}get(...e){return this._get(e)}getVirtual(...e){return this._get(e)}_get(e){let t=this.root;for(const s of e){const e=t.children.get(s);if(!e)return;t=e}return t.value}list(...e){const t=[];return this._list(this.root,e,0,t),t}listVirtual(...e){const t=[];return this._list(this.root,e,0,t),t}_list(e,t,s,n){if(s===t.length)return void(void 0!==e.value&&n.push(e.value));const r=t[s];if(r===w)for(const i of e.children.values())this._list(i,t,s+1,n);else{const i=e.children.get(r);i&&this._list(i,t,s+1,n)}}forEach(e){this._forEach(this.root,e)}_forEach(e,t){void 0!==e.value&&t(e.value);for(const s of e.children.values())this._forEach(s,t)}}class lt{constructor(e,t,s){this.realtimeClient=s,this.storeRegistry=new ot,this.emitMutex=new fe,this.virtualSeqOffset=0,this.realPublishSeq=0,this.refetchOnNextNetworkLoss=!0,this.connection=new pe(e,t,{onUpstreamRestarting:()=>{this.refetchOnNextNetworkLoss=!1},onReady:()=>{this.refetchOnNextNetworkLoss=!0},onResubscribeSent:()=>{if(this.virtualSeqOffset+=this.realPublishSeq,this.realPublishSeq=0,this.refetchOnNextNetworkLoss){this.virtualSeqOffset++;const e=this.virtualSeq;this.refetchAll(e),this.emitAll(e)}},onResubscribeError:(e,t)=>{var s;null==(s=this.storeRegistry.get(...e))||s.setError(t)},onPublish:(e,t)=>{this.realPublishSeq=e;const s=this.virtualSeq;for(const n of t)this.handlePublish(s,n);this.emitAll(s)}})}get virtualSeq(){return this.realPublishSeq+this.virtualSeqOffset}sync(){return b(this,null,function*(){yield this.connection.sync(),yield this.emitMutex.sync()})}refetchAll(e){this.storeRegistry.forEach(t=>{t instanceof He||t instanceof Xe||t.refetch(e)})}emitAll(e){return this.emitMutex.runExclusive(()=>b(this,null,function*(){const t=[];this.storeRegistry.forEach(s=>t.push(s.emit(e))),yield Promise.all(t)}))}handlePublish(e,t){var s,n,r,i,a,o,l,c,u,d,h,p,f,g,m,v,y,b,w,k,T,x,E,M,R,A,_,N,D,O,P,j,U,$,W,q,L,B;switch(t.type){case"user.created":return null==(s=this.storeRegistry.get("users",t.userId))||s.userCreated(e,t),null==(n=this.storeRegistry.get("me","conversations"))||n.userCreated(e,t),void(null==(r=this.storeRegistry.get("users",t.userId,"online"))||r.userCreated(e,t));case"user.edited":return void(null==(i=this.storeRegistry.get("users",t.userId))||i.userEdited(e,t));case"side.created":return null==(a=this.storeRegistry.get("me","conversations",t.conversationId,"messages"))||a.sideCreated(e,t),null==(o=this.storeRegistry.get("me","conversations",t.conversationId,"participants"))||o.sideCreated(e,t),null==(l=this.storeRegistry.get("me","conversations"))||l.sideCreated(e,t),this.storeRegistry.list("me","conversations",t.conversationId,"messages",C,"reactions",I).forEach(s=>s.sideOrMessageCreated(e,t)),null==(c=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId))||c.sideCreated(e,t),void this.storeRegistry.listVirtual("<virtual>","me","conversations",t.conversationId,"participants",S).forEach(s=>s.sideCreated(e,t));case"side.edited":return null==(u=this.storeRegistry.get("me","conversations"))||u.sideEdited(e,t),void(null==(d=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId))||d.sideEdited(e,t));case"side.deleted":return null==(p=null==(h=this.storeRegistry)?void 0:h.get("me","conversations",t.conversationId,"messages"))||p.sideDeleted(e,t),null==(g=null==(f=this.storeRegistry)?void 0:f.get("me","conversations",t.conversationId,"participants"))||g.sideDeleted(e,t),null==(v=null==(m=this.storeRegistry)?void 0:m.get("me","conversations",t.conversationId,"typing"))||v.sideDeleted(e,t),null==(y=this.storeRegistry.get("me","conversations"))||y.sideDeleted(e,t),this.storeRegistry.list("me","conversations",t.conversationId,"messages",C,"reactions",I).forEach(s=>s.sideOrMessageDeleted(e,t)),null==(b=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId))||b.sideDeleted(e,t),void this.storeRegistry.listVirtual("<virtual>","me","conversations",t.conversationId,"participants",S).forEach(s=>s.sideDeleted(e,t));case"conversation.edited":return void(null==(w=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId))||w.conversationEdited(e,t));case"message.created":return null==(k=this.storeRegistry.get("me","conversations",t.conversationId,"messages"))||k.messageCreated(e,t),void this.storeRegistry.list("me","conversations",t.conversationId,"messages",C,"reactions",I).forEach(s=>s.sideOrMessageCreated(e,t));case"message.edited":return void(null==(T=this.storeRegistry.get("me","conversations",t.conversationId,"messages"))||T.messageEdited(e,t));case"message.deleted":return null==(x=this.storeRegistry.get("me","conversations",t.conversationId,"messages"))||x.messageDeleted(e,t),void this.storeRegistry.list("me","conversations",t.conversationId,"messages",C,"reactions",I).forEach(s=>s.sideOrMessageDeleted(e,t));case"typing.available":return void(null==(E=this.storeRegistry.get("me","conversations",t.conversationId,"typing"))||E.typingAvailable(e,t));case"typing.changed":return void(null==(M=this.storeRegistry.get("me","conversations",t.conversationId,"typing"))||M.typingChanged(e,t));case"conversation.cleared":return void(null==(R=this.storeRegistry.get("me","conversations",t.conversationId,"messages"))||R.conversationCleared(e,t));case"participant.edited":return null==(A=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId))||A.participantEdited(e,t),void(null==(_=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId,"participants",t.userId))||_.participantEdited(e,t));case"participant.created":return null==(N=this.storeRegistry.get("me","conversations",t.conversationId,"participants"))||N.participantCreated(e,t),void(null==(D=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId,"participants",t.userId))||D.participantCreated(e,t));case"participant.deleted":return null==(O=this.storeRegistry.get("me","conversations",t.conversationId,"participants"))||O.participantDeleted(e,t),void(null==(P=this.storeRegistry.getVirtual("<virtual>","me","conversations",t.conversationId,"participants",t.userId))||P.participantDeleted(e,t));case"user.online.changed":return void(null==(j=this.storeRegistry.get("users",t.userId,"online"))||j.userOnlineChanged(e,t));case"reaction.added":return void(null==(U=this.storeRegistry.get("me","conversations",t.conversationId,"messages",t.messageId,"reactions",t.emoji))||U.reactionAdded(e,t));case"reaction.removed":return void(null==($=this.storeRegistry.get("me","conversations",t.conversationId,"messages",t.messageId,"reactions",t.emoji))||$.reactionRemoved(e,t));case"virtual.conversations.loadedMore":return void(null==(W=this.storeRegistry.get("me","conversations"))||W.loadedMore(e,t));case"virtual.messages.loadedMore":return void(null==(q=this.storeRegistry.get("me","conversations",t.conversationId,"messages"))||q.loadedMore(e,t));case"virtual.participants.loadedMore":return void(null==(L=this.storeRegistry.get("me","conversations",t.conversationId,"participants"))||L.loadedMore(e,t));case"virtual.reactions.loadedMore":return void(null==(B=this.storeRegistry.get("me","conversations",t.conversationId,"messages",t.messageId,"reactions",t.emoji))||B.loadedMore(e,t))}}call(e){return b(this,arguments,function*({method:e,path:t,data:s,headers:n,flags:r}){if(!0!==(null==r?void 0:r.bypassCache)&&"GET"===e){const e=this.storeRegistry.get(...t);if(e&&"getFromCache"in e){yield this.sync();const t=yield e.getFromCache();if("NOT_IN_CACHE"!==t.value)return t}else if(T(t,["me","conversations",k,"messages",C])){const e=this.storeRegistry.get("me","conversations",t[2],"messages");if(e){yield this.sync();const s=yield e.getMessageFromCache(t[4]);if("NOT_IN_CACHE"!==s.value)return s}}else if(T(t,["me","conversations",k,"participants",S])){const e=this.storeRegistry.getVirtual("<virtual>","me","conversations",t[2],"participants",t[4]);if(e){yield this.sync();const t=yield e.getFromCache();if("NOT_IN_CACHE"!==t.value)return t}}else if(T(t,["me","conversations",k])){const e=this.storeRegistry.getVirtual("<virtual>","me","conversations",t[2]);if(e){yield this.sync();const t=yield e.getFromCache();if("NOT_IN_CACHE"!==t.value)return t}}}return this.connection.call({method:e,path:t,data:s,headers:null!=n?n:{}})})}subscribe(e,t){const s=this.getOrCreateStore(e),n=A(),r=A();n.promise.catch(()=>{}),r.promise.catch(()=>{});const i={state:{type:"pending",latestSnapshot:void 0},connected:n.promise,terminated:r.promise,loadMore:e=>b(this,null,function*(){"loadMore"in s&&(yield s.loadMore(e))}),unsubscribe:()=>{}},a=s.listen(s=>{if(s.ok){const e=!("loadedAll"in s.value)||s.value.loadedAll,r={type:"active",latestSnapshot:s.value.snapshot,loadedAll:e};i.state=r,null==t||t(s.value.snapshot,e),n.resolve(r)}else if("pending"===i.state.type||"active"===i.state.type){if("server"===s.where){const t={type:"error",error:new Error($(`Subscribe to ${e.join("/")}`,s.value))};return i.state=t,r.resolve(t),void n.reject("Subscription encountered an error during initial connection")}if("SESSION_DESTROYED"===s.value){const e={type:"error",error:new Error("Session was destroyed causing all subscriptions to be terminated")};return i.state=e,r.resolve(e),void n.reject("Subscription encountered an error during initial connection")}if("UNSUBSCRIBED"===s.value)return;if("TERMINATED"===s.value)return;s.value}});return i.unsubscribe=()=>{if("pending"===i.state.type||"active"===i.state.type){a();const e={type:"unsubscribed"};i.state=e,r.resolve(e),n.reject("Subscription was unsubscribed before connecting")}},i}onVirtualPublish(e){return b(this,null,function*(){this.virtualSeqOffset++;const t=this.virtualSeq;this.handlePublish(t,e),yield this.emitAll(t)})}getOrCreateStore(e){const t=this.storeRegistry.get(...e);if(t)return t;this.connection.subscribe(e).then(e=>{e.ok||s.setError(e)});const s=this.instantiateStore(e,()=>{this.storeRegistry.delete(...e),this.connection.unsubscribe(e)});return this.storeRegistry.set(e,s),s}destroy(){this.storeRegistry=new ot,this.connection.destroy()}isConnected(){return this.connection.isConnected()}instantiateStore(e,t){if(T(e,["users",S]))return new Pe(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});if(T(e,["me","conversations",k]))return new Le(this.virtualSeq,this.subscribeConvData(e[2]),this.realtimeClient,this.emitMutex,{onTeardown:t});if(T(e,["me","conversations",k,"messages"]))return new $e(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(T(e,["me","conversations",k,"participants"]))return new Je(this.virtualSeq,t=>this.subscribeParticipantData(e[2],t),e[2],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(T(e,["me","conversations",k,"participants",S]))return new st(this.virtualSeq,this.subscribeParticipantData(e[2],e[4]),this.realtimeClient,this.emitMutex,{onTeardown:t});if(T(e,["me","conversations",k,"typing"]))return new Fe(this.virtualSeq,e[2],this.realtimeClient,this.emitMutex,{onTeardown:t});if(T(e,["me","conversations"]))return new Qe(this.virtualSeq,e=>this.subscribeConvData(e),this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});if(T(e,["users",S,"online"]))return new tt(this.virtualSeq,e[1],this.realtimeClient,this.emitMutex,{onTeardown:t});if(T(e,["me","conversations",k,"messages",C,"reactions",I]))return new nt(this.virtualSeq,e[2],e[4],e[6],this.realtimeClient,this.emitMutex,{onTeardown:t,onLoadedMore:e=>this.onVirtualPublish(e)});throw"Unreachable"}subscribeConvData(e){const t="string"==typeof e?e:e.id,s=this.storeRegistry.getVirtual("<virtual>","me","conversations",t);if(s)return{store:s,unsubscribe:s.registerInternalSubscription()};const n=new Xe(this.virtualSeq,e,this.realtimeClient,this.emitMutex,{onTeardown:()=>{this.storeRegistry.deleteVirtual("<virtual>","me","conversations",t)}});return this.storeRegistry.setVirtual(["<virtual>","me","conversations",t],n),{store:n,unsubscribe:n.registerInternalSubscription()}}subscribeParticipantData(e,t){const s="string"==typeof t?t:t.id,n=this.storeRegistry.getVirtual("<virtual>","me","conversations",e,"participants",s);if(n)return{store:n,unsubscribe:n.registerInternalSubscription()};const r=new He(this.virtualSeq,e,t,this.realtimeClient,this.emitMutex,{onTeardown:()=>{this.storeRegistry.deleteVirtual("<virtual>","me","conversations",e,"participants",s)}});return this.storeRegistry.setVirtual(["<virtual>","me","conversations",e,"participants",s],r),{store:r,unsubscribe:r.registerInternalSubscription()}}}class ct{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get(){return b(this,null,function*(){const e=yield this._realtimeClient.getUser(this.brandedId);return Or("Get user "+this.id,e)})}set(e){return b(this,null,function*(){null===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,s="string"==typeof e.phone?[e.phone]:e.phone,n=yield this._realtimeClient.call({method:"PUT",path:["users",this.brandedId],data:p(h({},e),{email:t,phone:s})});U("Set user "+this.id,n)})}createIfNotExists(e){return b(this,null,function*(){void 0===e.role&&(e.role="default");const t="string"==typeof e.email?[e.email]:e.email,s="string"==typeof e.phone?[e.phone]:e.phone,n=yield this._realtimeClient.call({method:"POST",path:["users",this.brandedId],data:p(h({},e),{email:t,phone:s})});(n.ok||"server"!==n.where||409!=n.value.status)&&U(`Create user ${this.id} if not exists`,n)})}subscribe(e){return this._realtimeClient.subscribe(["users",this.brandedId],e)}subscribeOnline(e){return this._realtimeClient.subscribe(["users",this.brandedId,"online"],e)}}function ut(e){const t="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";let s=0;const n=[],r=e===s;s=e;const i=new Array(8);for(let o=7;o>=0;o--)i[o]=t.charAt(e%64),e=Math.floor(e/64);if(0!==e)throw new Error("We should have converted the entire timestamp.");let a=i.join("");if(r){let e;for(e=11;e>=0&&63===n[e];e--)n[e]=0;n[e]++}else for(let o=0;o<12;o++)n[o]=Math.floor(64*Math.random());for(let o=0;o<12;o++)a+=t.charAt(n[o]);if(20!=a.length)throw new Error("Length should be 20.");return a}const dt=(e,t,s=void 0)=>e.reduce((e,n,r)=>e.concat((e=>{if("string"==typeof e)return t(e,s);switch(e.type){case"bold":case"italic":case"strikethrough":case"blockquote":case"bulletlist":case"bulletList":case"bulletpoint":case"bulletPoint":return[{type:e.type,children:dt(e.children,t,e.type)}];case"link":return[{type:e.type,url:e.url,children:dt(e.children,t,e.type)}];case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return[{type:e.type,action:e.action,params:e.params,children:dt(e.children,t,e.type)}];case"mention":case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"suppressed":case"emoji":case"customemoji":case"customEmoji":return[e]}})(n)),[]);function ht(e,t){return s=>{const n=s;let r=0;const i=[];for(const a of Ce(s,e)){a.index-r>0&&i.push(n.substring(r,a.index));const e=t(a);Array.isArray(e)?i.push(...e):i.push(e),r=a.index+a[0].length}return r<s.length&&i.push(s.substring(r)),i}}const pt="’'()[]{}<>:,‒–—―…!.«»-‐?‘’“”;/⁄␠·&@*\\•^¤¢$€£¥₩₪†‡°¡¿¬#№%‰‱¶′§~¨_|¦⁂☞∴‽※".replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var ft,gt=((ft=gt||{})[ft.italic=1]="italic",ft[ft.strikethrough=2]="strikethrough",ft[ft.bold=4]="bold",ft);const mt=[0,1,2,3,4,5,6].map(e=>{const t=[];return 1&e||t.push(/_([^\s_].*?[^\s_])_|_([^\s_])_/),2&e||t.push(/~([^\s~].*?[^\s~])~|~([^\s~])~/),4&e||t.push(/\*([^\s*].*?[^\s*])\*|\*([^\s*])\*/),new RegExp(t.map(e=>e.source).join("|"),"g")}),vt={_:1,"*":4,"~":2};function yt(e){return bt(e,0)}function bt(e,t=0){const s=mt[t],n=s?function(e){const t=ht(wt.getOrCompute(e,()=>new RegExp(`(?:^|[\\s${pt}])(?:${e.source})(?=[\\s${pt}]|$)`,"g")),e=>{const t=e[0][1],s=e[1]||e[2]||e[3]||e[4]||e[5]||e[6];return[" ",{type:gt[vt[t]],children:[s]}]});return e=>{const[s,...n]=t(" "+e);return s.length>1&&n.unshift(s.substring(1)),n}}(s):()=>[e];return dt(n(e),(e,s)=>"bold"===s||"italic"===s||"strikethrough"===s?bt(e,t|gt[s]):[e])}const wt=function(){const e=function(){try{return new WeakMap}catch(e){const t={has:()=>!1,get:()=>{},set:()=>t};return t}}();return{getOrCompute(t,s){if(e.has(t))return e.get(t);const n=s();return e.set(t,n),n}}}();var kt=function(e,t){return(kt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s])})(e,t)};function Ct(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function s(){this.constructor=e}kt(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)}var St=function(){return St=Object.assign||function(e){for(var t,s=1,n=arguments.length;s<n;s++)for(var r in t=arguments[s])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},St.apply(this,arguments)};"function"==typeof SuppressedError&&SuppressedError;var It=Object.prototype.hasOwnProperty;function Tt(e){return"boolean"==typeof e}function xt(e,t){for(var s=e.length-1;s>=0;s--)!0===t(e[s])&&e.splice(s,1)}function Et(e){throw new Error("Unhandled case for value: '".concat(e,"'"))}var Mt=/\s+/,Rt=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.tagName=e.tagName||"",this.attrs=e.attrs||{},this.innerHTML=e.innerHtml||e.innerHTML||""}return e.prototype.setTagName=function(e){return this.tagName=e,this},e.prototype.getTagName=function(){return this.tagName},e.prototype.setAttr=function(e,t){return this.getAttrs()[e]=t,this},e.prototype.getAttr=function(e){return this.getAttrs()[e]},e.prototype.setAttrs=function(e){return Object.assign(this.getAttrs(),e),this},e.prototype.getAttrs=function(){return this.attrs},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,s=this.getClass(),n=s?s.split(Mt):[],r=e.split(Mt);t=r.shift();)-1===n.indexOf(t)&&n.push(t);return this.getAttrs().class=n.join(" "),this},e.prototype.removeClass=function(e){for(var t,s=this.getClass(),n=s?s.split(Mt):[],r=e.split(Mt);n.length&&(t=r.shift());){var i=n.indexOf(t);-1!==i&&n.splice(i,1)}return this.getAttrs().class=n.join(" "),this},e.prototype.getClass=function(){return this.getAttrs().class||""},e.prototype.hasClass=function(e){return-1!==(" "+this.getClass()+" ").indexOf(" "+e+" ")},e.prototype.setInnerHTML=function(e){return this.innerHTML=e,this},e.prototype.setInnerHtml=function(e){return this.setInnerHTML(e)},e.prototype.getInnerHTML=function(){return this.innerHTML||""},e.prototype.getInnerHtml=function(){return this.getInnerHTML()},e.prototype.toAnchorString=function(){var e=this.getTagName(),t=this.buildAttrsStr();return["<",e,t=t?" "+t:"",">",this.getInnerHtml(),"</",e,">"].join("")},e.prototype.buildAttrsStr=function(){var e=this.getAttrs(),t=[];for(var s in e)It.call(e,s)&&t.push(s+'="'+e[s]+'"');return t.join(" ")},e}();function At(e){var t="";return e.scheme&&e.host&&(t+=e.scheme+"://"),e.host&&(t+=e.host),e.path&&(t+="/"+e.path),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t}function _t(e,t,s){var n=t/2,r=Math.ceil(n),i=-1*Math.floor(n),a="";return i<0&&(a=e.substr(i)),e.substr(0,r)+s+a}var Nt=function(){function e(e){void 0===e&&(e={}),this.newWindow=!1,this.truncate={},this.className="",this.newWindow=e.newWindow||!1,this.truncate=e.truncate||{},this.className=e.className||""}return e.prototype.build=function(e){return new Rt({tagName:"a",attrs:this.createAttrs(e),innerHtml:this.processAnchorText(e.getAnchorText())})},e.prototype.createAttrs=function(e){var t={href:e.getAnchorHref()},s=this.createCssClass(e);return s&&(t.class=s),this.newWindow&&(t.target="_blank",t.rel="noopener noreferrer"),this.truncate.length&&this.truncate.length<e.getAnchorText().length&&(t.title=e.getAnchorHref()),t},e.prototype.createCssClass=function(e){var t=this.className;if(t){for(var s=[t],n=e.getCssClassSuffixes(),r=0,i=n.length;r<i;r++)s.push(t+"-"+n[r]);return s.join(" ")}return""},e.prototype.processAnchorText=function(e){return this.doTruncate(e)},e.prototype.doTruncate=function(e){var t=this.truncate;if(!t.length)return e;var s,n,r,i,a=t.length,o=t.location;return"smart"===o?function(e,t,s){var n,r;if(null==s?(s="…",r=3,n=8):(r=s.length,n=s.length),e.length<=t)return e;var i,a,o,l=t-r,c=(i={},(o=(a=e).match(/^([a-z]+):\/\//i))&&(i.scheme=o[1],a=a.slice(o[0].length)),(o=a.match(/^(.*?)(?=(\?|#|\/|$))/i))&&(i.host=o[1],a=a.slice(o[0].length)),(o=a.match(/^\/(.*?)(?=(\?|#|$))/i))&&(i.path=o[1],a=a.slice(o[0].length)),(o=a.match(/^\?(.*?)(?=(#|$))/i))&&(i.query=o[1],a=a.slice(o[0].length)),(o=a.match(/^#(.*?)$/i))&&(i.fragment=o[1]),i);if(c.query){var u=c.query.match(/^(.*?)(?=(\?|#))(.*?)$/i);u&&(c.query=c.query.substr(0,u[1].length),e=At(c))}if(e.length<=t)return e;if(c.host&&(c.host=c.host.replace(/^www\./,""),e=At(c)),e.length<=t)return e;var d="";if(c.host&&(d+=c.host),d.length>=l)return c.host.length===t?(c.host.substr(0,t-r)+s).substr(0,l+n):_t(d,l,s).substr(0,l+n);var h="";if(c.path&&(h+="/"+c.path),c.query&&(h+="?"+c.query),h){if((d+h).length>=l)return(d+h).length==t?(d+h).substr(0,t):(d+_t(h,l-d.length,s)).substr(0,l+n);d+=h}if(c.fragment){var p="#"+c.fragment;if((d+p).length>=l)return(d+p).length==t?(d+p).substr(0,t):(d+_t(p,l-d.length,s)).substr(0,l+n);d+=p}if(c.scheme&&c.host){var f=c.scheme+"://";if((d+f).length<l)return(f+d).substr(0,t)}if(d.length<=t)return d;var g="";return l>0&&(g=d.substr(-1*Math.floor(l/2))),(d.substr(0,Math.ceil(l/2))+s+g).substr(0,l+n)}(e,a):"middle"===o?function(e,t,s){if(e.length<=t)return e;var n,r;null==s?(s="…",n=8,r=3):(n=s.length,r=s.length);var i=t-r,a="";return i>0&&(a=e.substr(-1*Math.floor(i/2))),(e.substr(0,Math.ceil(i/2))+s+a).substr(0,i+n)}(e,a):(n=a,r=void 0,(s=e).length>n&&(null==r?(r="…",i=3):i=r.length,s=s.substring(0,n-i)+r),s)},e}(),Dt=function(){function e(e){this._=null,this.matchedText="",this.offset=0,this.tagBuilder=e.tagBuilder,this.matchedText=e.matchedText,this.offset=e.offset}return e.prototype.getMatchedText=function(){return this.matchedText},e.prototype.setOffset=function(e){this.offset=e},e.prototype.getOffset=function(){return this.offset},e.prototype.getCssClassSuffixes=function(){return[this.type]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}();function Ot(e){return e>=65&&e<=90||e>=97&&e<=122}function Pt(e){return e>=48&&e<=57}function jt(e){return 34==e||39==e}function Ut(e){return e<8232?e<160?e>=9&&e<=13||32==e:e<5760?160==e:5760==e||e>=8192&&e<=8202:e<8287?e>=8232&&e<=8233||8239==e:e<12288?8287==e:12288==e||65279==e}function $t(e){return e<4800?e<2949?e<2451?e<1425?e<768?e<192?e<169?e<65?e>=48&&e<=57:e>=65&&e<=90||e>=97&&e<=122:e<181?e>=169&&e<=170||174==e:181==e||186==e:e<710?e<216?e>=192&&e<=214:e>=216&&e<=246||e>=248&&e<=705:e<748?e>=710&&e<=721||e>=736&&e<=740:748==e||750==e:e<910?e<895?e<886?e>=768&&e<=884:e>=886&&e<=887||e>=890&&e<=893:e<904?895==e||902==e:e>=904&&e<=906||908==e:e<1155?e<931?e>=910&&e<=929:e>=931&&e<=1013||e>=1015&&e<=1153:e<1369?e>=1155&&e<=1327||e>=1329&&e<=1366:1369==e||e>=1377&&e<=1415:e<1808?e<1552?e<1476?e<1471?e>=1425&&e<=1469:1471==e||e>=1473&&e<=1474:e<1488?e>=1476&&e<=1477||1479==e:e>=1488&&e<=1514||e>=1520&&e<=1522:e<1749?e<1568?e>=1552&&e<=1562:e>=1568&&e<=1641||e>=1646&&e<=1747:e<1770?e>=1749&&e<=1756||e>=1759&&e<=1768:e>=1770&&e<=1788||1791==e:e<2230?e<2042?e<1869?e>=1808&&e<=1866:e>=1869&&e<=1969||e>=1984&&e<=2037:e<2112?2042==e||e>=2048&&e<=2093:e>=2112&&e<=2139||e>=2208&&e<=2228:e<2406?e<2260?e>=2230&&e<=2237:e>=2260&&e<=2273||e>=2275&&e<=2403:e<2437?e>=2406&&e<=2415||e>=2417&&e<=2435:e>=2437&&e<=2444||e>=2447&&e<=2448:e<2693?e<2579?e<2519?e<2486?e<2474?e>=2451&&e<=2472:e>=2474&&e<=2480||2482==e:e<2503?e>=2486&&e<=2489||e>=2492&&e<=2500:e>=2503&&e<=2504||e>=2507&&e<=2510:e<2534?e<2524?2519==e:e>=2524&&e<=2525||e>=2527&&e<=2531:e<2565?e>=2534&&e<=2545||e>=2561&&e<=2563:e>=2565&&e<=2570||e>=2575&&e<=2576:e<2631?e<2613?e<2602?e>=2579&&e<=2600:e>=2602&&e<=2608||e>=2610&&e<=2611:e<2620?e>=2613&&e<=2614||e>=2616&&e<=2617:2620==e||e>=2622&&e<=2626:e<2649?e<2635?e>=2631&&e<=2632:e>=2635&&e<=2637||2641==e:e<2662?e>=2649&&e<=2652||2654==e:e>=2662&&e<=2677||e>=2689&&e<=2691:e<2821?e<2759?e<2730?e<2703?e>=2693&&e<=2701:e>=2703&&e<=2705||e>=2707&&e<=2728:e<2741?e>=2730&&e<=2736||e>=2738&&e<=2739:e>=2741&&e<=2745||e>=2748&&e<=2757:e<2784?e<2763?e>=2759&&e<=2761:e>=2763&&e<=2765||2768==e:e<2809?e>=2784&&e<=2787||e>=2790&&e<=2799:2809==e||e>=2817&&e<=2819:e<2887?e<2858?e<2831?e>=2821&&e<=2828:e>=2831&&e<=2832||e>=2835&&e<=2856:e<2869?e>=2858&&e<=2864||e>=2866&&e<=2867:e>=2869&&e<=2873||e>=2876&&e<=2884:e<2911?e<2902?e>=2887&&e<=2888||e>=2891&&e<=2893:e>=2902&&e<=2903||e>=2908&&e<=2909:e<2929?e>=2911&&e<=2915||e>=2918&&e<=2927:2929==e||e>=2946&&e<=2947:e<3517?e<3205?e<3046?e<2984?e<2969?e<2958?e>=2949&&e<=2954:e>=2958&&e<=2960||e>=2962&&e<=2965:e<2974?e>=2969&&e<=2970||2972==e:e>=2974&&e<=2975||e>=2979&&e<=2980:e<3014?e<2990?e>=2984&&e<=2986:e>=2990&&e<=3001||e>=3006&&e<=3010:e<3024?e>=3014&&e<=3016||e>=3018&&e<=3021:3024==e||3031==e:e<3142?e<3086?e<3072?e>=3046&&e<=3055:e>=3072&&e<=3075||e>=3077&&e<=3084:e<3114?e>=3086&&e<=3088||e>=3090&&e<=3112:e>=3114&&e<=3129||e>=3133&&e<=3140:e<3160?e<3146?e>=3142&&e<=3144:e>=3146&&e<=3149||e>=3157&&e<=3158:e<3174?e>=3160&&e<=3162||e>=3168&&e<=3171:e>=3174&&e<=3183||e>=3200&&e<=3203:e<3333?e<3274?e<3242?e<3214?e>=3205&&e<=3212:e>=3214&&e<=3216||e>=3218&&e<=3240:e<3260?e>=3242&&e<=3251||e>=3253&&e<=3257:e>=3260&&e<=3268||e>=3270&&e<=3272:e<3296?e<3285?e>=3274&&e<=3277:e>=3285&&e<=3286||3294==e:e<3313?e>=3296&&e<=3299||e>=3302&&e<=3311:e>=3313&&e<=3314||e>=3329&&e<=3331:e<3423?e<3389?e<3342?e>=3333&&e<=3340:e>=3342&&e<=3344||e>=3346&&e<=3386:e<3402?e>=3389&&e<=3396||e>=3398&&e<=3400:e>=3402&&e<=3406||e>=3412&&e<=3415:e<3458?e<3430?e>=3423&&e<=3427:e>=3430&&e<=3439||e>=3450&&e<=3455:e<3482?e>=3458&&e<=3459||e>=3461&&e<=3478:e>=3482&&e<=3505||e>=3507&&e<=3515:e<3804?e<3722?e<3570?e<3535?e<3520?3517==e:e>=3520&&e<=3526||3530==e:e<3544?e>=3535&&e<=3540||3542==e:e>=3544&&e<=3551||e>=3558&&e<=3567:e<3664?e<3585?e>=3570&&e<=3571:e>=3585&&e<=3642||e>=3648&&e<=3662:e<3716?e>=3664&&e<=3673||e>=3713&&e<=3714:3716==e||e>=3719&&e<=3720:e<3754?e<3737?e<3725?3722==e:3725==e||e>=3732&&e<=3735:e<3749?e>=3737&&e<=3743||e>=3745&&e<=3747:3749==e||3751==e:e<3776?e<3757?e>=3754&&e<=3755:e>=3757&&e<=3769||e>=3771&&e<=3773:e<3784?e>=3776&&e<=3780||3782==e:e>=3784&&e<=3789||e>=3792&&e<=3801:e<4176?e<3902?e<3872?e<3840?e>=3804&&e<=3807:3840==e||e>=3864&&e<=3865:e<3895?e>=3872&&e<=3881||3893==e:3895==e||3897==e:e<3974?e<3913?e>=3902&&e<=3911:e>=3913&&e<=3948||e>=3953&&e<=3972:e<4038?e>=3974&&e<=3991||e>=3993&&e<=4028:4038==e||e>=4096&&e<=4169:e<4688?e<4301?e<4256?e>=4176&&e<=4253:e>=4256&&e<=4293||4295==e:e<4348?4301==e||e>=4304&&e<=4346:e>=4348&&e<=4680||e>=4682&&e<=4685:e<4746?e<4698?e>=4688&&e<=4694||4696==e:e>=4698&&e<=4701||e>=4704&&e<=4744:e<4786?e>=4746&&e<=4749||e>=4752&&e<=4784:e>=4786&&e<=4789||e>=4792&&e<=4798:e<11035?e<7416?e<6176?e<5873?e<4992?e<4824?e<4802?4800==e:e>=4802&&e<=4805||e>=4808&&e<=4822:e<4888?e>=4824&&e<=4880||e>=4882&&e<=4885:e>=4888&&e<=4954||e>=4957&&e<=4959:e<5121?e<5024?e>=4992&&e<=5007:e>=5024&&e<=5109||e>=5112&&e<=5117:e<5761?e>=5121&&e<=5740||e>=5743&&e<=5759:e>=5761&&e<=5786||e>=5792&&e<=5866:e<6002?e<5920?e<5888?e>=5873&&e<=5880:e>=5888&&e<=5900||e>=5902&&e<=5908:e<5984?e>=5920&&e<=5940||e>=5952&&e<=5971:e>=5984&&e<=5996||e>=5998&&e<=6e3:e<6108?e<6016?e>=6002&&e<=6003:e>=6016&&e<=6099||6103==e:e<6155?e>=6108&&e<=6109||e>=6112&&e<=6121:e>=6155&&e<=6157||e>=6160&&e<=6169:e<6783?e<6512?e<6400?e<6272?e>=6176&&e<=6263:e>=6272&&e<=6314||e>=6320&&e<=6389:e<6448?e>=6400&&e<=6430||e>=6432&&e<=6443:e>=6448&&e<=6459||e>=6470&&e<=6509:e<6608?e<6528?e>=6512&&e<=6516:e>=6528&&e<=6571||e>=6576&&e<=6601:e<6688?e>=6608&&e<=6617||e>=6656&&e<=6683:e>=6688&&e<=6750||e>=6752&&e<=6780:e<7040?e<6832?e<6800?e>=6783&&e<=6793:e>=6800&&e<=6809||6823==e:e<6992?e>=6832&&e<=6846||e>=6912&&e<=6987:e>=6992&&e<=7001||e>=7019&&e<=7027:e<7245?e<7168?e>=7040&&e<=7155:e>=7168&&e<=7223||e>=7232&&e<=7241:e<7376?e>=7245&&e<=7293||e>=7296&&e<=7304:e>=7376&&e<=7378||e>=7380&&e<=7414:e<8450?e<8130?e<8025?e<7960?e<7424?e>=7416&&e<=7417:e>=7424&&e<=7669||e>=7675&&e<=7957:e<8008?e>=7960&&e<=7965||e>=7968&&e<=8005:e>=8008&&e<=8013||e>=8016&&e<=8023:e<8031?e<8027?8025==e:8027==e||8029==e:e<8118?e>=8031&&e<=8061||e>=8064&&e<=8116:e>=8118&&e<=8124||8126==e:e<8205?e<8150?e<8134?e>=8130&&e<=8132:e>=8134&&e<=8140||e>=8144&&e<=8147:e<8178?e>=8150&&e<=8155||e>=8160&&e<=8172:e>=8178&&e<=8180||e>=8182&&e<=8188:e<8305?e<8252?8205==e:8252==e||8265==e:e<8336?8305==e||8319==e:e>=8336&&e<=8348||e>=8400&&e<=8432:e<8579?e<8486?e<8469?e<8455?8450==e:8455==e||e>=8458&&e<=8467:e<8482?8469==e||e>=8473&&e<=8477:8482==e||8484==e:e<8495?e<8488?8486==e:8488==e||e>=8490&&e<=8493:e<8517?e>=8495&&e<=8505||e>=8508&&e<=8511:e>=8517&&e<=8521||8526==e:e<9410?e<9e3?e<8592?e>=8579&&e<=8580:e>=8592&&e<=8703||e>=8986&&e<=8987:e<9193?9e3==e||9167==e:e>=9193&&e<=9203||e>=9208&&e<=9210:e<9723?e<9654?9410==e||e>=9642&&e<=9643:9654==e||9664==e:e<10548?e>=9723&&e<=9726||e>=9728&&e<=10175:e>=10548&&e<=10549||e>=11013&&e<=11015:e<43259?e<12445?e<11688?e<11520?e<11264?e<11088?e>=11035&&e<=11036:11088==e||11093==e:e<11360?e>=11264&&e<=11310||e>=11312&&e<=11358:e>=11360&&e<=11492||e>=11499&&e<=11507:e<11568?e<11559?e>=11520&&e<=11557:11559==e||11565==e:e<11647?e>=11568&&e<=11623||11631==e:e>=11647&&e<=11670||e>=11680&&e<=11686:e<11744?e<11712?e<11696?e>=11688&&e<=11694:e>=11696&&e<=11702||e>=11704&&e<=11710:e<11728?e>=11712&&e<=11718||e>=11720&&e<=11726:e>=11728&&e<=11734||e>=11736&&e<=11742:e<12330?e<11823?e>=11744&&e<=11775:11823==e||e>=12293&&e<=12294:e<12353?e>=12330&&e<=12341||e>=12347&&e<=12349:e>=12353&&e<=12438||e>=12441&&e<=12442:e<42512?e<12951?e<12549?e<12449?e>=12445&&e<=12447:e>=12449&&e<=12538||e>=12540&&e<=12543:e<12704?e>=12549&&e<=12589||e>=12593&&e<=12686:e>=12704&&e<=12730||e>=12784&&e<=12799:e<19968?e<12953?12951==e:12953==e||e>=13312&&e<=19893:e<42192?e>=19968&&e<=40917||e>=40960&&e<=42124:e>=42192&&e<=42237||e>=42240&&e<=42508:e<42891?e<42623?e<42560?e>=42512&&e<=42539:e>=42560&&e<=42610||e>=42612&&e<=42621:e<42775?e>=42623&&e<=42725||e>=42736&&e<=42737:e>=42775&&e<=42783||e>=42786&&e<=42888:e<43072?e<42928?e>=42891&&e<=42926:e>=42928&&e<=42935||e>=42999&&e<=43047:e<43216?e>=43072&&e<=43123||e>=43136&&e<=43205:e>=43216&&e<=43225||e>=43232&&e<=43255:e<55243?e<43744?e<43488?e<43312?e<43261?43259==e:43261==e||e>=43264&&e<=43309:e<43392?e>=43312&&e<=43347||e>=43360&&e<=43388:e>=43392&&e<=43456||e>=43471&&e<=43481:e<43600?e<43520?e>=43488&&e<=43518:e>=43520&&e<=43574||e>=43584&&e<=43597:e<43642?e>=43600&&e<=43609||e>=43616&&e<=43638:e>=43642&&e<=43714||e>=43739&&e<=43741:e<43824?e<43785?e<43762?e>=43744&&e<=43759:e>=43762&&e<=43766||e>=43777&&e<=43782:e<43808?e>=43785&&e<=43790||e>=43793&&e<=43798:e>=43808&&e<=43814||e>=43816&&e<=43822:e<44012?e<43868?e>=43824&&e<=43866:e>=43868&&e<=43877||e>=43888&&e<=44010:e<44032?e>=44012&&e<=44013||e>=44016&&e<=44025:e>=44032&&e<=55203||e>=55216&&e<=55238:e<64848?e<64298?e<64112?e<55296?e>=55243&&e<=55291:e>=55296&&e<=57343||e>=63744&&e<=64109:e<64275?e>=64112&&e<=64217||e>=64256&&e<=64262:e>=64275&&e<=64279||e>=64285&&e<=64296:e<64320?e<64312?e>=64298&&e<=64310:e>=64312&&e<=64316||64318==e:e<64326?e>=64320&&e<=64321||e>=64323&&e<=64324:e>=64326&&e<=64433||e>=64467&&e<=64829:e<65296?e<65024?e<64914?e>=64848&&e<=64911:e>=64914&&e<=64967||e>=65008&&e<=65019:e<65136?e>=65024&&e<=65039||e>=65056&&e<=65071:e>=65136&&e<=65140||e>=65142&&e<=65276:e<65474?e<65345?e>=65296&&e<=65305||e>=65313&&e<=65338:e>=65345&&e<=65370||e>=65382&&e<=65470:e<65490?e>=65474&&e<=65479||e>=65482&&e<=65487:e>=65490&&e<=65495||e>=65498&&e<=65500}function Wt(e){return e<58?e<44?33==e:44==e||46==e:e<63?e>=58&&e<=59:63==e||94==e}function qt(e){return e<91?40==e:91==e||123==e}function Lt(e){return e<93?41==e:93==e||125==e}var Bt=/^(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|travelersinsurance|vermögensberatung|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbah1a3hjkrd|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--mgbcpq6gpa1a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbc0a9azcg|xn--nqv7fs00ema|americanfamily|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq480n2rg|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|wolterskluwer|xn--cckwcxetd|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|xn--4dbrk0ce|xn--80adxhks|xn--80asehdb|xn--8y0a063a|xn--gckr3f0f|xn--mgb9awbf|xn--mgbab2bd|xn--mgbgu82a|xn--mgbpl2fh|xn--mgbt3dhd|xn--mk1bu44c|xn--ngbc5azd|xn--ngbe9e0a|xn--ogbpf8fl|xn--qcka1pmc|accountants|barclaycard|blackfriday|blockbuster|bridgestone|calvinklein|contractors|creditunion|engineering|enterprises|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|williamhill|xn--11b4c3d|xn--1ck2e1b|xn--1qqw23a|xn--2scrj9c|xn--3bst00m|xn--3ds443g|xn--3hcrj9c|xn--42c2d9a|xn--45brj9c|xn--55qw42g|xn--6frz82g|xn--80ao21a|xn--9krt00a|xn--cck2b3b|xn--czr694b|xn--d1acj3b|xn--efvy88h|xn--fct429k|xn--fjq720a|xn--flw351e|xn--g2xx48c|xn--gecrj9c|xn--gk3at1e|xn--h2brj9c|xn--hxt814e|xn--imr513n|xn--j6w193g|xn--jvr189m|xn--kprw13d|xn--kpry57d|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pgbs0dh|xn--q9jyb4c|xn--rhqv96g|xn--rovu88b|xn--s9brj9c|xn--ses554g|xn--t60b56a|xn--vuq861b|xn--w4rs40l|xn--xhq521b|xn--zfr164b|சிங்கப்பூர்|accountant|apartments|associates|basketball|bnpparibas|boehringer|capitalone|consulting|creditcard|cuisinella|eurovision|extraspace|foundation|healthcare|immobilien|industries|management|mitsubishi|nextdirect|properties|protection|prudential|realestate|republican|restaurant|schaeffler|tatamotors|technology|university|vlaanderen|xn--30rr7y|xn--3pxu8k|xn--45q11c|xn--4gbrim|xn--55qx5d|xn--5tzm5g|xn--80aswg|xn--90a3ac|xn--9dbq2a|xn--9et52u|xn--c2br7g|xn--cg4bki|xn--czrs0t|xn--czru2d|xn--fiq64b|xn--fiqs8s|xn--fiqz9s|xn--io0a7i|xn--kput3i|xn--mxtq1m|xn--o3cw4h|xn--pssy2u|xn--q7ce6a|xn--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|institute|insurance|kuokgroup|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|pramerica|richardli|shangrila|solutions|statebank|statefarm|stockholm|travelers|vacations|xn--90ais|xn--c1avg|xn--d1alf|xn--e1a4c|xn--fhbei|xn--j1aef|xn--j1amh|xn--l1acc|xn--ngbrx|xn--nqv7f|xn--p1acf|xn--qxa6a|xn--tckwe|xn--vhquv|yodobashi|موريتانيا|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|builders|business|capetown|catering|catholic|cipriani|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|mckinsey|memorial|merckmsd|mortgage|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|softbank|software|stcgroup|supplies|training|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|banamex|bauhaus|bestbuy|booking|brother|capital|caravan|careers|channel|charity|chintai|citadel|clubmed|college|cologne|company|compare|contact|cooking|corsica|country|coupons|courses|cricket|cruises|dentist|digital|domains|exposed|express|farmers|fashion|ferrari|ferrero|finance|fishing|fitness|flights|florist|flowers|forsale|frogans|fujitsu|gallery|genting|godaddy|grocery|guitars|hamburg|hangout|hitachi|holiday|hosting|hotmail|hyundai|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lanxess|lasalle|latrobe|leclerc|limited|lincoln|markets|monster|netbank|netflix|network|neustar|okinawa|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|singles|staples|storage|support|surgery|systems|temasek|theater|theatre|tickets|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|yamaxun|youtube|zuerich|католик|البحرين|الجزائر|العليان|پاکستان|كاثوليك|இந்தியா|abbott|abbvie|africa|agency|airbus|airtel|alipay|alsace|alstom|amazon|anquan|aramco|author|bayern|beauty|berlin|bharti|bostik|boston|broker|camera|career|casino|center|chanel|chrome|church|circle|claims|clinic|coffee|comsec|condos|coupon|credit|cruise|dating|datsun|dealer|degree|dental|design|direct|doctor|dunlop|dupont|durban|emerck|energy|estate|events|expert|family|flickr|futbol|gallup|garden|george|giving|global|google|gratis|health|hermes|hiphop|hockey|hotels|hughes|imamat|insure|intuit|jaguar|joburg|juegos|kaufen|kindle|kosher|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|monash|mormon|moscow|museum|nagoya|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|pictet|quebec|racing|realty|reisen|repair|report|review|rogers|ryukyu|safety|sakura|sanofi|school|schule|search|secure|select|shouji|soccer|social|stream|studio|supply|suzuki|swatch|sydney|taipei|taobao|target|tattoo|tennis|tienda|tjmaxx|tkmaxx|toyota|travel|unicom|viajes|viking|villas|virgin|vision|voting|voyage|walter|webcam|xihuan|yachts|yandex|zappos|москва|онлайн|ابوظبي|ارامكو|الاردن|المغرب|امارات|فلسطين|مليسيا|भारतम्|இலங்கை|ファッション|actor|adult|aetna|amfam|amica|apple|archi|audio|autos|azure|baidu|beats|bible|bingo|black|boats|bosch|build|canon|cards|chase|cheap|cisco|citic|click|cloud|coach|codes|crown|cymru|dance|deals|delta|drive|dubai|earth|edeka|email|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|irish|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|loans|locus|lotte|lotto|mango|media|miami|money|movie|music|nexus|nikon|ninja|nokia|nowtv|omega|osaka|paris|parts|party|phone|photo|pizza|place|poker|praxi|press|prime|promo|quest|radio|rehab|reise|ricoh|rocks|rodeo|rugby|salon|sener|seven|sharp|shell|shoes|skype|sling|smart|smile|solar|space|sport|stada|store|study|style|sucks|swiss|tatar|tires|tirol|tmall|today|tokyo|tools|toray|total|tours|trade|trust|tunes|tushu|ubank|vegas|video|vodka|volvo|wales|watch|weber|weibo|works|world|xerox|yahoo|ישראל|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|aero|akdn|ally|amex|arab|army|arpa|arte|asda|asia|audi|auto|baby|band|bank|bbva|beer|best|bike|bing|blog|blue|bofa|bond|book|buzz|cafe|call|camp|care|cars|casa|case|cash|cbre|cern|chat|citi|city|club|cool|coop|cyou|data|date|dclk|deal|dell|desi|diet|dish|docs|dvag|erni|fage|fail|fans|farm|fast|fido|film|fire|fish|flir|food|ford|free|fund|game|gbiz|gent|ggee|gift|gmbh|gold|golf|goog|guge|guru|hair|haus|hdfc|help|here|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kids|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|love|ltda|luxe|maif|meet|meme|menu|mini|mint|mobi|moda|moto|name|navy|news|next|nico|nike|ollo|open|page|pars|pccw|pics|ping|pink|play|plus|pohl|porn|post|prod|prof|qpon|read|reit|rent|rest|rich|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scot|seat|seek|sexy|shia|shop|show|silk|sina|site|skin|sncf|sohu|song|sony|spot|star|surf|talk|taxi|team|tech|teva|tiaa|tips|town|toys|tube|vana|visa|viva|vivo|vote|voto|wang|weir|wien|wiki|wine|work|xbox|yoga|zara|zero|zone|дети|сайт|بارت|بيتك|ڀارت|تونس|شبكة|عراق|عمان|موقع|भारत|ভারত|ভাৰত|ਭਾਰਤ|ભારત|ଭାରତ|ಭಾರತ|ලංකා|アマゾン|グーグル|クラウド|ポイント|组织机构|電訊盈科|香格里拉|aaa|abb|abc|aco|ads|aeg|afl|aig|anz|aol|app|art|aws|axa|bar|bbc|bbt|bcg|bcn|bet|bid|bio|biz|bms|bmw|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|ceo|cfa|cfd|com|cpa|crs|dad|day|dds|dev|dhl|diy|dnp|dog|dot|dtv|dvr|eat|eco|edu|esq|eus|fan|fit|fly|foo|fox|frl|ftr|fun|fyi|gal|gap|gay|gdn|gea|gle|gmo|gmx|goo|gop|got|gov|hbo|hiv|hkt|hot|how|ibm|ice|icu|ifm|inc|ing|ink|int|ist|itv|jcb|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|llp|lol|lpl|ltd|man|map|mba|med|men|mil|mit|mlb|mls|mma|moe|moi|mom|mov|msd|mtn|mtr|nab|nba|nec|net|new|nfl|ngo|nhk|now|nra|nrw|ntt|nyc|obi|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|scb|sew|sex|sfr|ski|sky|soy|spa|srl|stc|tab|tax|tci|tdk|tel|thd|tjx|top|trv|tui|tvs|ubs|uno|uol|ups|vet|vig|vin|vip|wed|win|wme|wow|wtc|wtf|xin|xxx|xyz|you|yun|zip|бел|ком|қаз|мкд|мон|орг|рус|срб|укр|հայ|קום|عرب|قطر|كوم|مصر|कॉम|नेट|คอม|ไทย|ລາວ|ストア|セール|みんな|中文网|亚马逊|天主教|我爱你|新加坡|淡马锡|飞利浦|ac|ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|ευ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|广东|微博|慈善|手机|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)$/,Gt=/https?:\/\//i,Ft=new RegExp("^"+Gt.source,"i"),Ht=/^(javascript|vbscript):/i,zt=/^[A-Za-z][-.+A-Za-z0-9]*:(\/\/)?([^:/]*)/,Jt=/^(?:\/\/)?([^/#?:]+)/,Yt=Ot;function Vt(e){return Ot(e)||Pt(e)||43===e||45===e||46===e}var Qt=$t;function Kt(e){return 95===e||Qt(e)}function Zt(e){return $t(e)||((t=e)<91?t<47?t>=35&&t<=43||45==t:t<61?47==t:61==t||64==t:t<95?91==t||93==t:t<123?95==t:t>=123&&t<=126||10003==t)||Wt(e);var t}function Xt(e){return 47===e||63===e||35===e}function es(e){return Bt.test(e.toLowerCase())}var ts=/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,ss=/[:/?#]/,ns=/^(https?:\/\/)?(?:www\.)?/i,rs=/^\/\//,is=function(e){function t(t){var s=e.call(this,t)||this;return s.type="url",s.url="",s.urlMatchType="scheme",s.protocolRelativeMatch=!1,s.stripPrefix={scheme:!0,www:!0},s.stripTrailingSlash=!0,s.decodePercentEncoding=!0,s.protocolPrepended=!1,s.urlMatchType=t.urlMatchType,s.url=t.url,s.protocolRelativeMatch=t.protocolRelativeMatch,s.stripPrefix=t.stripPrefix,s.stripTrailingSlash=t.stripTrailingSlash,s.decodePercentEncoding=t.decodePercentEncoding,s}return Ct(t,e),t.prototype.getType=function(){return"url"},t.prototype.getUrlMatchType=function(){return this.urlMatchType},t.prototype.getUrl=function(){var e=this.url;return this.protocolRelativeMatch||"scheme"===this.urlMatchType||this.protocolPrepended||(e=this.url="http://"+e,this.protocolPrepended=!0),e},t.prototype.getAnchorHref=function(){return this.getUrl().replace(/&/g,"&")},t.prototype.getAnchorText=function(){var e,t=this.getMatchedText();return this.protocolRelativeMatch&&(t=t.replace(rs,"")),this.stripPrefix.scheme&&(t=t.replace(Ft,"")),this.stripPrefix.www&&(t=(e=t).includes("www.")?e.replace(ns,"$1"):e),this.stripTrailingSlash&&(t=function(e){return"/"===e.charAt(e.length-1)&&(e=e.slice(0,-1)),e}(t)),this.decodePercentEncoding&&(t=function(e){var t=e.replace(/%(?:22|26|27|3C|3E)/gi,function(e){return"%22"===e?""":"%26"===e?"&":"%27"===e?"'":"%3C"===e||"%3c"===e?"<":">"});if(t.includes("%"))try{return decodeURIComponent(t)}catch(s){}return t}(t)),t},t}(Dt),as=/^mailto:/i,os=$t;function ls(e){return os(e)||((t=e)<47?t<42?33==t||t>=35&&t<=39:t>=42&&t<=43||45==t:t<63?47==t||61==t:t<94?63==t:t>=94&&t<=96||t>=123&&t<=126);var t}var cs=function(e){function t(t){var s=e.call(this,t)||this;return s.type="email",s.email="",s.email=t.email,s}return Ct(t,e),t.prototype.getType=function(){return"email"},t.prototype.getEmail=function(){return this.email},t.prototype.getAnchorHref=function(){return"mailto:"+this.email},t.prototype.getAnchorText=function(){return this.email},t}(Dt);function us(e){return 95===e||$t(e)}var ds=["twitter","facebook","instagram","tiktok","youtube"],hs=function(e){function t(t){var s=e.call(this,t)||this;return s.type="hashtag",s.serviceName="twitter",s.hashtag="",s.serviceName=t.serviceName,s.hashtag=t.hashtag,s}return Ct(t,e),t.prototype.getType=function(){return"hashtag"},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getHashtag=function(){return this.hashtag},t.prototype.getAnchorHref=function(){var e=this.serviceName,t=this.hashtag;switch(e){case"twitter":return"https://twitter.com/hashtag/"+t;case"facebook":return"https://www.facebook.com/hashtag/"+t;case"instagram":return"https://instagram.com/explore/tags/"+t;case"tiktok":return"https://www.tiktok.com/tag/"+t;case"youtube":return"https://youtube.com/hashtag/"+t;default:Et(e)}},t.prototype.getAnchorText=function(){return"#"+this.hashtag},t.prototype.getCssClassSuffixes=function(){var t=e.prototype.getCssClassSuffixes.call(this),s=this.getServiceName();return s&&t.push(s),t},t}(Dt),ps={twitter:/^@\w{1,15}$/,instagram:/^@[_\w]{1,30}$/,soundcloud:/^@[-a-z0-9_]{3,25}$/,tiktok:/^@[.\w]{1,23}[\w]$/,youtube:/^@[-.·\w]{3,30}$/};function fs(e){return 45===e||46===e||95===e||Ot(e)||Pt(e)}var gs=["twitter","instagram","soundcloud","tiktok","youtube"],ms=function(e){function t(t){var s=e.call(this,t)||this;return s.type="mention",s.serviceName="twitter",s.mention="",s.mention=t.mention,s.serviceName=t.serviceName,s}return Ct(t,e),t.prototype.getType=function(){return"mention"},t.prototype.getMention=function(){return this.mention},t.prototype.getServiceName=function(){return this.serviceName},t.prototype.getAnchorHref=function(){switch(this.serviceName){case"twitter":return"https://twitter.com/"+this.mention;case"instagram":return"https://instagram.com/"+this.mention;case"soundcloud":return"https://soundcloud.com/"+this.mention;case"tiktok":return"https://www.tiktok.com/@"+this.mention;case"youtube":return"https://youtube.com/@"+this.mention;default:Et(this.serviceName)}},t.prototype.getAnchorText=function(){return"@"+this.mention},t.prototype.getCssClassSuffixes=function(){var t=e.prototype.getCssClassSuffixes.call(this),s=this.getServiceName();return s&&t.push(s),t},t}(Dt),vs=/[-. ()]/,ys=new RegExp("^".concat(/(?:(?:(?:(\+)?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-. ]?(?:\d[-. ]?){6,12}\d+))([,;]+[0-9]+#?)*/.source,"|").concat(/(0([1-9]-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/.source,"$"));function bs(e){return 45===e||46===e||32===e}function ws(e){return 44===e||59===e}var ks=function(e){function t(t){var s=e.call(this,t)||this;return s.type="phone",s.number="",s.plusSign=!1,s.number=t.number,s.plusSign=t.plusSign,s}return Ct(t,e),t.prototype.getType=function(){return"phone"},t.prototype.getPhoneNumber=function(){return this.number},t.prototype.getNumber=function(){return this.getPhoneNumber()},t.prototype.getAnchorHref=function(){return"tel:"+(this.plusSign?"+":"")+this.number},t.prototype.getAnchorText=function(){return this.matchedText},t}(Dt),Cs=function(){function e(e,t){this.charIdx=0,this.matches=[],this._stateMachines=[],this.schemeUrlMachinesCount=0,this.text=e,this.tagBuilder=t.tagBuilder,this.stripPrefix=t.stripPrefix,this.stripTrailingSlash=t.stripTrailingSlash,this.decodePercentEncoding=t.decodePercentEncoding,this.hashtagServiceName=t.hashtagServiceName,this.mentionServiceName=t.mentionServiceName}return Object.defineProperty(e.prototype,"stateMachines",{get:function(){return this._stateMachines},enumerable:!1,configurable:!0}),e.prototype.addMachine=function(e){this._stateMachines.push(e),bn(e)&&this.schemeUrlMachinesCount++},e.prototype.removeMachine=function(e){this._stateMachines=this._stateMachines.filter(function(t){return t!==e}),bn(e)&&this.schemeUrlMachinesCount--},e.prototype.hasSchemeUrlMachine=function(){return this.schemeUrlMachinesCount>0},e}();function Ss(e,t,s){var n=e.charIdx;if(35===s)e.addMachine({type:2,startIdx:n,state:28,acceptStateReached:!1});else if(64===s)e.addMachine(function(e){return{type:3,startIdx:e,state:30,acceptStateReached:!1}}(n));else if(47===s)e.addMachine(vn(n,11));else if(43===s)e.addMachine(yn(n,37));else if(40===s)e.addMachine(yn(n,32));else{if(Pt(s)&&(e.addMachine(yn(n,38)),e.addMachine(function(e){return{type:0,startIdx:e,state:13,acceptStateReached:!1,matchType:2,octetsEncountered:1}}(n))),os(s)){var r="m"===t.toLowerCase()?15:22;e.addMachine(function(e,t){return{type:1,startIdx:e,state:t,acceptStateReached:!1}}(n,r))}Yt(s)&&e.addMachine(mn(n,0)),$t(s)&&e.addMachine(vn(n,5))}}function Is(e,t,s){58===s?t.state=2:45===s?t.state=1:Vt(s)||e.removeMachine(t)}function Ts(e,t,s){var n=e.charIdx;45===s||(47===s?(e.removeMachine(t),e.addMachine(vn(n,11))):Vt(s)?t.state=0:e.removeMachine(t))}function xs(e,t,s){var n=e.charIdx;47===s?t.state=3:46===s?e.removeMachine(t):Qt(s)?(t.state=5,Yt(s)&&e.addMachine(mn(n,0))):e.removeMachine(t)}function Es(e,t,s){47===s?t.state=4:Zt(s)?(t.state=10,t.acceptStateReached=!0):pn(e,t)}function Ms(e,t,s,n){47===n?(t.state=10,t.acceptStateReached=!0):Qt(n)?(t.state=5,t.acceptStateReached=!0):e.removeMachine(t)}function Rs(e,t,s){47===s?t.state=12:e.removeMachine(t)}function As(e,t,s){Qt(s)?t.state=5:e.removeMachine(t)}function _s(e,t,s){46===s?t.state=7:45===s?t.state=6:58===s?t.state=8:Xt(s)?t.state=10:Kt(s)||pn(e,t)}function Ns(e,t,s,n){45===n||(46===n?pn(e,t):Qt(n)?t.state=5:pn(e,t))}function Ds(e,t,s,n){46===n?pn(e,t):Qt(n)?(t.state=5,t.acceptStateReached=!0):pn(e,t)}function Os(e,t,s){46===s?t.state=14:58===s?t.state=8:Pt(s)||(Xt(s)?t.state=10:$t(s)?e.removeMachine(t):pn(e,t))}function Ps(e,t,s){Pt(s)?(t.octetsEncountered++,4===t.octetsEncountered&&(t.acceptStateReached=!0),t.state=13):pn(e,t)}function js(e,t,s){Pt(s)?t.state=9:pn(e,t)}function Us(e,t,s){Pt(s)||(Xt(s)?t.state=10:pn(e,t))}function $s(e,t,s){Zt(s)||pn(e,t)}function Ws(e,t,s,n){"a"===s.toLowerCase()?t.state=16:zs(e,t,n)}function qs(e,t,s,n){"i"===s.toLowerCase()?t.state=17:zs(e,t,n)}function Ls(e,t,s,n){"l"===s.toLowerCase()?t.state=18:zs(e,t,n)}function Bs(e,t,s,n){"t"===s.toLowerCase()?t.state=19:zs(e,t,n)}function Gs(e,t,s,n){"o"===s.toLowerCase()?t.state=20:zs(e,t,n)}function Fs(e,t,s){58===s?t.state=21:zs(e,t,s)}function Hs(e,t,s){ls(s)?t.state=22:e.removeMachine(t)}function zs(e,t,s){46===s?t.state=23:64===s?t.state=24:ls(s)?t.state=22:e.removeMachine(t)}function Js(e,t,s){46===s||64===s?e.removeMachine(t):ls(s)?t.state=22:e.removeMachine(t)}function Ys(e,t,s){Qt(s)?t.state=25:e.removeMachine(t)}function Vs(e,t,s){46===s?t.state=27:45===s?t.state=26:Kt(s)||pn(e,t)}function Qs(e,t,s){45===s||46===s?pn(e,t):Kt(s)?t.state=25:pn(e,t)}function Ks(e,t,s){46===s||45===s?pn(e,t):Qt(s)?(t.state=25,t.acceptStateReached=!0):pn(e,t)}function Zs(e,t,s){us(s)?(t.state=29,t.acceptStateReached=!0):e.removeMachine(t)}function Xs(e,t,s){us(s)||pn(e,t)}function en(e,t,s){fs(s)?(t.state=31,t.acceptStateReached=!0):e.removeMachine(t)}function tn(e,t,s){fs(s)||($t(s)?e.removeMachine(t):pn(e,t))}function sn(e,t,s,n){Pt(n)?t.state=38:(e.removeMachine(t),Ss(e,s,n))}function nn(e,t,s,n){Pt(n)?t.state=33:e.removeMachine(t),Ss(e,s,n)}function rn(e,t,s){Pt(s)?t.state=34:e.removeMachine(t)}function an(e,t,s){Pt(s)?t.state=35:e.removeMachine(t)}function on(e,t,s){41===s?t.state=36:e.removeMachine(t)}function ln(e,t,s,n){Pt(n)?t.state=38:bs(n)?t.state=39:e.removeMachine(t)}function cn(e,t,s,n){var r=e.charIdx;t.acceptStateReached=!0,ws(n)?t.state=40:35===n?t.state=41:Pt(n)||(40===n?t.state=32:bs(n)?t.state=39:(pn(e,t),Yt(n)&&e.addMachine(mn(r,0))))}function un(e,t,s,n){Pt(n)?t.state=38:40===n?t.state=32:(pn(e,t),Ss(e,s,n))}function dn(e,t,s){ws(s)||(35===s?t.state=41:Pt(s)?t.state=38:pn(e,t))}function hn(e,t,s){ws(s)?t.state=40:Pt(s)?e.removeMachine(t):pn(e,t)}function pn(e,t){var s,n=e.matches,r=e.text,i=e.charIdx,a=e.tagBuilder,o=e.stripPrefix,l=e.stripTrailingSlash,c=e.decodePercentEncoding,u=e.hashtagServiceName,d=e.mentionServiceName;if(e.removeMachine(t),t.acceptStateReached){var h,p,f=t.startIdx,g=r.slice(t.startIdx,i);switch(g=function(e){for(var t={"(":0,"{":0,"[":0},s=0;s<e.length;s++){var n=e.charAt(s);qt(i=e.charCodeAt(s))?t[n]++:Lt(i)&&t[gn[n]]--}for(var r=e.length-1;r>=0;){var i;if(n=e.charAt(r),Lt(i=e.charCodeAt(r))){var a=gn[n];if(!(t[a]<0))break;t[a]++,r--}else{if(!Wt(i))break;r--}}return e.slice(0,r+1)}(g),t.type){case 0:if(64===r.charCodeAt(t.startIdx-1))return;switch(t.matchType){case 0:var m=Gt.exec(g);if(m&&(f+=m.index,g=g.slice(m.index)),!function(e){if(Ht.test(e))return!1;var t=e.match(zt);if(!t)return!1;var s=!!t[1],n=t[2];return!!s||!(-1===n.indexOf(".")||!/[A-Za-z]/.test(n))}(g))return;break;case 1:if(!function(e){var t=e.match(Jt);if(!t)return!1;var s=t[0].split(".");return!(s.length<2||!es(s[s.length-1]))}(g))return;break;case 2:if(p=g.split(ss,1)[0],!ts.test(p))return;break;default:Et(t)}n.push(new is({tagBuilder:a,matchedText:g,offset:f,urlMatchType:fn(t.matchType),url:g,protocolRelativeMatch:"//"===g.slice(0,2),stripPrefix:o,stripTrailingSlash:l,decodePercentEncoding:c}));break;case 1:es(g.split(".").pop())&&n.push(new cs({tagBuilder:a,matchedText:g,offset:f,email:g.replace(as,"")}));break;case 2:g.length<=140&&n.push(new hs({tagBuilder:a,matchedText:g,offset:f,serviceName:u,hashtag:g.slice(1)}));break;case 3:s=g,ps[d].test(s)&&n.push(new ms({tagBuilder:a,matchedText:g,offset:f,serviceName:d,mention:g.slice(1)}));break;case 4:if(("+"===(h=g=g.replace(/ +$/g,"")).charAt(0)||vs.test(h))&&ys.test(h)){var v=g.replace(/[^0-9,;#]/g,"");n.push(new ks({tagBuilder:a,matchedText:g,offset:f,number:v,plusSign:"+"===g.charAt(0)}))}break;default:Et(t)}}}function fn(e){switch(e){case 0:return"scheme";case 1:return"tld";case 2:return"ipV4";default:Et(e)}}var gn={")":"(","}":"{","]":"["};function mn(e,t){return{type:0,startIdx:e,state:t,acceptStateReached:!1,matchType:0}}function vn(e,t){return{type:0,startIdx:e,state:t,acceptStateReached:!1,matchType:1}}function yn(e,t){return{type:4,startIdx:e,state:t,acceptStateReached:!1}}function bn(e){return 0===e.type&&0===e.matchType}var wn=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.type=e.type||"tag",this.name=e.name||"",this.isOpening=!!e.isOpening,this.isClosing=!!e.isClosing},kn=new wn,Cn=function(e,t){this.charIdx=0,this.state=0,this.currentDataIdx=0,this.currentTag=kn,this.html=e,this.callbacks=t};function Sn(e,t){"<"===t&&Hn(e)}function In(e,t,s){"!"===t?e.state=13:"/"===t?(e.state=2,e.currentTag=new wn(St(St({},e.currentTag),{isClosing:!0}))):"<"===t?Hn(e):Ot(s)?(e.state=3,e.currentTag=new wn(St(St({},e.currentTag),{isOpening:!0}))):(e.state=0,e.currentTag=kn)}function Tn(e,t,s){Ut(s)?(e.currentTag=new wn(St(St({},e.currentTag),{name:Jn(e)})),e.state=4):"<"===t?Hn(e):"/"===t?(e.currentTag=new wn(St(St({},e.currentTag),{name:Jn(e)})),e.state=12):">"===t?(e.currentTag=new wn(St(St({},e.currentTag),{name:Jn(e)})),zn(e)):Ot(s)||Pt(s)||":"===t||Fn(e)}function xn(e,t,s){">"===t?Fn(e):Ot(s)?e.state=3:Fn(e)}function En(e,t,s){var n;Ut(s)||("/"===t?e.state=12:">"===t?zn(e):"<"===t?Hn(e):"="===t||jt(s)||(n=s)>=0&&n<=31||127==n?Fn(e):e.state=5)}function Mn(e,t,s){Ut(s)?e.state=6:"/"===t?e.state=12:"="===t?e.state=7:">"===t?zn(e):"<"===t?Hn(e):jt(s)&&Fn(e)}function Rn(e,t,s){Ut(s)||("/"===t?e.state=12:"="===t?e.state=7:">"===t?zn(e):"<"===t?Hn(e):jt(s)?Fn(e):e.state=5)}function An(e,t,s){Ut(s)||('"'===t?e.state=8:"'"===t?e.state=9:/[>=`]/.test(t)?Fn(e):"<"===t?Hn(e):e.state=10)}function _n(e,t){'"'===t&&(e.state=11)}function Nn(e,t){"'"===t&&(e.state=11)}function Dn(e,t,s){Ut(s)?e.state=4:">"===t?zn(e):"<"===t&&Hn(e)}function On(e,t,s){Ut(s)?e.state=4:"/"===t?e.state=12:">"===t?zn(e):"<"===t?Hn(e):(e.state=4,e.charIdx--)}function Pn(e,t){">"===t?(e.currentTag=new wn(St(St({},e.currentTag),{isClosing:!0})),zn(e)):Fn(e)}function jn(e){var t=e.html,s=e.charIdx;"--"===t.slice(s,s+2)?(e.charIdx++,e.currentTag=new wn(St(St({},e.currentTag),{type:"comment"})),e.state=14):"DOCTYPE"===t.slice(s,s+7).toUpperCase()?(e.charIdx+=6,e.currentTag=new wn(St(St({},e.currentTag),{type:"doctype"})),e.state=20):Fn(e)}function Un(e,t){"-"===t?e.state=15:">"===t?Fn(e):e.state=16}function $n(e,t){"-"===t?e.state=18:">"===t?Fn(e):e.state=16}function Wn(e,t){"-"===t&&(e.state=17)}function qn(e,t){e.state="-"===t?18:16}function Ln(e,t){">"===t?zn(e):"!"===t?e.state=19:"-"===t||(e.state=16)}function Bn(e,t){"-"===t?e.state=17:">"===t?zn(e):e.state=16}function Gn(e,t){">"===t?zn(e):"<"===t&&Hn(e)}function Fn(e){e.state=0,e.currentTag=kn}function Hn(e){e.state=1,e.currentTag=new wn({idx:e.charIdx})}function zn(e){var t=e.html.slice(e.currentDataIdx,e.currentTag.idx);t&&e.callbacks.onText(t,e.currentDataIdx);var s=e.currentTag;"comment"===s.type?e.callbacks.onComment(s.idx):"doctype"===s.type?e.callbacks.onDoctype(s.idx):(s.isOpening&&e.callbacks.onOpenTag(s.name,s.idx),s.isClosing&&e.callbacks.onCloseTag(s.name,s.idx)),Fn(e),e.currentDataIdx=e.charIdx+1}function Jn(e){var t=e.currentTag.idx+(e.currentTag.isClosing?2:1);return e.html.slice(t,e.charIdx).toLowerCase()}var Yn=function(){function e(t){var s;void 0===t&&(t={}),this.version=e.version,this.urls={},this.email=!0,this.phone=!0,this.hashtag=!1,this.mention=!1,this.newWindow=!0,this.stripPrefix={scheme:!0,www:!0},this.stripTrailingSlash=!0,this.decodePercentEncoding=!0,this.truncate={length:0,location:"end"},this.className="",this.replaceFn=null,this.context=void 0,this.sanitizeHtml=!1,this.tagBuilder=null,this.urls=(null==(s=t.urls)&&(s=!0),Tt(s)?{schemeMatches:s,tldMatches:s,ipV4Matches:s}:{schemeMatches:!Tt(s.schemeMatches)||s.schemeMatches,tldMatches:!Tt(s.tldMatches)||s.tldMatches,ipV4Matches:!Tt(s.ipV4Matches)||s.ipV4Matches}),this.email=Tt(t.email)?t.email:this.email,this.phone=Tt(t.phone)?t.phone:this.phone,this.hashtag=t.hashtag||this.hashtag,this.mention=t.mention||this.mention,this.newWindow=Tt(t.newWindow)?t.newWindow:this.newWindow,this.stripPrefix=function(e){return null==e&&(e=!0),Tt(e)?{scheme:e,www:e}:{scheme:!Tt(e.scheme)||e.scheme,www:!Tt(e.www)||e.www}}(t.stripPrefix),this.stripTrailingSlash=Tt(t.stripTrailingSlash)?t.stripTrailingSlash:this.stripTrailingSlash,this.decodePercentEncoding=Tt(t.decodePercentEncoding)?t.decodePercentEncoding:this.decodePercentEncoding,this.sanitizeHtml=t.sanitizeHtml||!1;var n=this.mention;if(!1!==n&&-1===gs.indexOf(n))throw new Error("invalid `mention` cfg '".concat(n,"' - see docs"));var r,i=this.hashtag;if(!1!==i&&-1===ds.indexOf(i))throw new Error("invalid `hashtag` cfg '".concat(i,"' - see docs"));this.truncate="number"==typeof(r=t.truncate)?{length:r,location:"end"}:St({length:Number.POSITIVE_INFINITY,location:"end"},r),this.className=t.className||this.className,this.replaceFn=t.replaceFn||this.replaceFn,this.context=t.context||this}return e.link=function(t,s){return new e(s).link(t)},e.parse=function(t,s){return new e(s).parse(t)},e.prototype.parse=function(e){var t=this,s=["a","style","script"],n=0,r=[];return function(e,t){for(var s=new Cn(e,t),n=e.length;s.charIdx<n;){var r=e.charAt(s.charIdx),i=e.charCodeAt(s.charIdx);switch(s.state){case 0:Sn(s,r);break;case 1:In(s,r,i);break;case 2:xn(s,r,i);break;case 3:Tn(s,r,i);break;case 4:En(s,r,i);break;case 5:Mn(s,r,i);break;case 6:Rn(s,r,i);break;case 7:An(s,r,i);break;case 8:_n(s,r);break;case 9:Nn(s,r);break;case 10:Dn(s,r,i);break;case 11:On(s,r,i);break;case 12:Pn(s,r);break;case 13:jn(s);break;case 14:Un(s,r);break;case 15:$n(s,r);break;case 16:Wn(s,r);break;case 17:qn(s,r);break;case 18:Ln(s,r);break;case 19:Bn(s,r);break;case 20:Gn(s,r);break;default:Et(s.state)}s.charIdx++}var a,o;s.currentDataIdx<s.charIdx&&(o=(a=s).html.slice(a.currentDataIdx,a.charIdx),a.callbacks.onText(o,a.currentDataIdx),a.currentDataIdx=a.charIdx+1)}(e,{onOpenTag:function(e){s.indexOf(e)>=0&&n++},onText:function(e,s){if(0===n){var i=e.split(/( | |<|<|>|>|"|"|')/gi),a=s;i.forEach(function(e,s){if(s%2==0){var n=t.parseText(e,a);r.push.apply(r,function(e,t,s){if(s||2===arguments.length)for(var n,r=0,i=t.length;r<i;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}([],function(e,t){var s="function"==typeof Symbol&&e[Symbol.iterator];if(!s)return e;var n,r,i=s.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(o){r={error:o}}finally{try{n&&!n.done&&(s=i.return)&&s.call(i)}finally{if(r)throw r.error}}return a}(n),!1))}a+=e.length})}},onCloseTag:function(e){s.indexOf(e)>=0&&(n=Math.max(n-1,0))},onComment:function(){},onDoctype:function(){}}),r=this.compactMatches(r),r=this.removeUnwantedMatches(r)},e.prototype.compactMatches=function(e){e.sort(Vn);for(var t=0;t<e.length-1;){var s=e[t],n=s.getOffset(),r=s.getMatchedText().length;if(t+1<e.length&&e[t+1].getOffset()===n){var i=e[t+1].getMatchedText().length>r?t:t+1;e.splice(i,1)}else t++}return e},e.prototype.removeUnwantedMatches=function(e){return this.hashtag||xt(e,function(e){return"hashtag"===e.getType()}),this.email||xt(e,function(e){return"email"===e.getType()}),this.phone||xt(e,function(e){return"phone"===e.getType()}),this.mention||xt(e,function(e){return"mention"===e.getType()}),this.urls.schemeMatches||xt(e,function(e){return"url"===e.getType()&&"scheme"===e.getUrlMatchType()}),this.urls.tldMatches||xt(e,function(e){return"url"===e.getType()&&"tld"===e.getUrlMatchType()}),this.urls.ipV4Matches||xt(e,function(e){return"url"===e.getType()&&"ipV4"===e.getUrlMatchType()}),e},e.prototype.parseText=function(e,t){t=t||0;for(var s=function(e,t){for(var s=new Cs(e,t);s.charIdx<s.text.length;s.charIdx++){var n=e.charAt(s.charIdx),r=e.charCodeAt(s.charIdx);if(0===s.stateMachines.length)Ss(s,n,r);else{for(var i=s.stateMachines.length-1;i>=0;i--){var a=s.stateMachines[i];switch(a.state){case 11:Rs(s,a,r);break;case 12:As(s,a,r);break;case 0:Is(s,a,r);break;case 1:Ts(s,a,r);break;case 2:xs(s,a,r);break;case 3:Es(s,a,r);break;case 4:Ms(s,a,0,r);break;case 5:_s(s,a,r);break;case 6:Ns(s,a,0,r);break;case 7:Ds(s,a,0,r);break;case 13:Os(s,a,r);break;case 14:Ps(s,a,r);break;case 8:js(s,a,r);break;case 9:Us(s,a,r);break;case 10:$s(s,a,r);break;case 15:Ws(s,a,n,r);break;case 16:qs(s,a,n,r);break;case 17:Ls(s,a,n,r);break;case 18:Bs(s,a,n,r);break;case 19:Gs(s,a,n,r);break;case 20:Fs(s,a,r);break;case 21:Hs(s,a,r);break;case 22:zs(s,a,r);break;case 23:Js(s,a,r);break;case 24:Ys(s,a,r);break;case 25:Vs(s,a,r);break;case 26:Qs(s,a,r);break;case 27:Ks(s,a,r);break;case 28:Zs(s,a,r);break;case 29:Xs(s,a,r);break;case 30:en(s,a,r);break;case 31:tn(s,a,r);break;case 32:nn(s,a,n,r);break;case 33:rn(s,a,r);break;case 34:an(s,a,r);break;case 35:on(s,a,r);break;case 36:ln(s,a,0,r);break;case 37:sn(s,a,n,r);break;case 38:cn(s,a,0,r);break;case 39:un(s,a,n,r);break;case 40:dn(s,a,r);break;case 41:hn(s,a,r);break;default:Et(a.state)}}if(!s.hasSchemeUrlMachine()&&s.charIdx>0&&Yt(r)){var o=s.text.charCodeAt(s.charIdx-1);Yt(o)||s.addMachine(mn(s.charIdx,0))}}}for(var l=s.stateMachines.length-1;l>=0;l--)s.stateMachines.forEach(function(e){return pn(s,e)});return s.matches}(e,{tagBuilder:this.getTagBuilder(),stripPrefix:this.stripPrefix,stripTrailingSlash:this.stripTrailingSlash,decodePercentEncoding:this.decodePercentEncoding,hashtagServiceName:this.hashtag,mentionServiceName:this.mention||"twitter"}),n=0,r=s.length;n<r;n++)s[n].setOffset(t+s[n].getOffset());return s},e.prototype.link=function(e){if(!e)return"";this.sanitizeHtml&&(e=e.replace(/</g,"<").replace(/>/g,">"));for(var t=this.parse(e),s=new Array(2*t.length+1),n=0,r=0,i=t.length;r<i;r++){var a=t[r];s.push(e.substring(n,a.getOffset())),s.push(this.createMatchReturnVal(a)),n=a.getOffset()+a.getMatchedText().length}return s.push(e.substring(n)),s.join("")},e.prototype.createMatchReturnVal=function(e){var t;return this.replaceFn&&(t=this.replaceFn.call(this.context,e)),"string"==typeof t?t:!1===t?e.getMatchedText():t instanceof Rt?t.toAnchorString():e.buildTag().toAnchorString()},e.prototype.getTagBuilder=function(){var e=this.tagBuilder;return e||(e=this.tagBuilder=new Nt({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),e},e.version="4.1.5",e}();function Vn(e,t){return e.getOffset()-t.getOffset()}function Qn(e,t=e){return{type:"autolink",url:e,text:t}}const Kn=ht(/<!!mention:([^>\s]*?)\|(.*?)>/gm,([e,t,s])=>function(e,t){return{type:"mention",id:e,text:t}}(decodeURIComponent(t),s)),Zn=ht(/<!!customemoji:(.*?)>/gm,([e,t])=>function(e){return{type:"customemoji",text:e}}(t)),Xn=ht(/<((?:https?|mailto):.*?)\|(.*?)>/gi,([e,t,s])=>function(e,t=[]){return{type:"link",url:e,children:t}}(t,[s])),er=ht(/<actionlink:([^|]+)[|]([^>]*)>/gi,([e,t,s])=>{const{action:n,params:r}=sr(t);return function(e,t,s=[]){return{type:"actionlink",action:e,params:t,children:s}}(n,r,[s])}),tr=ht(/<actionbutton:([^|]+)[|]([^>]*)>/gi,([e,t,s])=>{const{action:n,params:r}=sr(t);return function(e,t,s=[]){return{type:"actionbutton",action:e,params:t,children:s}}(n,r,[s])});function sr(e){const t=e.indexOf("?");return-1===t?{action:e,params:{}}:{action:e.slice(0,t),params:Object.fromEntries(new URLSearchParams(e.slice(t)))}}const nr=ht(/(?:^|\n)(?:\s*[-*+]\s+[^\n]+(?:\n|$))+/g,([e])=>function(e=[]){return{type:"bulletlist",children:e}}([e.startsWith("\n")?e.slice(1):e])),rr=ht(/^\s*[-*+]\s+([^\n]+)(?:\n|$)/gm,([e,t])=>({type:"bulletpoint",children:[t]})),ir=e=>{const t=/(?:^|[^-:/\w])([(+]?[0-9](?:[-_+ ().]?[0-9]){5,11}[0-9])(?:[^-:/\w]|$)/g,s=/^(\d{4})-(\d{4})$/;let n=0;const r=[];for(const i of Ce(e,t)){const t=i[0],a=i[1],o=a.match(s);if(o&&Number(o[1])<Number(o[2]))continue;const l=t.startsWith(a)?i.index:i.index+1;l-n>0&&r.push(e.substring(n,l));const c=Qn("tel:"+a.replace(/[^0-9+]/g,""),a);r.push(c),n=l+a.length}return n<e.length&&r.push(e.substring(n)),r},ar=e=>Xn(e).flatMap(e=>"string"==typeof e?or(e):["<",...or(e.url),...or("|"+e.children[0]+">")]),or=e=>{const t=Yn.parse(e,{urls:!0,email:!0,phone:!1,hashtag:!1,mention:!1}),s=[];let n=0;for(const r of t){const t=r.getOffset(),i=r.getMatchedText(),a=i.length;let o=i;r instanceof cs?o="mailto:"+r.getEmail():r instanceof is&&(o=r.getUrl()),t>n&&s.push(e.substring(n,t)),s.push(Qn(o,i)),n=t+a}return n<e.length&&s.push(e.substring(n)),s},lr=["Codeblock","Codespan","FormattedLink","Wikitext","Autolink","Actions","Mention","Mention","BulletPoint","CustomEmoji"];const cr=function(){const e=RegExp("[^\n]+\n?|\n","g");return t=>Array.from(t.match(e)||[])}();function ur(e,t={except:[]}){let s=function(e,t){let s=[e];return s=hr(s,t.multilineSteps),s=hr(s,[cr]),s=hr(s,t.singlelineSteps),s=pr(s),s}(e,function(e={except:[]}){var t;const s={multilineSteps:[],singlelineSteps:[]},n=null!=(t=e.except)?t:lr.filter(t=>!e.only.includes(t));return n.includes("BulletPoint")||s.multilineSteps.push(nr,rr),n.includes("Mention")||s.singlelineSteps.push(Kn),n.includes("CustomEmoji")||s.singlelineSteps.push(Zn),n.includes("Codespan")||s.multilineSteps.push(ht(/```([^]+?)```/g,([e,t])=>({type:"codespan",text:t.replace(/<!!mention:.*?\|([^>]*)>/gim,"@$1").replace(/<!!customemoji:(.*?)>/gim,"$1")}))),n.includes("FormattedLink")||s.singlelineSteps.push(Xn),n.includes("Actions")||(s.singlelineSteps.push(er),s.singlelineSteps.push(tr)),n.includes("Wikitext")||s.singlelineSteps.push(yt),n.includes("Autolink")||s.singlelineSteps.push(ar,ir),s}(t));return s=fr(s,!1),s}function dr(e){return ur(e,{except:["FormattedLink","Actions"]})}function hr(e,t){return t.reduce((e,t)=>dt(e,t),e)}function pr(e){const t=[];let s=-1;for(const n of e)"string"==typeof n?"string"==typeof t[s]?t[s]+=n:t[++s]=n:t[++s]="children"in n?p(h({},n),{children:pr(n.children)}):n;return t}function fr(e,t){const s=[];let n=[];for(let r=0;r<e.length;r++){const i=e[r];if("string"==typeof i)n.push(i);else if("children"in i){n.length>0&&(s.push(n.join("")),n=[]);const e=fr(i.children,t||"link"===i.type||"actionbutton"===i.type||"actionlink"===i.type);s.push(p(h({},i),{children:e}))}else"autolink"===i.type&&t?n.push(i.text):(n.length>0&&(s.push(n.join("")),n=[]),s.push(i))}return n.length>0&&(s.push(n.join("")),n=[]),s}function gr(e,t,s){return e.primary<t.primary?"ASC"===s.primaryOrder?"before":"after":e.primary>t.primary?"ASC"===s.primaryOrder?"after":"before":e.secondary<t.secondary?"ASC"===s.secondaryOrder?"before":"after":e.secondary>t.secondary?"ASC"===s.secondaryOrder?"after":"before":"equal"}function mr(e,t){return t>=e.length?e:Q(e.slice(0,t))}class vr{constructor(e,t,s,n,r){this._onSnapshot=t,this._pageSize=s,this._maxPageSize=n,this._sort=r,this._windowStatus=void 0,this._loadMoreDeferred=void 0,this._connectedDefer=A(),this._connectedDefer.promise.catch(()=>{}),this._underlyingSubscription=e(this.handleSnapshot.bind(this)),this._underlyingSubscription.connected.catch(e=>this._connectedDefer.reject(e))}updateWindowStatusAndGetState(e,t){var s,n;if(null===e){const s={type:"active",latestSnapshot:e,loadedAll:t};return this._windowStatus=void 0,s}if(0===e.length){const s={type:"active",latestSnapshot:e,loadedAll:t};return this._windowStatus&&(this._windowStatus.lastState=s),s}if(void 0===this._windowStatus){const s=mr(e,this._pageSize),n=s[s.length-1],r=this._sort.getSortPointer(n),i=t?0:this._pageSize-s.length,a={type:"active",latestSnapshot:s,loadedAll:t&&e===s};return this._windowStatus={endPoint:r,loadingMore:i,lastState:a},a}const r=function(e,t,s,n){if(0===e.length)return 0;var r,i;r=t,i=e.length-1;const a=t=>{const r=e[t];return"after"===gr(s.getSortPointer(r),n,s)};if(a(t=Math.max(0,Math.min(r,i)))){for(let e=t-1;e>=0;e--)if(!a(e))return e+1;return 0}for(let o=t+1;o<e.length;o++)if(a(o))return o;return e.length}(e,null!=(n=null==(s=this._windowStatus.lastState.latestSnapshot)?void 0:s.length)?n:this._pageSize,this._sort,this._windowStatus.endPoint),i=Math.min(r+this._windowStatus.loadingMore,e.length),a=function(e,t,s){if(e===t)return!1;if(null===e||null===t)return!0;if(e.length!==s)return!0;for(let n=0;n<s;n++)if(e[n]!==t[n])return!0;return!1}(this._windowStatus.lastState.latestSnapshot,e,i),o=t&&i===e.length,l=this._windowStatus.lastState.loadedAll!==o;if(!a&&!l)return this._windowStatus.lastState;const c=mr(e,i),u={type:"active",latestSnapshot:c,loadedAll:o};if(0===c.length)return u;const d=c.length-r,f=u.loadedAll?0:this._windowStatus.loadingMore-d;if(f===this._windowStatus.loadingMore)return this._windowStatus=p(h({},this._windowStatus),{lastState:u}),u;const g=c[c.length-1],m="after"===gr(v=this._sort.getSortPointer(g),y=this._windowStatus.endPoint,this._sort)?v:y;var v,y;return this._windowStatus={endPoint:m,loadingMore:f,lastState:u},u}handleSnapshot(e,t){var s,n;const r=null==(s=this._windowStatus)?void 0:s.lastState,i=this.updateWindowStatusAndGetState(e,t);if(this._connectedDefer.resolve(i),i!==r&&(null==(n=this._onSnapshot)||n.call(this,i.latestSnapshot,i.loadedAll)),this._loadMoreDeferred&&void 0===this._windowStatus&&(this._loadMoreDeferred.resolve(),this._loadMoreDeferred=void 0),this._loadMoreDeferred&&this._windowStatus&&this._windowStatus.loadingMore<=0&&(this._loadMoreDeferred.resolve(),this._loadMoreDeferred=void 0),this._windowStatus&&this._windowStatus.loadingMore>0){const e=this._windowStatus.loadingMore;setTimeout(()=>this._underlyingSubscription.loadMore(e))}}get state(){const e=this._underlyingSubscription.state;return"active"===e.type&&null!==e?this._windowStatus?this._windowStatus.lastState:this.updateWindowStatusAndGetState(e.latestSnapshot,e.loadedAll):e}get connected(){return this._connectedDefer.promise}get terminated(){return this._underlyingSubscription.terminated}loadMore(){return b(this,arguments,function*(e=this._pageSize){var t,s,n;if(e<=0||!Number.isInteger(e))throw new Error("Invalid count: must be a positive integer.");if(e>this._maxPageSize)throw new Error(`Invalid count: cannot load more than ${this._maxPageSize} items at once.`);if(void 0===this._windowStatus)return Promise.resolve();if("active"!==this._underlyingSubscription.state.type)return Promise.resolve();const r=this._underlyingSubscription.state.latestSnapshot;if(null===r)return Promise.resolve();const i=this._underlyingSubscription.state.loadedAll,a=this.updateWindowStatusAndGetState(r,i),o=r.length-a.latestSnapshot.length,l=i?o:Number.POSITIVE_INFINITY,c=Math.min(e,l);if(this._windowStatus.loadingMore=Math.max(this._windowStatus.loadingMore,c),o>0){const e=this._windowStatus.lastState,s=this.updateWindowStatusAndGetState(r,i);s!==e&&(null==(t=this._onSnapshot)||t.call(this,s.latestSnapshot,s.loadedAll))}if(this._windowStatus.loadingMore<=0)return null==(s=this._loadMoreDeferred)||s.resolve(),void(this._loadMoreDeferred=void 0);const u=null!=(n=this._loadMoreDeferred)?n:A();this._loadMoreDeferred=u,yield this._underlyingSubscription.loadMore(this._windowStatus.loadingMore),yield u.promise})}unsubscribe(){return this._underlyingSubscription.unsubscribe()}}class yr extends vr{constructor(e,t,s){super(s=>e.subscribe(["me","conversations",t,"messages"],s),s,30,100,{getSortPointer:e=>({primary:e.createdAt,secondary:e.id}),primaryOrder:"DESC",secondaryOrder:"ASC"})}}class br extends vr{constructor(e,t,s){super(s=>e.subscribe(["me","conversations",t,"participants"],s),s,10,50,{getSortPointer:e=>({primary:e.joinedAt,secondary:e.user.id}),primaryOrder:"DESC",secondaryOrder:"ASC"})}}class wr extends vr{constructor(e,t){super(t=>e.subscribe(["me","conversations"],t),t,20,30,{getSortPointer:e=>{var t,s;return{primary:null!=(s=null==(t=e.lastMessage)?void 0:t.createdAt)?s:e.createdAt,secondary:e.id}},primaryOrder:"DESC",secondaryOrder:"ASC"})}}class kr{constructor(e,t){this.id=e,this._realtimeClient=t,this.uselessObjForTypeCheck={subject:null,photoUrl:null,welcomeMessages:null,custom:null,access:null,notify:null}}get brandedId(){return this.id}get brandedUserId(){return this._realtimeClient.userId}participant(e){if("string"==typeof e){if(""===e)throw new Error(`Creating ParticipantRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.participant(this.brandedId,e)}if("brandedId"in e)return this._realtimeClient.refs.participant(this.brandedId,e.id);throw new Error(`Creating ParticipantRef failed because user "${e}" is not a string or a UserRef`)}message(e){if("string"!=typeof e)throw new Error(`Creating MessageRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating MessageRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.message(this.brandedId,e)}get(){return b(this,null,function*(){const e=this.subscribe(),t=yield e.connected.catch(()=>{throw new Error("GET Conversation failed, could not fetch conversation")});yield this._realtimeClient.sync();const s=e.state;if(e.unsubscribe(),"active"===s.type)return s.latestSnapshot;if("pending"===s.type)return t.latestSnapshot;if("unsubscribed"===s.type)return t.latestSnapshot;throw"error"===s.type?s.error:"Unreachable"})}set(e){return b(this,null,function*(){const t=this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedId],data:e}),s=this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedId,"participants",this.brandedUserId],data:e}),n=yield t;var r;!n.ok&&"server"===n.where&&403===n.value.status&&"UNAUTHORIZED_TO_EDIT"===n.value.errorCode&&(void 0===(r=e).subject&&void 0===r.photoUrl&&void 0===r.welcomeMessages&&null!==r.custom&&(void 0===r.custom||!Object.values(r.custom).some(e=>void 0!==e)))||U("Set conversation "+this.id,n);const i=yield s;!i.ok&&"server"===i.where&&403===i.value.status&&"UNAUTHORIZED_TO_EDIT_PARTICIPANT"===i.value.errorCode&&function(e){return void 0===e.access&&void 0===e.notify}(e)||U("Set your participation in conversation "+this.id,i)})}createIfNotExists(){return b(this,arguments,function*(e={}){const t=this._realtimeClient.call({method:"POST",path:["conversations",this.brandedId],data:e}),s=this._realtimeClient.call({method:"POST",path:["conversations",this.brandedId,"participants",this.brandedUserId],data:e}),n=yield t;(n.ok||"server"!==n.where||409!==n.value.status)&&U("Create conversation "+this.id,yield t);const r=yield s;(r.ok||"server"!==r.where||409!==r.value.status)&&U("Join conversation "+this.id,yield s)})}markAsRead(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"POST",path:["me","conversations",this.brandedId,"read"],data:{}});U(`Mark ${this.id} as read`,e)})}markAsUnread(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"POST",path:["me","conversations",this.brandedId,"unread"],data:{}});U(`Mark ${this.id} as unread`,e)})}send(e){return b(this,null,function*(){const t={content:Cr(e),referencedMessageId:Sr(e),custom:"string"==typeof e?void 0:e.custom,idempotencyKey:ut((new Date).getTime())},s=yield this._realtimeClient.call({method:"POST",path:["conversations",this.brandedId,"messages"],data:t}),n=U("Send message to conversation "+this.id,s);return this._realtimeClient.refs.message(this.brandedId,n.id)})}subscribeMessages(e){return new yr(this._realtimeClient,this.brandedId,e)}subscribeParticipants(e){return new br(this._realtimeClient,this.brandedId,e)}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId],e)}subscribeTyping(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"typing"],e)}markAsTyping(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"POST",path:["me","conversations",this.brandedId,"typing"],data:{}});U(`Set user as typing in ${this.id}`,e)})}}function Cr(e){return"string"==typeof e?[{type:"text",children:dr(e)}]:"text"in e?[{type:"text",children:dr(e.text)}]:e.content}function Sr(e){if("string"==typeof e)return;const t=e.referencedMessage;return void 0!==t?"string"==typeof t?t:t.id:void 0}class Ir{constructor(e,t,s){this.userId=e,this.conversationId=t,this._realtimeClient=s}get brandedUserId(){return this.userId}get brandedConversationId(){return this.conversationId}get(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"GET",path:["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],data:{}}),t=yield this._realtimeClient.call({method:"GET",path:["users",this.brandedUserId],data:{includePrivateFields:!1}}),[s,n]=yield Promise.all([e,t]);return(s.ok||"server"!==s.where||404!==s.value.status)&&(n.ok||"server"!==n.where||404!==n.value.status)?De(U(`Get participant ${this.userId} in conversation ${this.conversationId}`,s),Ne(U(`Get user ${this.userId}`,n))):null})}set(){return b(this,arguments,function*(e={}){const t=yield this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:e});U(`Set participant ${this.userId} in conversation ${this.conversationId}`,t)})}edit(){return b(this,arguments,function*(e={}){const t=yield this._realtimeClient.call({method:"PATCH",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:e});U(`Edit participant ${this.userId} in conversation ${this.conversationId}`,t)})}createIfNotExists(){return b(this,arguments,function*(e={}){const t=yield this._realtimeClient.call({method:"POST",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:e});(t.ok||"server"!==t.where||409!==t.value.status)&&U(`Add participant ${this.userId} to conversation ${this.conversationId}`,t)})}delete(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"DELETE",path:["conversations",this.brandedConversationId,"participants",this.brandedUserId],data:{}});(e.ok||"server"!==e.where||404!==e.value.status)&&U(`Remove participant ${this.userId} from conversation ${this.conversationId}`,e)})}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],e)}}class Tr{constructor(e,t,s){this.id=e,this.conversationId=t,this._realtimeClient=s}get brandedId(){return this.id}get brandedConversationId(){return this.conversationId}reactions(e){if("string"!=typeof e)throw new Error(`Creating ReactionsRef failed because emoji "${e}" is not a string`);if(""===e)throw new Error(`Creating ReactionsRef failed because emoji "${e}" is an empty string`);return this._realtimeClient.refs.reactions(this.brandedConversationId,this.brandedId,e)}reaction(e){return this.reactions(e)}get(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"GET",path:["me","conversations",this.brandedConversationId,"messages",this.brandedId],data:{}});if(!e.ok&&"server"===e.where&&404===e.value.status)return null;if(!e.ok&&"server"===e.where&&403===e.value.status&&"NOT_A_PARTICIPANT"===e.value.errorCode)return null;const t=U("Get message "+this.id,e),s=yield this._realtimeClient.hydrateMessageData(t,this.brandedConversationId);return Or("Get message "+this.id,s)})}edit(e){return b(this,null,function*(){const t={content:xr(e),custom:"string"==typeof e?void 0:e.custom},s=yield this._realtimeClient.call({method:"PATCH",path:["conversations",this.brandedConversationId,"messages",this.brandedId],data:t});U(`Edit message ${this.id} in conversation ${this.conversationId}`,s)})}delete(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"DELETE",path:["conversations",this.brandedConversationId,"messages",this.brandedId],data:{}});(e.ok||"server"!==e.where||404!==e.value.status)&&U(`Delete message ${this.id} in conversation ${this.conversationId}`,e)})}}function xr(e){return"string"==typeof e?[{type:"text",children:ur(e)}]:"text"in e&&e.text?[{type:"text",children:ur(e.text)}]:"content"in e&&e.content?e.content:void 0}class Er{constructor(e,t,s,n){this.emoji=e,this.messageId=t,this.conversationId=s,this._realtimeClient=n}get brandedMessageId(){return this.messageId}get brandedConversationId(){return this.conversationId}get brandedEmoji(){return this.emoji}add(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"PUT",path:["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.brandedEmoji,this._realtimeClient.userId],data:{}});U(`Add ${this.emoji} reaction on message ${this.messageId} in conversation ${this.conversationId}`,e)})}remove(){return b(this,null,function*(){const e=yield this._realtimeClient.call({method:"DELETE",path:["conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.brandedEmoji,this._realtimeClient.userId],data:{}});(e.ok||"server"!==e.where||404!==e.value.status)&&U(`Remove ${this.emoji} reaction from message ${this.messageId} in conversation ${this.conversationId}`,e)})}getFirstReactions(){return b(this,null,function*(){const e=this.subscribe(),{latestSnapshot:t}=yield e.connected;return e.unsubscribe(),t?t.slice(0,10):null})}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedConversationId,"messages",this.brandedMessageId,"reactions",this.brandedEmoji],e)}}const Mr="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}},Rr=globalThis.FinalizationRegistry,Ar=void 0!==Rr?Rr:class{constructor(e){}register(e,t,s){}unregister(e){}};class _r{constructor(e){this.client=e,this.userRefs=new Map,this.conversationRefs=new Map,this.participantRefs=new Map,this.messageRefs=new Map,this.reactionsRefs=new Map,this.registry=new Ar(({map:e,key:t})=>{e.delete(t)})}user(e){var t;const s=null==(t=this.userRefs.get(e))?void 0:t.deref();if(s)return s;const n=Q(new ct(e,this.client));return this.userRefs.set(e,new Mr(n)),this.registry.register(n,{map:this.userRefs,key:e}),n}conversation(e){var t;const s=null==(t=this.conversationRefs.get(e))?void 0:t.deref();if(s)return s;const n=Q(new kr(e,this.client));return this.conversationRefs.set(e,new Mr(n)),this.registry.register(n,{map:this.conversationRefs,key:e}),n}participant(e,t){var s;const n=`[${e}][${t}]`,r=null==(s=this.participantRefs.get(n))?void 0:s.deref();if(r)return r;const i=Q(new Ir(t,e,this.client));return this.participantRefs.set(n,new Mr(i)),this.registry.register(i,{map:this.participantRefs,key:n}),i}message(e,t){var s;const n=`[${e}][${t}]`,r=null==(s=this.messageRefs.get(n))?void 0:s.deref();if(r)return r;const i=Q(new Tr(t,e,this.client));return this.messageRefs.set(n,new Mr(i)),this.registry.register(i,{map:this.messageRefs,key:n}),i}reactions(e,t,s){var n;const r=`[${e}][${t}][${s}]`,i=null==(n=this.reactionsRefs.get(r))?void 0:n.deref();if(i)return i;const a=Q(new Er(s,t,e,this.client));return this.reactionsRefs.set(r,new Mr(a)),this.registry.register(a,{map:this.reactionsRefs,key:r}),a}}class Nr{constructor(e,t,s){this.userId=t,this.refs=new _r(this),this.alive=!0,this.connection=new lt(e,s,this),s.onTokenRefreshFailed(()=>{this.destroy()})}call(e){return b(this,null,function*(){return this.alive?this.connection.call(e):D("SESSION_DESTROYED")})}subscribe(e,t){return this.connection.subscribe(e,t)}internalSubscribe(e){const t=this.connection.getOrCreateStore(e);return{store:t,unsubscribe:t.registerInternalSubscription()}}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}sync(){return b(this,null,function*(){yield this.connection.sync()})}hydrateMessageData(e,t){return b(this,null,function*(){const s=null===e.senderId?Promise.resolve(N(null)):this.getUser(e.senderId),n=null===e.referencedMessageId?Promise.resolve(N(null)):this.getReferencedMessage(t,e.referencedMessageId),r=yield s;if(!r.ok)return r;const i=yield n;if(!i.ok)return i;var a,o,l;return N((a=e,o=r.value,l=i.value,Q({id:a.id,type:a.type,sender:o,referencedMessage:l,custom:Q(a.custom),createdAt:a.createdAt,editedAt:a.editedAt,origin:a.origin,content:a.content,reactions:Oe(a.reactions),plaintext:Ae(a.content,{})})))})}hydrateConvData(e,t){return b(this,null,function*(){const s=this.listMessages(e.id,{limit:1},t),n=yield this.call({method:"GET",path:["me","conversations",e.id],data:{},headers:t});if(!n.ok&&"server"===n.where&&404===n.value.status)return N(null);const r=U("Get conversation "+e.id,n),i=Or("Get last message in conversation "+e.id,yield s);var a,o;return N((a=r,o=0===i.length?null:i[0],Q({id:a.id,subject:a.subject,photoUrl:a.photoUrl,welcomeMessages:Q(a.welcomeMessages),custom:Q(a.custom),createdAt:a.createdAt,joinedAt:a.joinedAt,lastMessageAt:a.lastMessageAt,unreadMessageCount:a.unreadMessageCount,isUnread:a.isUnread,access:a.access,notify:a.notify,lastMessage:o,readUntil:a.readUntil,everyoneReadUntil:a.everyoneReadUntil})))})}listMessages(e,t,s){return b(this,null,function*(){const n=yield this.call({method:"GET",path:["me","conversations",e,"messages"],data:t,headers:s});if(!n.ok)return Dr(n,"Listing messages in "+e);const r=n.value.data.data,i=yield Promise.all(r.map(t=>this.hydrateMessageData(t,e))),a=i.find(e=>!e.ok);return void 0===a||a.ok?N(i.map(({value:e})=>e)):a})}getReferencedMessage(e,t){return b(this,null,function*(){const s=yield this.call({method:"GET",path:["me","conversations",e,"messages",t],data:{}});if(!s.ok&&"server"===s.where&&404===s.value.status)return N(null);if(!s.ok&&"server"===s.where&&403===s.value.status&&"NOT_A_PARTICIPANT"===s.value.errorCode)return N(null);if(!s.ok)return Dr(s,`Fetching referenced message ${t} in conversation ${e}`);const n=s.value.data,r=yield this.getUser(n.senderId);if(!r.ok)return r;var i,a;return N((i=n,a=r.value,Q({id:i.id,type:i.type,sender:a,referencedMessageId:i.referencedMessageId,custom:Q(i.custom),createdAt:i.createdAt,editedAt:i.editedAt,origin:i.origin,content:i.content,reactions:Oe(i.reactions),plaintext:Ae(i.content,{})})))})}getUser(e){return b(this,null,function*(){const t=yield this.call({method:"GET",path:["users",e],data:{includePrivateFields:!1}});return t.ok||"server"!==t.where||404!==t.value.status?t.ok?N(Ne(t.value.data)):Dr(t,"Get user "+e):N(null)})}}function Dr(e,t){return"server"===e.where?O(p(h({},e.value),{operation:t})):e}function Or(e,t){var s;if(t.ok)return t.value;throw"SESSION_DESTROYED"===t.value?new Error(`${e} failed because the session was destroyed`):new Error($(null!=(s=t.value.operation)?s:e,t.value))}class Pr{constructor(e,t,s){this.realtimeWsApiUrl=e,this.internalHttpApiUrl=t,this.restApiHttpUrl=s}getBokensUrl(e,t,s){return this.internalHttpApiUrl+`/${e}/bokens/${encodeURIComponent(t)}?signature=${encodeURIComponent(null!=s?s:"")}`}getRealtimeWsUrl(e,t,s,n,r){const i=encodeURIComponent(t);return this.realtimeWsApiUrl+`/${e}/realtime/${i}?talkjs-client-build=${null!=r?r:"standalone"}&talkjs-core=${s}&talkjs-client-id=${n}`}static fromHost(e){var t;const s=new Pr("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");if(!e)return s;if("@currentHost"===e){if("undefined"==typeof location)throw new Error("You can only use @currentHost in a browser.");e=(null!=(t=window.top)?t:window).location.host}if(e.endsWith("talkjs.com")){const t=e.match(/^(?:\w+-)?([^.]+)\.talkjs\.com$/);if(t){const e=t[1];return["app","cdn","api","realtime"].includes(e)?s:new Pr(`wss://realtime-${e}.talkjs.com/v1`,`https://app-${e}.talkjs.com/api/v0`,`https://api-${e}.talkjs.com/v1`)}return s}return e.includes("localhost")||e.includes("localtest.me")||/^\d+\.\d+\.\d+\.\d+(:\d+)?$/.test(e)?new Pr(`ws://${e}/public_api/v1`,`http://${e}/api/v0`,`http://${e}/public_api/v1`):new Pr(`wss://${e}/public_api/v1`,`https://${e}/api/v0`,`https://${e}/public_api/v1`)}}function jr({method:e,url:t,data:s,options:n,attempts:r,shouldRetry:i,authProvider:a,errorTracker:o,abortSignal:l}){var c;(!r||r<=0)&&(r=1);const u={"x-talkjs-client-build":"jssdk-dev","x-talkjs-client-date":"2026-04-03T10:11:16.548Z"};return s instanceof FormData||(u["Content-Type"]=null!=(c=null==n?void 0:n.contentType)?c:"application/json"),R(r,()=>b(null,null,function*(){if(a){const e=yield a.getToken();u.Authorization=`Bearer ${e}`}return fetch(t,{method:e,headers:u,body:s,signal:l}).then(e=>{if(e.ok)return e;throw e})}),{initialDelay:.2,log:void 0,shouldRetry:s=>b(null,null,function*(){return a&&401===s.status?(null==o||o.log(`401 error from ${e} ${t}, ${yield a.getToken()}`),a.invalidateAndRefresh(),!0):i?i(s):!("object"==typeof s&&"status"in s&&s.status>=400&&s.status<500)})}).catch(s=>{if(Math.random()<.1&&!t.toString().startsWith("https://capture.trackjs.com")){const n=`Network Error for ${e} ${t}`;"undefined"!=typeof window&&(s instanceof Response?s.clone().text().then(e=>null==o?void 0:o.log(`${n} ${s.status} ${e} (10% logged)`)):null==o||o.log(`${n} ${s} (10% logged)`)),console.error("[TalkJS]",n)}throw s})}class Ur{constructor(e){var t,r,i,a;v(this,s),v(this,n),this._timeCreated=Date.now(),y(this,s,null!=(r=null==(t=globalThis.document)?void 0:t.referrer)?r:""),y(this,n,(null!=(a=null==(i=globalThis.location)?void 0:i.href)?a:globalThis.HermesInternal)?"React Native Hermes":""),this._trackJSData={customer:{application:"",correlationId:"",sessionId:"",token:"",userId:"",version:"dev-2026-04-03T10:11:16.548Z"},entry:"direct",environment:{age:Date.now()-this._timeCreated,dependencies:{},originalUrl:m(this,n),referrer:m(this,s),userAgent:window.navigator.userAgent},metadata:[],nav:[],network:[],url:m(this,n),stack:"",timestamp:(new Date).toISOString(),version:"dev-2026-04-03T10:11:16.548Z",throttled:0},this._url=`https://capture.trackjs.com/capture?token=${e}`,this._trackJSData.customer.token=e}setData({appId:e,meId:t,sessionId:s}){this._trackJSData.customer.userId=e,this._trackJSData.customer.sessionId=`${e}/${t}`,this._trackJSData.customer.correlationId=s}log(e){return b(this,null,function*(){try{const t=p(h({},this._trackJSData),{message:e});yield jr({method:"POST",url:this._url,data:JSON.stringify(t),options:{contentType:"text/plain"}})}catch(t){console.error("[TalkJS] Failed when sending an error report. Error: ",t)}})}}s=new WeakMap,n=new WeakMap;const $r={log:e=>Promise.resolve(),setData:e=>{}};class Wr{constructor(e,t={}){this._onSubscription=t,this._handlers={};for(const s in e)Object.hasOwnProperty.call(e,s)&&(this._handlers[s]=[])}emit(e,t){for(const n of this._handlers[e])try{n(t)}catch(s){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,s)}}emitAsync(e,t){return b(this,null,function*(){try{const s=this._handlers[e].map(e=>e(t));yield Promise.all(s)}catch(s){console.error(`[TalkJS] '${String(e)}' handler threw an error:`,s)}})}supports(e){return e in this._handlers}on(e,t){var s,n;if(!this.supports(e))throw new Error(`Unknown event type '${String(e)}'`);null==(n=(s=this._onSubscription)[e])||n.call(s),this._handlers[e].push(t)}off(e,t){if(!Object.hasOwnProperty.call(this._handlers,e))throw new Error(`Unknown event type '${String(e)}'`);const s=this._handlers[e].indexOf(t);-1!==s&&this._handlers[e].splice(s,1)}removeAllListeners(){for(const e in this._handlers)this._handlers[e]=[]}handles(e){return this._handlers[e].length>0}subscribe(e,t){return this.on(e,t),{unsubscribe:()=>this.off(e,t)}}}class qr{constructor(e){this.handlers=e,this.tokenResult=null,this.pendingToken=null}getTokenResult(){return b(this,null,function*(){if(this.tokenResult)return this.tokenResult;if(this.pendingToken)return this.pendingToken.promise;const e=A();return this.pendingToken=e,this.handlers.onNeedToken(),e.promise})}getCachedTokenResult(){return this.tokenResult?this.tokenResult:void 0}setTokenResult(e){this.pendingToken&&(this.pendingToken.resolve(e),this.pendingToken=null),this.tokenResult=e,this.handlers.onChange(e)}refreshToken(){this.pendingToken||(this.pendingToken=A(),this.handlers.onNeedToken())}invalidateAndRefresh(){this.tokenResult=null,this.refreshToken()}}class Lr{constructor(e,t,s,n){this.apiUrls=e,this.appId=t,this.userId=s,this.signature=n,this.inner=new qr({onChange:e=>{e.ok?this.eventEmitter.emit("tokenChanged",e.value):this.emitTokenRefreshFailed(e.value)},onNeedToken:()=>b(this,null,function*(){if(this._usingBokens&&!this.signature&&!this._calledBokens&&(yield new Promise(e=>setTimeout(e,1))),this._usingBokens)yield this.sendBokenRequest().then(e=>this.inner.setTokenResult(N(e))).catch(e=>this.inner.setTokenResult(O(e)));else if(this.onNeedToken)this.onNeedToken();else{const e=D("Cannot refresh token, no `onNeedToken` provided.");this.inner.setTokenResult(e)}})}),this._usingBokens=!0,this._calledBokens=!1,this.onNeedToken=void 0,this.eventEmitter=new Wr({tokenChanged(e){},tokenRefreshFailed(e){},tokenAccepted(e){}}),this.sessionExpiryWarningTimeoutId=void 0;const r="undefined"!=typeof window&&e.restApiHttpUrl.includes("api.talkjs.com");this.errorTracker=r?new Ur("970cd0be0fb74630b75c8451051299dc"):$r}get usingBokens(){return this._usingBokens}getToken(){return b(this,null,function*(){return Gr(yield this.inner.getTokenResult())})}getCachedToken(){const e=this.inner.getCachedTokenResult();if(void 0!==e)return Gr(e)}checkCanSetAuth(){if(this._calledBokens)throw new Error("[TalkJS] Cannot switch to JWT authentication once connected to TalkJS servers. To use JWTs, call `setToken` or set `onNeedToken` before triggering any requests or mounting any components. We recommend setting up authentication in your app's entry point (App.jsx, main.js, or similar) so it runs first.")}setToken(e){this.checkCanSetAuth(),setTimeout(()=>this.checkJwt(e),200),this._usingBokens=!1,this.inner.setTokenResult(N(e))}setTokenError(e){this._usingBokens=!1,this.inner.setTokenResult(D(e))}refreshToken(){this.inner.refreshToken()}invalidateAndRefresh(){this.inner.invalidateAndRefresh()}setOnNeedToken(e){this.checkCanSetAuth(),this._usingBokens=!1,this.onNeedToken=e}onTokenChanged(e){return this.eventEmitter.on("tokenChanged",e),()=>{this.eventEmitter.off("tokenChanged",e)}}onTokenRefreshFailed(e){return this.eventEmitter.on("tokenRefreshFailed",e),()=>{this.eventEmitter.off("tokenRefreshFailed",e)}}emitTokenRefreshFailed(e){this.eventEmitter.emit("tokenRefreshFailed",e)}onTokenAccepted(e){return this.eventEmitter.on("tokenAccepted",e),()=>{this.eventEmitter.off("tokenAccepted",e)}}emitTokenAccepted(e){this.eventEmitter.emit("tokenAccepted",e)}clearScheduledRefresh(){this.sessionExpiryWarningTimeoutId&&clearTimeout(this.sessionExpiryWarningTimeoutId)}scheduleRefresh(e){if(this.clearScheduledRefresh(),null===e)return;const t=void 0!==this.onNeedToken;e<120&&!t?console.warn(`[TalkJS] TalkJS will stop working in ${e} seconds due to auth token expiry. Token expires in ${e} seconds, and cannot be refreshed because no \`onNeedToken\` callback was provided. Non-refreshable tokens are recommended to expire at least 24 hours in the future.`):e<120&&t?console.warn(`[TalkJS] TalkJS auth token will expire and need to be refreshed in ${e} seconds. Refreshable JWTs are recommended to expire at least 30 minutes in the future, to improve performance and reduce unnecessary refreshes.`):e<3300&&!t&&console.warn(`[TalkJS debug] TalkJS will stop working in ${Math.round(e/60)} minutes due to auth token expiry. Non-refreshable tokens are recommended to expire at least 24 hours in the future. Alternatively, set \`onNeedToken\` with a callback that will run whenever a new token is needed.`);const s=e>600?e-300:e/2,n=Math.min(1728e6,1e3*s);this.sessionExpiryWarningTimeoutId=setTimeout(()=>{void 0!==this.onNeedToken&&this.refreshToken()},n)}checkJwt(e){!function(e){if(!("string"==typeof e||e instanceof String)){if(void 0===e)throw"Token was undefined";throw"Token must be a string, got: "+e}}(e);const t=[];let s,n,r;if("string"==typeof e?s=e:t.push(`Token type is ${typeof e} instead of a string.`),s)try{const e=function(e){const t=e.split(".");if(3!==t.length)throw"Token does not contain exactly two `.`. Check that you generated your JWT correctly. It should be `<header>.<payload>.<signature>`.";return{header:Br(t[0]),payload:Br(t[1])}}(s);n=e.header,r=e.payload}catch(i){t.push(i)}if(n){const e=this.checkJwtHeader(n);t.push(...e)}if(r){const e=this.checkJwtPayload(r);t.push(...e)}if(t.length)if(this.usingBokens)this.errorTracker.log(`JWT Errors detected by AuthProvider when using bokens: ${t.join("\n")}`);else{console.warn("[TalkJS] Authentication token appears to be generated incorrectly. Will still attempt to authenticate, but TalkJS may not work as expected. See below for a description of any problems and how to fix them.");const s=t.length>1;t.forEach((e,t)=>{const n=s?`Reason ${t+1}:`:"Reason:";console.warn(`[TalkJS] ${n} ${e}`)}),console.warn(`[TalkJS]: Authentication token: "${e}"`)}}checkJwtHeader(e){const t=[],s=e.alg;return void 0===s?t.push('Token header must contain `"alg": "HS256"`, but no `alg` was specified.'):"string"!=typeof s?t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was ${typeof s} instead of a string. Make sure you wrap the value in "".`):"HS256"!==s&&t.push(`Token header must contain \`"alg": "HS256"\`, but \`alg\` was set to "${s}" instead. HS256 is the only supported algorithm.`),t}checkJwtPayload(e){const t=[],s=e.iss;void 0===s?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was missing.`):"string"!=typeof s?t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was ${typeof s} instead of a string. Make sure you wrap the value in "".`):s!==this.appId&&t.push(`Token payload must contain an \`iss\` claim set to your app ID (${this.appId}), but \`iss\` was set to "${s}" instead.`);const n=e.sub;void 0===n?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was missing.`):"string"!=typeof n?t.push(`Token payload must contain a \`sub\` claim set to your user ID (${this.userId}), but \`sub\` was ${typeof n} instead of a string. Make sure you wrap the value in "".`):n!==this.userId&&t.push(`Token payload must contain a \`sub\` claim set to your userId ID (${this.userId}), but \`sub\` was set to "${n}" instead.`);const r=e.tokenType;void 0===r?t.push('Token payload must contain a `"tokenType": "user"` claim, but no `tokenType` was specified.'):"string"!=typeof r?t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was ${typeof r} instead of a string. Make sure you wrap the value in "".`):"user"!==r&&t.push(`Token payload must contain a \`"tokenType": "user"\` claim, but \`tokenType\` was set to "${r}" instead.`);const i=e.exp;void 0===i||("number"!=typeof i?t.push(`Token payload contains an \`exp\` claim, but \`exp\` was ${typeof r} instead of a number. If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Don't wrap the value in "".`):i<1e9?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01.`):i>1e11?t.push(`Token payload contains an \`exp\` claim, but \`exp\` is very small (${i}, representing ${new Date(1e3*i).toLocaleDateString()}). If set, \`exp\` should be the expiry date as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`):i<(new Date).getTime()/1e3&&t.push(`Token payload contains an \`exp\` claim, but \`exp\` (${i}, representing ${new Date(1e3*i).toLocaleDateString()}) appears to be in the past, meaning the token will be rejected. This error can also happen if your device's clock is set incorrectly, in which case the token will still work.`));const a=e.nbf;return void 0===a||("number"!=typeof a?t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` was ${typeof r} instead of a number. If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01.`):a>1e11&&t.push(`Token payload contains a \`nbf\` (not-before) claim, but \`nbf\` is very large (${a}, representing ${new Date(1e3*a).toLocaleDateString()}). If set, \`nbf\` should be the date when the JWT becomes valid, as a number of seconds since 1970-01-01. Double-check that you are using seconds and not milliseconds or nanoseconds.`)),t}sendBokenRequest(){return b(this,null,function*(){this._calledBokens=!0;let e=0;const t=this.apiUrls.getBokensUrl(this.appId,this.userId,this.signature),s=yield jr({method:"GET",url:t,attempts:1e4,shouldRetry:t=>{if(t instanceof Error)return!0;if(401===t.status)throw"Check that you provided a valid signature.";if(404===t.status)throw"Check that you specified the correct App ID.";if(429===t.status||502===t.status)return!0;if(t.status>=400&&t.status<500)throw`Unexpected HTTP ${t.status} response when fetching auth token. Check that you configured the session correctly.`;if(e++,e>=5)throw`Unexpected HTTP ${t.status} response when fetching auth token, retrying did not help.`;return!0},errorTracker:this.errorTracker});return(yield s.json()).boken})}}function Br(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(t){throw`Could not base64-decode and JSON-parse token section: ${e}. Check that you base-64 encoded the section correctly.`}}function Gr(e){if(e.ok)return e.value;throw e.value}const Fr=new class{constructor(){this.registry={}}getOrCreate(e){const t=this.key(e),s=this.registry[t];if(s)return s;const n=new Hr(e);return this.registry[t]=n,n}deregister(e,t){const s=this.key({appId:e,userId:t});delete this.registry[s]}key({appId:e,userId:t}){return`${e}:${t}`}};class Hr{constructor(e){this._onNeedToken=void 0,function(e){function t(e,t){if(!e)throw new Error("[TalkJS] TalkSession: "+t)}t(e&&"object"==typeof e,"Expected an object argument in `getTalkSession`."),t(e.appId&&"string"==typeof e.appId,"The `appId` property of the `getTalkSession` options is required and it must be a non-empty string."),t("string"==typeof e.userId,"The `userId` property of the `getTalkSession` options is required and it must be a string."),void 0!==e.token&&t(e.token&&"string"==typeof e.token,"The `token` property of the `getTalkSession` options must be a non-empty string."),void 0!==e.tokenFetcher&&t("function"==typeof e.tokenFetcher,"The `tokenFetcher` property of the `getTalkSession` options must be a function.")}(e);const{appId:t,userId:s,token:n,tokenFetcher:r,signature:i}=e;this._appId=t,this._apiUrls=e.apiUrls?new Pr(e.apiUrls.realtimeWsApiUrl,e.apiUrls.internalHttpApiUrl,e.apiUrls.restApiHttpUrl):Pr.fromHost(e.host),this._authProvider=new Lr(this._apiUrls,t,s,i),n&&this._authProvider.setToken(n),r&&this._authProvider.setOnNeedToken(()=>b(this,null,function*(){try{const e=yield r();this._authProvider.setToken(e)}catch(e){this._authProvider.setTokenError(`${e}`)}}));const a=Math.random().toString().split(".")[1];this._realtimeClient=new Nr(this._apiUrls.getRealtimeWsUrl(t,s,"1.8.3",a,e.clientBuild),s,this._authProvider),this.currentUser=this.user(s),this._terminationReason=A(),this._terminationReason.promise.then(e=>{console.error(`[TalkJS] ${e}`)}),function(e,t){return b(this,null,function*(){return jr({method:"GET",url:`${t}/${e}`}).then(e=>b(null,null,function*(){return 200===e.status||404!==e.status&&(console.warn(`[TalkJS] Received unexpected ${e.status} status code when validating app ID. Assuming that the app ID is valid.`),!0)})).catch(e=>{if("string"!=typeof e&&"status"in e){const t=e;return 200===t.status||404!==t.status&&(console.warn(`[TalkJS] Received unexpected ${t.status} status code when validating app ID. Assuming that the app ID is valid.`),!0)}return console.warn("[TalkJS] Encountered network issues when validating app ID. Assuming that the app ID is valid."),!0})})}(this._appId,this._apiUrls.internalHttpApiUrl).then(e=>{e||this.terminate(new Error(`The app ID ${this._appId} does not exist. Make sure you are using the correct app ID as found on the TalkJS dashboard. App IDs are case-sensitive.`))}),this._authProvider.onTokenRefreshFailed(e=>{this.terminate(new Error(`Could not authenticate, cannot recover automatically: ${e}`))})}setToken(e){this._authProvider.setToken(e)}get onNeedToken(){return this._onNeedToken}set onNeedToken(e){this._onNeedToken=e,void 0===e?this._authProvider.setOnNeedToken(void 0):this._authProvider.setOnNeedToken(()=>{try{e()}catch(t){console.error("[TalkJS] error when calling `onNeedToken` - your auth token will expire soon.",t)}})}onError(e){const t=A();return Promise.race([t.promise,this._terminationReason.promise]).then(t=>{"UNSUBSCRIBED"!==t&&e(t)}),{unsubscribe:()=>t.resolve("UNSUBSCRIBED")}}user(e){if("string"!=typeof e)throw new Error(`Creating UserRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating UserRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.user(e)}conversation(e){if("string"!=typeof e)throw new Error(`Creating ConversationRef failed because ID "${e}" is not a string`);if(""===e)throw new Error(`Creating ConversationRef failed because ID "${e}" is an empty string`);return this._realtimeClient.refs.conversation(e)}subscribeConversations(e){return new wr(this._realtimeClient,e)}searchMessages(e){let t;return{setQuery:s=>t&&t.searchString===s?t.currentState:(t&&t.cancel(),s&&""!==s?(t=new Jr(e,s,`${this._apiUrls.restApiHttpUrl}/${this._appId}/me/messages/search`,e=>b(this,null,function*(){const[t,s]=yield Promise.all([this.conversation(e.conversationId).get(),this._realtimeClient.hydrateMessageData(e,e.conversationId)]);return null===t?D("Message belongs to nonexistent conversation"):s.ok?N({conversation:t,message:s.value}):s}),this._authProvider),t.loadMore(3)):(t=void 0,null==e||e([],"loadedAll"),Promise.resolve({results:[],loadedAll:!0}))),loadMore:e=>t?t.loadMore(null!=e?e:10):Promise.resolve({results:[],loadedAll:!0})}}searchConversations(e){let t;return{setQuery:s=>t&&t.searchString===s?t.currentState:(t&&t.cancel(),s&&""!==s?(t=new Jr(e,s,`${this._apiUrls.restApiHttpUrl}/${this._appId}/me/conversations/search`,e=>b(this,null,function*(){const t=yield this._realtimeClient.hydrateConvData(e);if(!t.ok)return t;const s=t.value;return null===s?O({status:404,errorCode:"CONVERSATION_NOT_FOUND",reasons:["No conversation with that ID was found"]}):N(s)}),this._authProvider),t.loadMore(3)):(t=void 0,null==e||e([],"loadedAll"),Promise.resolve({results:[],loadedAll:!0}))),loadMore:e=>t?t.loadMore(null!=e?e:10):Promise.resolve({results:[],loadedAll:!0})}}terminate(e){Fr.deregister(this._appId,this.currentUser.id),this._terminationReason.resolve(e),this._realtimeClient.destroy()}_isConnected(){return this._realtimeClient.isConnected()}uploadFile(e,t){return zr(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,t)}uploadImage(e,t){return zr(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,h({subtype:"image"},t))}uploadVideo(e,t){return zr(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,h({subtype:"video"},t))}uploadAudio(e,t){return zr(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,h({subtype:"audio"},t))}uploadVoice(e,t){return zr(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,this._realtimeClient,e,h({subtype:"voice"},t))}}function zr(e,t,s,n,r){return b(this,arguments,function*(e,t,s,n,{subtype:r,filename:i,width:a,height:o,duration:l}){U("Upload file",yield s.call({method:"POST",path:["files","validate"],data:{filename:i,filesize:n.size}}));const c=new FormData;return c.set("file",n,i),void 0!==r&&c.set("subtype",r),void 0!==a&&c.set("width",a.toString()),void 0!==o&&c.set("height",o.toString()),void 0!==l&&c.set("duration",l.toString()),jr({method:"POST",url:e,data:c,authProvider:t,errorTracker:t.errorTracker}).then(e=>e.json()).then(e=>e.fileToken).catch(e=>b(null,null,function*(){if(e instanceof Response){const t=yield e.json(),s=`Unexpected response when uploading file, status code ${e.status} ${t.errorCode}, ${t.reasons}`;throw new Error(s)}throw e}))})}class Jr{constructor(e,t,s,n,r){this.onResults=e,this.searchString=t,this.baseUrl=s,this.hydrateData=n,this.authProvider=r,this.error=void 0,this.lastCompletedQueryState={results:[],loadedAll:!1},this.currentCursor=void 0,this.cancelQuery=()=>{},null==e||e([],"searching")}get currentState(){return this.loadingDeferred?this.loadingDeferred.promise:Promise.resolve(this.lastCompletedQueryState)}cancel(){this.cancelQuery()}buildUrl(e){const t=new URL(this.baseUrl);return void 0===this.currentCursor&&t.searchParams.append("searchString",encodeURIComponent(this.searchString)),void 0!==this.currentCursor&&t.searchParams.append("cursor",this.currentCursor),t.searchParams.append("limit",e.toString()),t.toString()}loadMore(e){return b(this,null,function*(){var t,s;if(this.error)throw this.error;if(this.loadingDeferred)return this.loadingDeferred.promise;if(this.lastCompletedQueryState.loadedAll)return Promise.resolve(this.lastCompletedQueryState);this.loadingDeferred=A(),this.loadingDeferred.promise.catch(()=>{});const n=new AbortController;this.cancelQuery=()=>{n.abort()};const r=this.buildUrl(e),i=[],a=yield this._performSearch(r,n,e=>{const t=this.hydrateData(e);i.push(t),void 0!==this.onResults&&Promise.all(i).then(e=>{const t=j(e),s=Q([...this.lastCompletedQueryState.results,...t]);this.onResults(s,"searching")})}),o=a.ok?a.value:void 0;if(yield Promise.all(i).then(e=>{var t;const s=j(e),n=Q([...this.lastCompletedQueryState.results,...s]),r=void 0===o;this.lastCompletedQueryState=Q({results:n,loadedAll:r}),this.currentCursor=o;const i=r?"loadedAll":"canLoadMore";null==(t=this.onResults)||t.call(this,n,i)}),a.ok)return null==(t=this.loadingDeferred)||t.resolve(this.lastCompletedQueryState),this.loadingDeferred=void 0,this.lastCompletedQueryState;throw null==(s=this.loadingDeferred)||s.reject(a.value),this.loadingDeferred=void 0,this.error=a.value,a.value})}_performSearch(e,t,s){return b(this,null,function*(){let n;return jr({method:"GET",url:e,authProvider:this.authProvider,errorTracker:this.authProvider.errorTracker,abortSignal:t.signal}).then(e=>b(this,null,function*(){if(!e.body)return O("Search response was missing body");const t=e.body.getReader(),r=new TextDecoder;let i="",a=!0;const o=(e,t)=>{if(a)a=!1;else try{if(e.startsWith("]")){const t=`{"data":[${e}`,s=JSON.parse(t);return void(n=s.cursor)}let s=e;s.startsWith(",")&&(s=s.slice(1)),t(JSON.parse(s))}catch(s){console.warn("[TalkJS] Error during search, received unexpected data, ignoring. Some search results may be missing.")}};for(;;){const{done:e,value:n}=yield t.read();if(e)break;i+=r.decode(n,{stream:!0});const a=i.split("\n");i=a.pop()||"";for(const t of a)o(t,s)}i+=r.decode();const l=i.split("\n");for(const e of l)o(e,s);return N(n)})).catch(e=>b(this,null,function*(){if(e instanceof DOMException&&"AbortError"===e.name)return N(void 0);if(e instanceof Response){const t=yield e.clone().json();return O($("Search",{status:e.status,errorCode:t.errorCode,reasons:t.reasons}))}return O(e)}))})}}exports.getTalkSession=function(e){if(!e)throw new Error("[TalkJS] Must provide an options object to `getTalkSession`");return e.forceCreateNew?new Hr(e):Fr.getOrCreate(e)},exports.registerPolyfills=function({WebSocket:e}){W=e};
|
|
2
2
|
//# sourceMappingURL=talkSession.cjs.map
|