UNPKG

@talkjs/core

Version:

Lets you connect to your TalkJS chat as a user and read, subscribe to, and update your chat data.

1 lines 152 kB
"use strict";var e,t=Object.defineProperty,s=Object.defineProperties,n=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,o=(e,s,n)=>s in e?t(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n,u=(e,t)=>{for(var s in t||(t={}))i.call(t,s)&&o(e,s,t[s]);if(r)for(var s of r(t))a.call(t,s)&&o(e,s,t[s]);return e},l=(e,t)=>s(e,n(t)),c=(e,t,s)=>new Promise(((n,r)=>{var i=e=>{try{o(s.next(e))}catch(qe){r(qe)}},a=e=>{try{o(s.throw(e))}catch(qe){r(qe)}},o=e=>e.done?n(e.value):Promise.resolve(e.value).then(i,a);o((s=s.apply(e,t)).next())}));function h(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(d(e,t.value));throw"unreachable"}function d(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}`}function p(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if("*"!==t[s]&&e[s]!==t[s])return!1;return!0}function f(e){return e<=0?Promise.resolve():new Promise((t=>setTimeout(t,e)))}function m(e,t){return e*(1-t+2*Math.random()*t)}Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=()=>!0;function v(e,t,s){return c(this,arguments,(function*(e,t,{initialDelay:s,maxDelay:n,log:r,shouldRetry:i=g}){return t().catch((a=>c(this,null,(function*(){if(0===e)throw a;if(!(yield i(a)))throw a;const o=1e3*s*1.2,u=m(n?Math.min(1e3*n,o):o,.05);return f(u).then((()=>v(e-1,t,{initialDelay:u/1e3,maxDelay:n,log:r,shouldRetry:i})))}))))}))}function b(){const e={},t=new Promise((function(t,s){e.resolve=t,e.reject=s}));return e.promise=t,e}class y{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 w(e){return{ok:!0,value:e}}function C(e){return{ok:!1,where:"client",value:e}}function A(e){return{ok:!1,where:"server",value:e}}function E(){const e={},t=new Promise((t=>{e.ok=e=>c(this,null,(function*(){return t(w(e))})),e.clientErr=e=>t(C(e)),e.serverErr=e=>t(A(e)),e.resolve=e=>t(e)}));return e.promise=t,e}let k=null;class x{constructor(e,t){this.realtimeUrl=e,this.handlers=t,this.socket=null,this.stateMachine=new y("ReconnectingSocket",["STOPPED","CONNECTING","READY","DISCONNECTED","TERMINATED"],{startWs:{from:["STOPPED","DISCONNECTED"],to:"CONNECTING",afterTransition:()=>{const e=new(function(){if(k)return k;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=>c(this,[e],(function*({from:e}){"READY"===e&&this.handlers.onClose(),this.socket=null;const t=m(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),w(void 0)):C("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 T{constructor(e,t){this.handlers=t,this.socket=new x(e,{onOpen:()=>this.handlers.onOpen(),onClose:()=>this.handlers.onClose(),onMessage:e=>this.onWebSocketMessage(e)})}call(e,t,s,n){const r=`/${s.map((e=>encodeURIComponent(e))).join("/")}`,i=JSON.stringify([e,t,r,n]);return this.socket.send(i)}stopWs(){this.socket.stopWs()}startWs(){this.socket.startWs()}destroy(){this.socket.destroy()}terminate(){this.socket.terminate()}onWebSocketMessage(e){if("Auth token expired"!==e.data)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){}else this.handlers.onAuthExpired()}}class S{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)}}class I{constructor(){this.i=-1}next(){return this.i++,this.i}reset(){this.i=-1}}class D{constructor(e,t){this.handlers=t,this.seqCounter=new I,this.responseHandlers={},this.heartbeats=new M(this),this.socket=new T(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()}})}call(e,t,s){const n=this.seqCounter.next(),r=E();this.responseHandlers[n]=r;const i=this.socket.call(n,e,t,s);return i.ok||r.resolve(i),this.heartbeats.clientActive(),r.promise}onResponse(e,t,s){return c(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 M{constructor(e){this.connection=e,this.clientInactivityTimer=new S(25e3),this.serverInactivityTimer=new S(1e4),this.serverTimeoutTimer=new S(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("GET",["ping"],{}).catch((()=>{}))}}class F{constructor(e,t,s){this.authProvider=t,this.handlers=s,this.stateMachine=new y("AuthenticatedConnection",["WAITING_FOR_WS","LOGGING_IN","RENEWING_SESSION","READY","TERMINATED"],{logIn:{from:["WAITING_FOR_WS"],to:"LOGGING_IN",afterTransition:()=>c(this,null,(function*(){yield this.renewSession()}))},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>c(this,null,(function*(){this.authProvider.refreshToken(),yield this.renewSession()}))},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>c(this,null,(function*(){yield this.renewSession()}))},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>c(this,null,(function*(){this.authProvider.refreshToken(),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:()=>c(this,null,(function*(){this.handlers.onNotReady(),this.authProvider.refreshToken(),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 D(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")}))}call(e,t,s){const n=this.connection.call(e,t,s);return n.then((e=>{e.ok||"server"!==e.where||401!==e.value.status||"READY"!==this.stateMachine.state&&"RENEWING_SESSION"!==this.stateMachine.state||this.stateMachine.transition("authExpired")})),n}stopWs(){this.connection.stopWs()}startWs(){this.connection.startWs()}destroy(){this.stateMachine.transition("destroy")}renewSession(){return c(this,null,(function*(){const e=yield this.authProvider.getToken(),t=yield this.connection.call("POST",["session","renew"],{token:e});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(d("Authentication",s));if(402===s.status)return void this.authProvider.emitTokenRefreshFailed(d("Authentication",s));const n=5e3*Math.random()+5e3;setTimeout((()=>{this.call("POST",["session","renew"],{token:e}).catch((()=>{}))}),n)}))}}class B{constructor(e,t,s){this.handlers=s,this.stateMachine=new y("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 S(3e3),this.connection=new F(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}ensureStarted(){this.stateMachine.canTransition("start")&&this.stateMachine.transition("start")}call(e,t,s){return c(this,null,(function*(){this.inactivityTimer.stop(),this.pendingCalls++;const n=yield this.connection.call(e,t,s);return this.pendingCalls--,"SUBSCRIBE"===e&&n.ok?this.activeSubscriptions++:"UNSUBSCRIBE"===e&&n.ok&&this.activeSubscriptions--,this.inactive&&this.inactivityTimer.schedule((()=>{this.stateMachine.transition("stop")})),n}))}destroy(){this.stateMachine.transition("destroy")}isConnected(){return"READY"===this.stateMachine.state}}class R{constructor(e,t,s){this.handlers=s,this.stateMachine=new y("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 B(e,t,{onUpstreamRestarting:()=>{this.handlers.onUpstreamRestarting()},onReady:()=>{this.stateMachine.transition("processQueue")},onNotReady:()=>{this.stateMachine.transition("notReady")},onPublish:(e,t)=>{this.handlers.onPublish(e,t)}})}call(e,t,s){return"READY"===this.stateMachine.state?this.connection.call(e,t,s):("NOT_READY"===this.stateMachine.state&&this.connection.ensureStarted(),"SUBSCRIBE"===e||"UNSUBSCRIBE"===e?this._subscribe(e,t,s):this._call(e,t,s))}_subscribe(e,t,s){const n=t.join("/"),r=this.subscribeQueue[n];if(r&&r.method===e)return r.deferred.promise;r&&r.method!==e&&(r.deferred.ok({status:200,data:{}}),delete this.subscribeQueue[n]);const i={deferred:E(),method:e,path:t,data:s};return this.subscribeQueue[n]=i,i.deferred.promise}_call(e,t,s){const n={deferred:E(),method:e,path:t,data:s};return this.callQueue.push(n),n.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 c(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.method,t.path,t.data).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}}const N="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class P{constructor(e,t){this.clearPendingBatch=e,this.sendCalls=t,this.sent=!1,N((()=>this.send()))}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class O extends P{constructor(e,t){super(t,(()=>{this.sendSubscribe(),this.sendGet()})),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e,t){return O.isCorrectBatchTypeFor(e,t)}static isCorrectBatchTypeFor(e,t){return p(t,["users","*"])&&("GET"===e||"SUBSCRIBE"===e)}push(e,t,s){const n=t[1],r=E();return"GET"===e?this.getCalls.push({userId:n,deferred:r}):this.subscribeCalls.push({userId:n,deferred:r}),1e3!==this.getCalls.length&&1e3!==this.subscribeCalls.length||this.send(),r.promise}sendGet(){return c(this,null,(function*(){if(0===this.getCalls.length)return;const e=[...new Set(this.getCalls.map((e=>e.userId)))],t=yield this.connection.call("GET",["users"],{ids:e,includePrivateFields:!1});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("SUBSCRIBE",["users"],{ids:e}).then((e=>this.subscribeCalls.forEach((t=>t.deferred.resolve(e)))))}}class _ extends P{constructor(e,t,s){super(s,(()=>this.sendMutate())),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e,t){return!!_.isCorrectBatchTypeFor(e,t)&&t[1]===this.conversationId}static isCorrectBatchTypeFor(e,t){return p(t,["conversations","*","participants","*"])&&("PUT"===e||"POST"===e||"PATCH"===e)}push(e,t,s){const n=t[3],r=E();return this.calls.push({action:{id:n,method:e,params:s},deferred:r}),100===this.calls.length&&this.send(),r.promise}sendMutate(){return c(this,null,(function*(){const e=this.calls.map((e=>e.action)),t=yield this.connection.call("POST",["conversations",this.conversationId,"participants"],{actions:e});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(l(u({},t),{data:{}})):e.serverErr(t)}}))}}class U{constructor(e,t,s){this.pendingBatch=null,this.connection=new R(e,t,s)}call(e,t,s){return c(this,null,(function*(){var n;if(null==(n=this.pendingBatch)?void 0:n.canPush(e,t))return this.pendingBatch.push(e,t,s);this.pendingBatch&&this.pendingBatch.send();const r=this.createEmptyBatchFor(e,t);return r?(this.pendingBatch=r,r.push(e,t,s)):this.connection.call(e,t,s)}))}destroy(){var e;this.connection.destroy(),null==(e=this.pendingBatch)||e.destroy()}isConnected(){return this.connection.isConnected()}createEmptyBatchFor(e,t){if(O.isCorrectBatchTypeFor(e,t))return new O(this.connection,(()=>this.pendingBatch=null));if(_.isCorrectBatchTypeFor(e,t)){const e=t[1];return new _(e,this.connection,(()=>this.pendingBatch=null))}return null}}const j={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class ${constructor(e,t,s){this.throttler=new W,this.alive=!0,this.connection=new U(e,t,s)}call(e,t,s){return c(this,null,(function*(){let n=0;for(;this.alive;){const r=yield this.connection.call(e,t,s);if((r.ok||"client"!==r.where||"SOCKET_NOT_READY"!==r.value)&&(r.ok||"server"!==r.where||500!==r.value.status)||n++,10===n)return r;if(r.ok||"client"!==r.where){const e=r.value,t=e.status,s=j[t];if("RESOLVE"===s)return this.throttler.resetDelay(),r;if("RETRY"===s)continue;if("DELAY"===s){yield this.throttler.wait();continue}return console.warn("[TalkJS] Unexpected status code",t),e}if("SESSION_DESTROYED"===r.value)return C("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==r.value&&("SOCKET_NOT_READY"!==r.value?r.value:yield this.throttler.wait())}return C("SESSION_DESTROYED")}))}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class W{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=m(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),f(n)}resetDelay(){this.currentDelayMs=this.initialDelayMs}}function q(e){return e.map((e=>encodeURIComponent(e))).join()}class H{constructor(){this.paths={}}add(e){this.paths[q(e)]=e}delete(e){delete this.paths[q(e)]}has(e){return Object.hasOwnProperty.call(this.paths,q(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach((t=>e(t)))}}class G{constructor(e,t,s){this.handlers=s,this.targetSubscriptions=new H,this.connection=new $(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)}})}call(e,t,s){return this.connection.call(e,t,s)}subscribe(e){return c(this,null,(function*(){return this.targetSubscriptions.add(e),this.connection.call("SUBSCRIBE",e,{})}))}unsubscribe(e){return c(this,null,(function*(){return this.targetSubscriptions.delete(e),this.connection.call("UNSUBSCRIBE",e,{})}))}resubscribe(e){return c(this,null,(function*(){const t=yield this.connection.call("SUBSCRIBE",e,{});t.ok||this.handlers.onResubscribeError(e,t)}))}destroy(){this.targetSubscriptions.clear(),this.connection.destroy()}isConnected(){return this.connection.isConnected()}}function L(e,t){return void 0===t?e:t}function z(e,t){if(void 0===t)return e;if(null===t)return{};const s=u({},e);for(const n in t){const e=t[n];null===e?delete s[n]:s[n]=e}return s}function J(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(!J(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(!J(e[n],t[n]))return!1}}return!0}class Y{constructor(){this.prev=Promise.resolve()}runExclusive(e){return c(this,null,(function*(){const t=this.prev.then((()=>e()));return this.prev=t,t}))}}class Q{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){if(void 0!==this.getPointer&&e<this.getPointer.seq)throw`Trying to load state ${e} when we have previously loaded ${this.getPointer.seq}`;for(;this.pendingStates.length>0&&this.pendingStates[0].seq<=e;)this.getPointer=this.pendingStates.shift();return this.getPointer}}class V extends Q{constructor(e,t){super(e),this.onTeardown=t,this._error=null,this._lastGoodState=Promise.resolve(void 0)}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 Z extends V{constructor(e){super({seq:0,resultPromise:new Promise((e=>setTimeout(e))).then((()=>this.fetchInitial(0)))},e),this.getDeepMutex=new Y,this.lastDeep=void 0}refetchInitial(e){return c(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 c(this,null,(function*(){if(e>=t)return!1;const s=this.get(t),n=yield s.resultPromise;return!!n.ok&&(n.value.lastChanged>e||(yield this.anyChildChanged(e,t,n.value)))}))}getDeep(e){return c(this,null,(function*(){return this.getDeepMutex.runExclusive((()=>c(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 i.ok||this.setError(i),i}))))}))}}class K extends Z{constructor(e,t){super(t),this.emitMutex=e,this.unsubscribeTimer=new X,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,e.runExclusive((()=>c(this,null,(function*(){yield this.emit(0)}))))}registerInternalSubscription(){this.referencedByOtherStores++;let e=!0;return()=>{e&&(e=!1,this.referencedByOtherStores--,this.startUnsubscribeTimerIfOrphan())}}get onlyUsedInternally(){return 0===this.listeners.length}listen(e){return this.unsubscribeTimer.stop(),this.listeners.push(e),void 0!==this.lastEmitResult&&e(this.lastEmitResult),()=>{this.listeners=this.listeners.filter((t=>t!==e)),this.startUnsubscribeTimerIfOrphan()}}startUnsubscribeTimerIfOrphan(){0===this.referencedByOtherStores&&0===this.listeners.length&&this.unsubscribeTimer.restart((()=>{this.setError(C("UNSUBSCRIBED"))}),this.unsubscribeDebounceMs)}getLoadMoreSeq(){var e;const t=null!=(e=this.lastEmitSeq)?e:0,s=this.mostRecentState.seq;return Math.max(t,s)+1e-6}emit(e){return c(this,null,(function*(){var t;if(this.onlyUsedInternally)return;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 X{constructor(){this.timerId=void 0}restart(e,t){void 0!==this.timerId&&clearTimeout(this.timerId),this.timerId=setTimeout((()=>e()),t)}stop(){clearTimeout(this.timerId)}}class ee extends K{constructor(e,t,s,n){super(s,n),this.userId=e,this.realtimeClient=t,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return c(this,null,(function*(){const t=yield this.realtimeClient.call("GET",["users",this.userId],{includePrivateFields:!1},{bypassCache:!0});return t.ok?w({snapshot:this.realtimeClient.createUserSnapshot(t.value.data),lastChanged:e}):"server"===t.where&&404===t.value.status?w({snapshot:null,lastChanged:e}):t}))}equal(e,t){return J(e.snapshot,t.snapshot)}loadNested(e,t){return c(this,null,(function*(){return w(t)}))}userCreated(e,t){this.mutate(e,(s=>null!==s.value.snapshot?s:w({snapshot:this.realtimeClient.createUserSnapshot(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):w({snapshot:{id:n.id,name:L(n.name,t.diff.name),custom:z(n.custom,t.diff.custom),locale:L(n.locale,t.diff.locale),photoUrl:L(n.photoUrl,t.diff.photoUrl),role:L(n.role,t.diff.role),welcomeMessage:L(n.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})}))}getFromCache(){return c(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.snapshot?A({status:404,errorCode:"USER_NOT_FOUND",reasons:["That user does not exist yet"]}):w({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}}):C("NOT_IN_CACHE")}))}teardownNested(e){}anyChildChanged(e,t,s){return c(this,null,(function*(){return!1}))}}var te,se={};function ne(e,t){const s=t.lastIndex;let n;const r=[];for(;null!==(n=t.exec(e));)r.push(n);return t.lastIndex=s,r}function re(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(te)return se;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}te=1,Object.defineProperty(se,"__esModule",{value:!0}),se.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},se.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 ae=ie,oe=/^\/.*[^\\]\/[im]*$/;function ue(e){return!!oe.test(e)&&!le(e).test("")}function le(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 ce{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:s,allowedMatches:n,forbiddenMatches:r,suppressLinks:i,suppressEmailAddresses:a,suppressPhoneNumbers:o,replacement:u}){ae.oneOf(e,["all","otherOnly","off"]),this.mode=e,this.suppressLinks=!1!==i,this.suppressEmailAddresses=!1!==a,this.suppressPhoneNumbers=!1!==o,this.allowedHostnames=t||[],this.allowedPhoneNrs=(s||[]).filter((e=>e)).map((e=>e.replace(/[^0-9]/g,""))),this.allowedMatches=(n||[]).filter(ue).map((e=>le(e))),this.forbiddenMatches=(r||[]).filter(ue).map((e=>le(e))),ae((()=>this.allowedMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),ae((()=>this.forbiddenMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.forbiddenMatches` must be global. Check `forbiddenMatches`!"),u=null==u?void 0:u.trim(),this.replacement=u&&u.length>0?u:void 0}shouldSuppress({isContentBySender:e}){return"all"===this.mode||"otherOnly"===this.mode&&!e}}function he(e,t){return e.map((e=>function(e,t){if("text"===e.type)return de(e.children,function(e){var t,s,n,r,i,a,o,u,l,c,h,d;let p="";return e.t&&(p=`(${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:[],contactInfo:null!=(o=e.contactInfo)&&o,suppression:null!=(u=e.suppression)?u:new ce({mode:"off"}),contactInfoHiddenText:null!=(h=null!=(c=e.contactInfoHiddenText)?c:null==(l=e.suppression)?void 0:l.replacement)?h:p,customEmojiUrls:null!=(d=e.customEmojiUrls)?d:{}}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${re(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${re(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${re(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,`📎 ${re(e.url)}`):"location"===e.type?"📍":""}(e,t))).join("\n\n")}function de(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 de(e.children,t);case"bulletlist":case"bulletList":return"\n"+de(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+de(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("")}class pe extends Z{constructor(e,t,s){super(),this.conversationId=e,this.message=t,this.realtimeClient=s}get messageId(){return"string"==typeof this.message?this.message:this.message.id}fetchInitial(e){return c(this,null,(function*(){let t;if("object"==typeof this.message)t=this.message;else{const e=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId,"messages",this.message],{},{bypassCache:!0});if(!e.ok)return e;t=e.value.data}return w({lastChanged:e,sender:null===t.senderId?null:this.realtimeClient.internalSubscribe(["users",t.senderId]),data:{id:t.id,type:t.type,custom:t.custom,createdAt:t.createdAt,editedAt:t.editedAt,referencedMessageId:t.referencedMessageId,origin:t.origin,plaintext:he(t.content,{}),content:t.content}})}))}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 J(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}anyChildChanged(e,t,s){return c(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 c(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 w({snapshot:null});const a=null==i?void 0:i.value;return w({snapshot:{sender:null!=(r=null==a?void 0:a.snapshot)?r:null,id:t.data.id,type:t.data.type,custom:t.data.custom,createdAt:t.data.createdAt,editedAt:t.data.editedAt,origin:t.data.origin,plaintext:he(t.data.content,{}),content:t.data.content,referencedMessageId:t.data.referencedMessageId}})}))}messageEdited(e,t){this.mutate(e,(s=>null===s.value.data?s:w({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:L(s.value.data.editedAt,t.diff.editedAt),custom:z(s.value.data.custom,t.diff.custom),content:L(s.value.data.content,t.diff.content)}})))}messageDeleted(e,t){this.mutate(e,(s=>null===s.value.data?s:this.messageId===t.messageId?(this.teardownNested(s.value),w({lastChanged:e,sender:null,data:null})):s.value.data.referencedMessageId===t.messageId?w({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,content:s.value.data.content}}):s))}getFromCache(){return c(this,null,(function*(){var e;const t=yield this.mostRecentState.resultPromise;if(!t.ok)return C("NOT_IN_CACHE");if(null===t.value.data)return A({status:404,errorCode:"MESSAGE_NOT_FOUND",reasons:["No message with that ID exists"]});const s=t.value,{sender:n}=s,o=((e,t)=>{var s={};for(var n in e)i.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&r)for(var n of r(e))t.indexOf(n)<0&&a.call(e,n)&&(s[n]=e[n]);return s})(s,["sender"]);return w({status:200,data:l(u({},o.data),{senderId:null!=(e=null==n?void 0:n.store.userId)?e:null})})}))}}class fe extends Z{constructor(e,t,s){super(),this.createdAt=e,this.dataStore=t,this.referencedDataStore=s}get messageId(){return this.dataStore.messageId}fetchInitial(e){return c(this,null,(function*(){return w({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 c(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 c(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 w({snapshot:null});const o=yield null==(s=t.referencedDataStore)?void 0:s.getDeep(e);if(o&&!o.ok)return o;const u=null!=(n=null==o?void 0:o.value)?n:null,l=null!=(r=null==u?void 0:u.snapshot)?r:null;return w({snapshot:{id:a.snapshot.id,type:a.snapshot.type,sender:a.snapshot.sender,custom:a.snapshot.custom,createdAt:a.snapshot.createdAt,editedAt:a.snapshot.editedAt,referencedMessage:l,origin:a.snapshot.origin,plaintext:a.snapshot.plaintext,content:a.snapshot.content}})}))}}class me extends K{constructor(e,t,s,n){super(s,n),this.conversationId=e,this.realtimeClient=t,this.unsubscribeDebounceMs=1e3,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._loadMoreMessages(t)}})),super.listen(e)}fetchInitial(e){return c(this,null,(function*(){const t=this.onlyUsedInternally?1:30,s=yield ge({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return s.ok?null===s.value.messages?w({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}):ve({seq:e,messages:s.value.messages,cursor:s.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):s}))}teardownNested(e){if(e.stores){const t=C("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t))),e.inWindow.forEach((e=>e.setError(t)))}}anyChildChanged(e,t,s){return c(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 c(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&&!!J(Object.keys(e.stores),Object.keys(t.stores))&&!!J(e.inWindow.map((e=>e.messageId)),t.inWindow.map((e=>e.messageId)))&&J(e.windowEnd,t.windowEnd)}loadNested(e,t){return c(this,null,(function*(){if(null===t.stores)return w({snapshot:null,loadedAll:!0});const s=yield Promise.all(t.inWindow.map((t=>t.getDeep(e)))),n=s.find((e=>!e.ok));return n||w({snapshot:s.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot)),loadedAll:null===t.windowEnd})}))}loadMore(e){return c(this,null,(function*(){if(this.pendingLoadMore)return this.pendingLoadMore;const t=b();this.pendingLoadMore=t.promise,yield this._loadMoreMessages(e),t.resolve(),this.pendingLoadMore=void 0}))}_loadMoreMessages(e=30){return c(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const s=t.value.windowEnd.cursor,n=yield ge({count:e,cursor:s,conversationId:this.conversationId,realtimeClient:this.realtimeClient}),r=this.getLoadMoreSeq();this.mutate(r,(e=>null===e.value.windowEnd||s!==e.value.windowEnd.cursor?e:n.ok?null===n.value.messages?(console.warn("[TalkJS] When loading more messages, the conversation no longer existed. We should have been told about this."),e):ve({seq:r,prevState:e.value,messages:n.value.messages,cursor:n.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):n)),yield this.emitMutex.runExclusive((()=>this.emit(r)))}))}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=u({},s.value.stores),r=new pe(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 pe(this.conversationId,i,this.realtimeClient),n[i]=a);const o=new fe(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 w({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=u({},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 e=new pe(this.conversationId,t.newLastMessage,this.realtimeClient);n[e.messageId]=e;const s=t.newLastMessage.referencedMessageId;let i;null===s?i=null:s in n?i=n[s]:(i=new pe(this.conversationId,s,this.realtimeClient),n[s]=i);const a=new fe(t.newLastMessage.createdAt,e,i);r.push(a)}const i=void 0!==t.newLastMessage?e:s.value.lastMessageChanged;return w({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),w({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),w({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getMessageFromCache(e){return c(this,null,(function*(){const t=yield this.mostRecentState.resultPromise;if(!t.ok)return C("NOT_IN_CACHE");if(null===t.value.stores)return C("NOT_IN_CACHE");const s=t.value.stores[e];return void 0===s?C("NOT_IN_CACHE"):s.getFromCache()}))}}function ge(e){return c(this,arguments,(function*({cursor:e,realtimeClient:t,conversationId:s,count:n}){const r={limit:n,cursor:e},i=yield t.call("GET",["me","conversations",s,"messages"],r,{bypassCache:!0});if(i.ok){const{data:e,cursor:t}=i.value.data;return w({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?w({messages:null,nextCursor:null}):i}))}function ve({seq:e,prevState:t,messages:s,cursor:n,conversationId:r,realtimeClient:i}){var a,o,l,c;const h=t?u({},t.stores):{};for(const u of s)if(void 0===h[u.id]){const e=new pe(r,u,i);h[e.messageId]=e}for(const u of s){const e=u.referencedMessageId;if(e&&void 0===h[e]){const t=new pe(r,e,i);h[t.messageId]=t}}const d=t?[...t.inWindow]:[];for(const u of s)d.push(new fe(u.createdAt,h[u.id],u.referencedMessageId?h[u.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 w(null===n?{lastChanged:e,lastMessageChanged:p,stores:h,inWindow:d,windowEnd:null}:{lastChanged:e,lastMessageChanged:p,stores:h,inWindow:d,windowEnd:{cursor:n,oldestMessageTs:s[s.length-1].createdAt}})}class be extends K{constructor(e,t,s,n){super(s,n),this.convDataStore=e,this.realtimeClient=t,this.unsubscribeDebounceMs=0}fetchInitial(e){return c(this,null,(function*(){return w({lastChanged:e,store:this.convDataStore})}))}teardownNested(e){e.store.unsubscribe()}anyChildChanged(e,t,s){return c(this,null,(function*(){return s.store.store.changedBetween(e,t)}))}equal(e,t){return!0}loadNested(e,t){return c(this,null,(function*(){return t.store.store.getDeep(e)}))}getFromCache(){return c(this,null,(function*(){return this.convDataStore.store.getFromCache()}))}}function ye(e,t){for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t(e[s],s)}function we(e,t){return function(e){let s={};return ye(e,((e,n)=>{const[r,i]=(([e,s])=>[e,t(s,e)])([n,e],0);s[r]=i})),s}(e)}class Ce extends K{constructor(e,t,s,n){super(s,n),this.conversationId=e,this.realtimeClient=t,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return c(this,null,(function*(){const t=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId,"typing"],{},{bypassCache:!0});if(!t.ok&&"server"===t.where&&404===t.value.status)return w({data:null,lastChanged:e});if(!t.ok&&"server"===t.where&&403===t.value.status&&"NOT_A_PARTICIPANT"===t.value.errorCode)return w({data:null,lastChanged:e});if(!t.ok)return t;const s=t.value.data;return s.many?w({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e}):w({data:s,userSubscriptions:we(s.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t]))),lastChanged:e})}))}equal(e,t){return J(e.data,t.data)}loadNested(e,t){return c(this,null,(function*(){if(null===t.data)return w({snapshot:null,lastChanged:t.lastChanged});if(t.data.many)return w({snapshot:{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));return w({snapshot:{users:a,many:!1},lastChanged:Math.max(t.lastChanged,...o)})}))}typingAvailable(e,t){this.mutate(e,(()=>w({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,(s=>{if(null===s.value.data)return s;if(void 0===t.diff.many){if(!0===s.value.data.many)return s;const n=u({},s.value.data.usersTyping),r=u({},s.value.userSubscriptions);return ye(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])})),w({data:{usersTyping:n,many:!1},userSubscriptions:r,lastChanged:e})}if(!0===t.diff.many)return s.value.data.many?s:w({data:{usersTyping:null,many:!0},userSubscriptions:{},lastChanged:e});if(!1===t.diff.many){if(!1===s.value.data.many)return s;const n=we(t.diff.usersTyping,((e,t)=>this.realtimeClient.internalSubscribe(["users",t])));return w({data:t.diff,userSubscriptions:n,lastChanged:e})}throw t.diff,"Unreachable"}))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.data?t:w({data:null,lastChanged:e})))}teardownNested(e){e.data&&ye(e.userSubscriptions,(e=>e.unsubscribe()))}anyChildChanged(e,t,s){return c(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 Ae extends Z{constructor(e,t,s){super(),this.conversationId=e,this.participantData=t,this.realtimeClient=s}fetchInitial(e){return c(this,null,(function*(){return w({lastChanged:e,user:this.realtimeClient.internalSubscribe(["users",this.participantData.id]),data:this.participantData})}))}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)&&J(e.data,t.data)}teardownNested(e){var t;null==(t=e.user)||t.unsubscribe()}anyChildChanged(e,t,s){return c(this,null,(function*(){var n;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 c(this,null,(function*(){if(null===t.data)return w({snapshot:null});const s=yield t.user.store.getDeep(e);if(!1===s.ok)return s;const n=s.value.snapshot;return w({snapshot:this.realtimeClient.createParticipantSnapshotPreloaded(t.data,n)})}))}participantEdited(e,t){this.mutate(e,(s=>null===s.value.data?s:w({lastChanged:e,user:s.value.user,data:{id:s.value.data.id,access:L(s.value.data.access,t.diff.access),notify:L(s.value.data.notify,t.diff.notify),joinedAt:s.value.data.joinedAt}})))}participantDeleted(e,t){this.mutate(e,(t=>null===t.value.data?t:(this.teardownNested(t.value),w({lastChanged:e,user:null,data:null}))))}getFromCache(){return c(this,null,(function*(){const e=yield this.mostRecentState.resultPromise;return e.ok?null===e.value.data?A({status:404,errorCode:"PARTICIPANT_NOT_FOUND",reasons:["No participant with that ID exists"]}):w({status:200,data:e.value.data}):C("NOT_IN_CACHE")}))}}class Ee extends K{constructor(e,t,s,n){super(s,n),this.conversationId=e,this.realtimeClient=t,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}fetchInitial(e){return c(this,null,(function*(){const t=yield ke({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:10});return t.ok?null===t.value.participants?w({lastChanged:e,stores:null,inWindow:null,windowEnd:null})