@talkjs/core 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,6 +69,11 @@ If you encounter any problems with `@talkjs/core`, please open a [chat with supp
69
69
 
70
70
  ## Changelog
71
71
 
72
+ ### 1.0.1
73
+
74
+ - Fixed a bug with `ConversationRef.subscribe` where it would emit the same snapshot multiple times in a row, when old messages were edited or deleted.
75
+ - Exported types for `GenericFileMetadata`, `AudioFileMetadata`, `ImageFileMetadata`, `VideoFileMetadata`, and `VoiceRecordingFileMetadata`
76
+
72
77
  ### 1.0.0
73
78
 
74
79
  - Initial Release
@@ -1,2 +1,2 @@
1
- "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},c=(e,t)=>s(e,n(t)),l=(e,t,s)=>new Promise(((n,r)=>{var i=e=>{try{o(s.next(e))}catch(Ne){r(Ne)}},a=e=>{try{o(s.throw(e))}catch(Ne){r(Ne)}},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 l(this,arguments,(function*(e,t,{initialDelay:s,maxDelay:n,log:r,shouldRetry:i=g}){return t().catch((a=>l(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 A(e){return{ok:!1,where:"client",value:e}}function C(e){return{ok:!1,where:"server",value:e}}function E(){const e={},t=new Promise((t=>{e.ok=e=>l(this,null,(function*(){return t(w(e))})),e.clientErr=e=>t(A(e)),e.serverErr=e=>t(C(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.throttler=new S,this.stateMachine=new y("ReconnectingSocket",["STOPPED","WAITING_FOR_THROTTLER","CONNECTING","READY","TERMINATED"],{queueAutoReconnect:{from:["READY","CONNECTING"],to:"WAITING_FOR_THROTTLER",afterTransition:({from:e})=>{"READY"===e&&this.handlers.onClose(),this.throttler.request((()=>{this.stateMachine.transition("connect")}))}},stop:{from:["WAITING_FOR_THROTTLER","CONNECTING","READY"],to:"STOPPED",afterTransition:({from:e})=>{var t;"READY"===e&&this.handlers.onClose(),null==(t=null==this?void 0:this.socket)||t.close(1e3),this.socket=null,this.throttler.resetDelay()}},connect:{from:["STOPPED","WAITING_FOR_THROTTLER"],to:"CONNECTING",afterTransition:()=>this.createWebSocket()},ready:{from:["CONNECTING"],to:"READY",afterTransition:()=>{this.throttler.resetDelay(),this.handlers.onOpen()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{var e;null==(e=this.socket)||e.close(1e3)}}})}stopWs(){"TERMINATED"!==this.stateMachine.state&&this.stateMachine.transition("stop")}startWs(){this.stateMachine.canTransition("connect")&&this.stateMachine.transition("connect")}createWebSocket(){var e;null==(e=null==this?void 0:this.socket)||e.close(1e3);const t=new(function(){if(k)return k;if(globalThis.WebSocket)return globalThis.WebSocket;throw new Error("Missing WebSocket implementation")}())(this.realtimeUrl);this.socket=t;const s=()=>this.stateMachine.transition("ready");t.addEventListener("open",s),t.addEventListener("message",this.handlers.onMessage);const n=()=>{t.removeEventListener("open",s),t.removeEventListener("close",n),t.removeEventListener("message",this.handlers.onMessage),"TERMINATED"!==this.stateMachine.state&&"STOPPED"!==this.stateMachine.state&&this.stateMachine.transition("queueAutoReconnect")};t.addEventListener("close",n)}send(e){return"READY"===this.stateMachine.state?(this.socket.send(e),w(void 0)):A("SOCKET_NOT_READY")}terminate(){if(this.socket)if("terminate"in this.socket)this.socket.terminate();else if("dispatchEvent"in this.socket){this.socket.close(1e3);const e=new Event("close"),t=Object.assign(e,{code:1e3,reason:"",wasClean:!0});this.socket.dispatchEvent(t)}else this.socket.close(1e3)}destroy(){this.stateMachine.transition("destroy")}}let S=class{constructor(){this.initialDelayMs=200+200*Math.random(),this.exponentialFactor=1.2,this.maxDelayMs=1e4,this.currentDelayMs=this.initialDelayMs}request(e){const t=m(this.currentDelayMs,.05);f(this.currentDelayMs).then((()=>e())),this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs)}resetDelay(){this.currentDelayMs=this.initialDelayMs}};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 D{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 F{constructor(e,t){this.handlers=t,this.seqCounter=new I,this.responseHandlers={},this.heartbeats=new B(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 l(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 B{constructor(e){this.connection=e,this.clientInactivityTimer=new D(25e3),this.serverInactivityTimer=new D(1e4),this.serverTimeoutTimer=new D(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 M{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:()=>l(this,null,(function*(){yield this.renewSession()}))},logInFailed:{from:["LOGGING_IN"],to:"LOGGING_IN",afterTransition:()=>l(this,null,(function*(){this.authProvider.refreshToken(),yield this.renewSession()}))},scheduledReauth:{from:["READY"],to:"RENEWING_SESSION",afterTransition:()=>l(this,null,(function*(){yield this.renewSession()}))},scheduledReauthFailed:{from:["RENEWING_SESSION"],to:"RENEWING_SESSION",afterTransition:()=>l(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:()=>l(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 F(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 l(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 R{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 D(3e3),this.connection=new M(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 l(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 N{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 R(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 l(this,null,(function*(){for(;"PROCESSING_QUEUE"===this.stateMachine.state;){const e=this.dequeue();if(!e)return void this.stateMachine.transition("ready");this.connection.call(e.method,e.path,e.data).then((t=>{e.deferred.resolve(t)})),yield new Promise((e=>setTimeout(e,100)))}}))}isConnected(){return"READY"===this.stateMachine.state||"PROCESSING_QUEUE"===this.stateMachine.state}}const O="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class P{constructor(e,t){this.clearPendingBatch=e,this.sendCalls=t,this.sent=!1,O((()=>this.send()))}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class _ extends P{constructor(e,t){super(t,(()=>{this.sendSubscribe(),this.sendGet()})),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e,t){return _.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 l(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 U extends P{constructor(e,t,s){super(s,(()=>this.sendMutate())),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e,t){return!!U.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 l(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(c(u({},t),{data:{}})):e.serverErr(t)}}))}}class j{constructor(e,t,s){this.pendingBatch=null,this.connection=new N(e,t,s)}call(e,t,s){return l(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(_.isCorrectBatchTypeFor(e,t))return new _(this.connection,(()=>this.pendingBatch=null));if(U.isCorrectBatchTypeFor(e,t)){const e=t[1];return new U(e,this.connection,(()=>this.pendingBatch=null))}return null}}const $={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class W{constructor(e,t,s){this.throttler=new q,this.alive=!0,this.connection=new j(e,t,s)}call(e,t,s){return l(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=$[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 A("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==r.value&&("SOCKET_NOT_READY"!==r.value?r.value:yield this.throttler.wait())}return A("SESSION_DESTROYED")}))}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class q{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 H(e){return e.map((e=>encodeURIComponent(e))).join()}class G{constructor(){this.paths={}}add(e){this.paths[H(e)]=e}delete(e){delete this.paths[H(e)]}has(e){return Object.hasOwnProperty.call(this.paths,H(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach((t=>e(t)))}}class L{constructor(e,t,s){this.handlers=s,this.targetSubscriptions=new G,this.connection=new W(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 l(this,null,(function*(){return this.targetSubscriptions.add(e),this.connection.call("SUBSCRIBE",e,{})}))}unsubscribe(e){return l(this,null,(function*(){return this.targetSubscriptions.delete(e),this.connection.call("UNSUBSCRIBE",e,{})}))}resubscribe(e){return l(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 z(e,t){return void 0===t?e:t}function J(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 Y(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(!Y(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(!Y(e[n],t[n]))return!1}}return!0}class Q{constructor(){this.prev=Promise.resolve()}runExclusive(e){return l(this,null,(function*(){const t=this.prev.then((()=>e()));return this.prev=t,t}))}}class V{constructor(e,t){this.onTeardown=t,this.error=null,this.lastLoadedState=void 0,this.lastGoodState=Promise.resolve(void 0),this.initialised=!1,this.getDeepMutex=new Q,this.lastDeep=void 0;const s={seq:0,resultPromise:new Promise((e=>setTimeout(e))).then((()=>l(this,null,(function*(){const e=yield this.fetchInitial(0);return this.initialised=!0,e}))))};this.lastState=s,this.states=[s],this.lastLoadedState=void 0}set lastState(e){const t=this.lastGoodState;this.lastGoodState=e.resultPromise.then((e=>e.ok?e.value:t)),e.resultPromise.then((e=>{e.ok||this.setError(e)})),this._lastState=e}get lastState(){return this._lastState}refetchInitial(e){return l(this,null,(function*(){const t=this.lastGoodState,s=this.fetchInitial(e),[n,r]=yield Promise.all([t,s]);return void 0===n?r:r.ok&&this.equal(n,r.value)?w(n):r}))}refetch(e){if(this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.lastState=t,this.states.push(t)}mutate(e,t){if(this.error)return void console.warn("[TalkJS] Attempting to mutate a terminated store");if(!this.initialised&&e>this._lastState.seq)return;if(e<this.lastState.seq)throw"Seq is in the past";const s={seq:e,resultPromise:this.lastState.resultPromise.then((e=>e.ok?t(e):e))};this.lastState=s,this.states.push(s)}getDeep(e){return l(this,null,(function*(){return this.getDeepMutex.runExclusive((()=>l(this,null,(function*(){if(this.error)return this.error;if(this.lastLoadedState&&e<this.lastLoadedState.seq)throw`Trying to load state ${e} when we have previously loaded ${this.lastLoadedState.seq}`;for(;this.states.length&&this.states[0].seq<=e;)this.lastLoadedState=this.states.shift();if(void 0===this.lastLoadedState)throw`[TalkJS] Tried to load state ${e} which is before the store was created`;const t=yield this.lastLoadedState.resultPromise;if(!t.ok)return t;const s=yield this.loadNested(e,t.value);return s.ok&&this.lastDeep&&s.value.lastChanged===this.lastDeep.value.lastChanged?this.lastDeep:(s.ok?this.lastDeep=s:this.setError(s),s)}))))}))}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,t,s){super(e,s),this.emitMutex=t,this.unsubscribeTimer=new K,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive((()=>l(this,null,(function*(){yield this.emit(e)}))))}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(A("UNSUBSCRIBED"))}),this.unsubscribeDebounceMs)}emit(e){return l(this,null,(function*(){var t;if(this.lastEmitSeq&&this.lastEmitSeq>=e)return;if(!1===(null==(t=this.lastEmitResult)?void 0:t.ok))return;const s=this.lastEmitSeq;this.lastEmitSeq=e;const n=yield this.getDeep(e);this.lastEmitResult,this.lastEmitResult=n,n.ok?(void 0===s||s<n.value.lastChanged)&&this.listeners.forEach((e=>e(n))):this.listeners.forEach((e=>e(n)))}))}}class K{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 X extends Z{constructor(e,t,s,n,r){super(e,n,r),this.userId=t,this.realtimeClient=s,this.unsubscribeDebounceMs=1e4}fetchInitial(e){return l(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 Y(e.snapshot,t.snapshot)}loadNested(e,t){return l(this,null,(function*(){return w(t)}))}userCreated(e,t){this.mutate(e,(()=>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:z(n.name,t.diff.name),custom:J(n.custom,t.diff.custom),locale:z(n.locale,t.diff.locale),photoUrl:z(n.photoUrl,t.diff.photoUrl),role:z(n.role,t.diff.role),welcomeMessage:z(n.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})}))}getFromCache(){return l(this,null,(function*(){const e=yield this.lastState.resultPromise;return e.ok?null===e.value.snapshot?C({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}}):A("NOT_IN_CACHE")}))}teardownNested(e){}}const ee=/\uFE0F/g,te=String.fromCharCode(8205);const se={":)":"1f642",":o":"1f62e",":]":"1f60f",":d":"1f600",xd:"1f61d",":p":"1f61c",":@":"1f621",":[":"1f621",":(":"1f626",":'(":"1f62d",":’(":"1f62d",":*":"1f618",":/":"1f614",":s":"1f616",":|":"1f633",":$":"263a",":x":"1f637","<3":"2764","</3":"1f494"},ne={":thumbsup:":"1f44d",":thumbsdown:":"1f44e",":poop:":"1f4a9"};var re,ie={};function ae(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 oe(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1");return decodeURIComponent(t)}function ue(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(re)return ie;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}re=1,Object.defineProperty(ie,"__esModule",{value:!0}),ie.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},ie.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){}})(ue||(ue={}));const ce=ue,le=/^\/.*[^\\]\/[im]*$/;function he(e){return!!le.test(e)&&!de(e).test("")}function de(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 pe{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:s,allowedMatches:n,forbiddenMatches:r,suppressLinks:i,suppressEmailAddresses:a,suppressPhoneNumbers:o,replacement:u}){ce.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(he).map((e=>de(e))),this.forbiddenMatches=(r||[]).filter(he).map((e=>de(e))),ce((()=>this.allowedMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),ce((()=>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 fe(e,t){return e.map((e=>function(e,t){if("text"===e.type)return me(e.children,function(e){var t,s,n,r,i,a,o,u,c,l,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:[],emojis:null!=(i=e.emojis)&&i,highlight:null!=(a=e.highlight)?a:[],contactInfo:null!=(o=e.contactInfo)&&o,suppression:null!=(u=e.suppression)?u:new pe({mode:"off"}),contactInfoHiddenText:null!=(h=null!=(l=e.contactInfoHiddenText)?l:null==(c=e.suppression)?void 0:c.replacement)?h:p,customEmojiUrls:null!=(d=e.customEmojiUrls)?d:{}}}(t));if("file"===e.type&&"video"===e.subtype)return`🎥 ${oe(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${oe(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${oe(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,`📎 ${oe(e.url)}`):"location"===e.type?"📍":""}(e,t))).join("\n\n")}function me(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 me(e.children,t);case"bulletlist":case"bulletList":return"\n"+me(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+me(e.children,t)+"\n";case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"customemoji":case"customEmoji":return e.text;case"suppressed":return t.contactInfoHiddenText;case"mention":return`@${e.text}`;case"emoji":return"images"===t.emojis?"":"unicode"===t.emojis?function(e){if(":arslan:"===e.text)return":arslan:";const t=function({text:e,kind:t}){var s,n,r;return"unicode"===t?function(e){const t=[];let s=0,n=0,r=0;for(;r<e.length;)s=e.charCodeAt(r++),n?(t.push((65536+(n-55296<<10)+(s-56320)).toString(16)),n=0):55296<=s&&s<=56319?n=s:t.push(s.toString(16));return t.join("-")}((r=e).indexOf(te)<0?r.replace(ee,""):r):null!=(s=ne[e])?s:/;-?\)/.test(n=e)?"1f609":(n=n.replace(/;/g,":"),/:-o/i.test(n)?"1f631":(n=n.replace(/-/g,"").toLowerCase(),se[n]))}(e);return t?String.fromCodePoint(parseInt(t,16)):e.text}(e):e.text}})).join("")}class ge extends V{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 l(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:fe(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 Y(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}loadNested(e,t){return l(this,null,(function*(){var s,n,r,i;const a=yield null==(n=null==(s=t.sender)?void 0:s.store)?void 0:n.getDeep(e);if(!1===(null==a?void 0:a.ok))return a;if(null===t.data)return w({lastChanged:t.lastChanged,snapshot:null});const o=null==a?void 0:a.value;return w({lastChanged:Math.max(t.lastChanged,null!=(r=null==o?void 0:o.lastChanged)?r:0),snapshot:{sender:null!=(i=null==o?void 0:o.snapshot)?i: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:fe(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:z(s.value.data.editedAt,t.diff.editedAt),custom:J(s.value.data.custom,t.diff.custom),content:z(s.value.data.content,t.diff.content)}})))}messageDeleted(e,t){this.mutate(e,(s=>null===s.value.data?s:this.messageId===t.messageId?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 l(this,null,(function*(){var e;const t=yield this.lastState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.data)return C({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:c(u({},o.data),{senderId:null!=(e=null==n?void 0:n.store.userId)?e:null})})}))}}class ve extends V{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 l(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){}loadNested(e,t){return l(this,null,(function*(){var s,n,r,i;const a=yield t.dataStore.getDeep(e);if(!a.ok)return a;const o=a.value;if(null===o.snapshot)return w({lastChanged:a.value.lastChanged,snapshot:null});const u=yield null==(s=t.referencedDataStore)?void 0:s.getDeep(e);if(u&&!u.ok)return u;const c=null!=(n=null==u?void 0:u.value)?n:null,l=null!=(r=null==c?void 0:c.snapshot)?r:null;return w({lastChanged:Math.max(o.lastChanged,null!=(i=null==c?void 0:c.lastChanged)?i:0),snapshot:{id:o.snapshot.id,type:o.snapshot.type,sender:o.snapshot.sender,custom:o.snapshot.custom,createdAt:o.snapshot.createdAt,editedAt:o.snapshot.editedAt,referencedMessage:l,origin:o.snapshot.origin,plaintext:o.snapshot.plaintext,content:o.snapshot.content}})}))}}class be extends Z{constructor(e,t,s,n,r){super(e,t,r),this.conversationId=s,this.realtimeClient=n,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}listen(e){return this.onlyUsedInternally&&this.lastState.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 l(this,null,(function*(){const t=this.onlyUsedInternally?1:30,s=yield ye({realtimeClient:this.realtimeClient,conversationId:this.conversationId,count:t});return s.ok?null===s.value.messages?w({lastChanged:e,stores:null,inWindow:null,windowEnd:null}):we({seq:e,messages:s.value.messages,cursor:s.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):s}))}teardownNested(e){Ae(e)}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!Y(Object.keys(e.stores),Object.keys(t.stores))&&!!Y(e.inWindow.map((e=>e.messageId)),t.inWindow.map((e=>e.messageId)))&&Y(e.windowEnd,t.windowEnd)}loadNested(e,t){return l(this,null,(function*(){if(null===t.stores)return w({snapshot:null,loadedAll:!0,lastChanged:t.lastChanged});const s=yield Promise.all(t.inWindow.map((t=>t.getDeep(e)))),n=s.find((e=>!e.ok));if(n)return n;const r=s,i=r.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot)),a=Math.max(t.lastChanged,...r.map((e=>e.value.lastChanged)));return w({snapshot:i,loadedAll:null===t.windowEnd,lastChanged:a})}))}loadMore(e){return l(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 l(this,null,(function*(){const t=yield this.lastState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const s=t.value.windowEnd.cursor,n=yield ye({count:e,cursor:s,conversationId:this.conversationId,realtimeClient:this.realtimeClient}),r=this.lastState.seq+1e-6;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):we({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 ge(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 ge(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new ve(e,t.state.createdAt,r,a),c=[...s.value.inWindow,o];return c.sort(((e,t)=>t.createdAt-e.createdAt)),w({lastChanged:e,stores:n,inWindow:c,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 s=new ge(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 ge(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new ve(e,t.newLastMessage.createdAt,s,a);r.push(o)}return w({lastChanged:e,stores:n,inWindow:r,windowEnd:s.value.windowEnd})}))}conversationCleared(e,t){this.mutate(e,(t=>(Ae(t.value),w({lastChanged: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&&Ae(e.value)})),e):s))}sideDeleted(e,t){this.mutate(e,(t=>(Ae(t.value),w({lastChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getMessageFromCache(e){return l(this,null,(function*(){const t=yield this.lastState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.stores)return A("NOT_IN_CACHE");const s=t.value.stores[e];return void 0===s?A("NOT_IN_CACHE"):s.getFromCache()}))}}function ye(e){return l(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 we({seq:e,prevState:t,messages:s,cursor:n,conversationId:r,realtimeClient:i}){const a=t?u({},t.stores):{};for(const u of s)if(void 0===a[u.id]){const t=new ge(e,r,u,i);a[t.messageId]=t}for(const u of s){const t=u.referencedMessageId;if(t&&void 0===a[t]){const s=new ge(e,r,t,i);a[s.messageId]=s}}const o=t?[...t.inWindow]:[];for(const u of s)o.push(new ve(e,u.createdAt,a[u.id],u.referencedMessageId?a[u.referencedMessageId]:null));return o.sort(((e,t)=>t.createdAt-e.createdAt)),w(null===n?{lastChanged:e,stores:a,inWindow:o,windowEnd:null}:{lastChanged:e,stores:a,inWindow:o,windowEnd:{cursor:n,oldestMessageTs:s[s.length-1].createdAt}})}function Ae(e){if(e.stores){const t=A("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t))),e.inWindow.forEach((e=>e.setError(t)))}}class Ce extends Z{constructor(e,t,s,n,r){super(e,t,r),this.conversationId=s,this.realtimeClient=n,this.unsubscribeDebounceMs=5e3}fetchInitial(e){return l(this,null,(function*(){const t=this.realtimeClient.internalSubscribe(["me","conversations",this.conversationId,"messages"]),s=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId],{},{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 w({lastChanged:e,snapshot:n,messageWindowStore:t})}))}teardownNested(e){var t;null==(t=e.messageWindowStore)||t.unsubscribe()}equal(e,t){return Y(e.snapshot,t.snapshot)}loadNested(e,t){return l(this,null,(function*(){var s;if(!t.snapshot)return w({lastChanged:t.lastChanged,snapshot:null,loadedAll:!0});const n=yield t.messageWindowStore.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 w({lastChanged:Math.max(t.lastChanged,n.value.lastChanged),snapshot:c(u({},t.snapshot),{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):w({lastChanged:e,snapshot:Ee(s.value.snapshot,t.diff),messageWindowStore:s.value.messageWindowStore})))}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):w({lastChanged:e,snapshot:Ee(s.value.snapshot,t.diff),messageWindowStore:s.value.messageWindowStore})))}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):w({lastChanged:e,snapshot:Ee(s.value.snapshot,t.diff),messageWindowStore:s.value.messageWindowStore})))}sideCreated(e,t){this.mutate(e,(s=>s.value.snapshot?s:w({lastChanged:e,snapshot:t.state,messageWindowStore:s.value.messageWindowStore})))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.snapshot?t:w({lastChanged:e,snapshot:null,messageWindowStore:t.value.messageWindowStore})))}getFromCache(){return l(this,null,(function*(){const e=yield this.lastState.resultPromise;return e.ok&&e.value.snapshot?w({status:200,data:e.value.snapshot}):A("NOT_IN_CACHE")}))}}function Ee(e,t){const s=t;return{id:e.id,createdAt:e.createdAt,subject:z(e.subject,s.subject),photoUrl:z(e.photoUrl,s.photoUrl),welcomeMessages:z(e.welcomeMessages,s.welcomeMessages),custom:J(e.custom,s.custom),lastMessageAt:z(e.lastMessageAt,s.lastMessageAt),unreadMessageCount:z(e.unreadMessageCount,s.unreadMessageCount),isUnread:z(e.isUnread,s.isUnread),access:z(e.access,s.access),notify:z(e.notify,s.notify),readUntil:z(e.readUntil,s.readUntil),joinedAt:e.joinedAt}}class ke{constructor(e,t,s){this.realtimeClient=s,this.userStores={},this.messageWindowStores={},this.conversationStores={},this.emitMutex=new Q,this.seqOffset=0,this.seqInThisConnection=0,this.refetchOnNextNetworkLoss=!0,this.connection=new L(e,t,{onUpstreamRestarting:()=>{this.refetchOnNextNetworkLoss=!1},onReady:()=>{this.refetchOnNextNetworkLoss=!0},onResubscribeSent:()=>{if(this.seqOffset+=this.seq,this.seqInThisConnection=0,this.refetchOnNextNetworkLoss){this.seqOffset++;const e=this.seq;this.refetchAll(e),this.emitAll(e)}},onResubscribeError:(e,t)=>{var s;null==(s=this.getStoreIfExists(e))||s.setError(t)},onPublish:(e,t)=>{this.seqInThisConnection=e;const s=this.seq;for(const n of t)this.handlePublish(s,n);this.emitAll(s)}})}get seq(){return this.seqOffset+this.seqInThisConnection}refetchAll(e){for(const t of Object.values(this.userStores))t.refetch(e);for(const t of Object.values(this.messageWindowStores))t.refetch(e);for(const t of Object.values(this.conversationStores))t.refetch(e)}emitAll(e){return this.emitMutex.runExclusive((()=>l(this,null,(function*(){yield Promise.all([...Object.values(this.userStores).map((t=>t.emit(e))),...Object.values(this.messageWindowStores).map((t=>t.emit(e))),...Object.values(this.conversationStores).map((t=>t.emit(e)))])}))))}handlePublish(e,t){switch(t.type){case"user.created":return this.handleUserCreated(e,t);case"user.edited":return this.handleUserEdited(e,t);case"side.created":return this.handleSideCreated(e,t);case"side.edited":return this.handleSideEdited(e,t);case"side.deleted":return this.handleSideDeleted(e,t);case"participant.edited":return this.handleParticipantEdited(e,t);case"conversation.edited":return this.handleConversationEdited(e,t);case"message.created":return this.handleMessageCreated(e,t);case"message.edited":return this.handleMessageEdited(e,t);case"message.deleted":return this.handleMessageDeleted(e,t);case"messages.cleared":case"conversation.cleared":return this.handleConversationCleared(e,t)}}handleUserCreated(e,t){const s=this.userStores[t.userId];s&&s.userCreated(e,t)}handleUserEdited(e,t){const s=this.userStores[t.userId];s&&s.userEdited(e,t)}handleSideCreated(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.sideCreated(e,t);const n=this.conversationStores[t.conversationId];n&&n.sideCreated(e,t)}handleSideEdited(e,t){const s=this.conversationStores[t.conversationId];s&&s.sideEdited(e,t)}handleParticipantEdited(e,t){const s=this.conversationStores[t.conversationId];s&&s.participantEdited(e,t)}handleConversationEdited(e,t){const s=this.conversationStores[t.conversationId];s&&s.conversationEdited(e,t)}handleSideDeleted(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.sideDeleted(e,t);const n=this.conversationStores[t.conversationId];n&&n.sideDeleted(e,t)}handleMessageCreated(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.messageCreated(e,t)}handleMessageEdited(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.messageEdited(e,t)}handleMessageDeleted(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.messageDeleted(e,t)}handleConversationCleared(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.conversationCleared(e,t)}call(e,t,s,n){return l(this,null,(function*(){if(!n.bypassCache){if("GET"===e&&p(t,["users","*"])){const e=t[1],s=this.userStores[e];if(s){const e=yield s.getFromCache();if("NOT_IN_CACHE"!==e.value)return e}}if("GET"===e&&p(t,["me","conversations","*","messages","*"])){const e=t[2],s=this.messageWindowStores[e];if(s){const e=t[3],n=yield s.getMessageFromCache(e);if("NOT_IN_CACHE"!==n.value)return n}}}return this.connection.call(e,t,s)}))}subscribe(e,t){const s=this.getOrCreateStore(e),n=b(),r=b();n.promise.catch((()=>{})),r.promise.catch((()=>{}));const i={state:{type:"pending",latestSnapshot:void 0},connected:n.promise,terminated:r.promise,loadMore:e=>l(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(d(`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}getOrCreateStore(e){if(p(e,["users","*"])){const t=e[1];if(Object.hasOwnProperty.call(this.userStores,t))return this.userStores[t];{this.connection.subscribe(["users",t]).then((e=>{e.ok||s.setError(e)}));const e=this.seq,s=new X(e,t,this.realtimeClient,this.emitMutex,(()=>{delete this.userStores[t],this.connection.unsubscribe(["users",t])}));return this.userStores[t]=s,s}}if(p(e,["me","conversations","*"])){const t=e[2];if(Object.hasOwnProperty.call(this.conversationStores,t))return this.conversationStores[t];{this.connection.subscribe(["me","conversations",t]).then((t=>{t.ok||e.setError(t)}));const e=new Ce(this.seq,this.emitMutex,t,this.realtimeClient,(()=>{delete this.conversationStores[t],this.connection.unsubscribe(["me","conversations",t])}));return this.conversationStores[t]=e,e}}if(p(e,["me","conversations","*","messages"])){const t=e[2];if(Object.hasOwnProperty.call(this.messageWindowStores,t))return this.messageWindowStores[t];{this.connection.subscribe(["me","conversations",t,"messages"]).then((t=>{t.ok||e.setError(t)}));const e=new be(this.seq,this.emitMutex,t,this.realtimeClient,(()=>{delete this.messageWindowStores[t],this.connection.unsubscribe(["me","conversations",t,"messages"])}));return this.messageWindowStores[t]=e,e}}throw new Error("Unrecognised subscribe path: "+e)}getStoreIfExists(e){var t,s;if(p(e,["users","*"])){const s=e[1];return null!=(t=this.userStores[s])?t:null}if(p(e,["me","conversations","*","messages"])){const t=e[2];return null!=(s=this.messageWindowStores[t])?s:null}throw new Error("Unrecognised subscribe path: "+e)}destroy(){this.userStores={},this.messageWindowStores={},this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class xe{constructor(e,t,s){this.userId=t,this.alive=!0,this.connection=new ke(e,s,this),s.onTokenRefreshFailed((()=>{this.destroy()}))}call(e,t,s){return l(this,arguments,(function*(e,t,s,n={}){return this.alive?this.connection.call(e,t,s,n):A("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()}listMessages(e,t){return l(this,null,(function*(){const s=yield this.call("GET",["me","conversations",e,"messages"],t);if(!s.ok)return Se(s,"Listing messages in "+e);const n=s.value.data.data,r=yield Promise.all(n.map((t=>this.createMessageSnapshot(t,e)))),i=r.find((e=>!e.ok));return void 0===i||i.ok?w(r.map((({value:e})=>e))):i}))}createConversationSnapshotPreloaded(e,t){return{id:e.id,subject:e.subject,photoUrl:e.photoUrl,welcomeMessages:e.welcomeMessages,custom:e.custom,createdAt:e.createdAt,joinedAt:e.joinedAt,lastMessageAt:e.lastMessageAt,unreadMessageCount:e.unreadMessageCount,isUnread:e.isUnread,access:e.access,notify:e.notify,lastMessage:t,readUntil:e.readUntil}}createUserSnapshot(e){return{id:e.id,name:e.name,custom:e.custom,locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage}}createParticipantSnapshotPreloaded(e,t){return"None"===e.access?null:{user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt}}createMessageSnapshot(e,t){return l(this,null,(function*(){const s=null===e.senderId?Promise.resolve(w(null)):this.getUser(e.senderId),n=null===e.referencedMessageId?Promise.resolve(w(null)):this.getReferencedMessage(t,e.referencedMessageId),r=yield s;if(!r.ok)return r;const i=yield n;return i.ok?w(this.createMessageSnapshotPreloaded(e,r.value,i.value)):i}))}getReferencedMessage(e,t){return l(this,null,(function*(){const s=yield this.call("GET",["me","conversations",e,"messages",t],{});if(!s.ok&&"server"===s.where&&404===s.value.status)return w(null);if(!s.ok&&"server"===s.where&&403===s.value.status&&"NOT_A_PARTICIPANT"===s.value.errorCode)return w(null);if(!s.ok)return Se(s,`Fetching referenced message ${t} in conversation ${e}`);const n=s.value.data,r=yield this.getUser(n.senderId);if(!r.ok)return r;const i=r.value;return w(this.createReferencedMessageSnapshotPreloaded(n,i))}))}getUser(e){return l(this,null,(function*(){const t=yield this.call("GET",["users",e],{includePrivateFields:!1});return t.ok||"server"!==t.where||404!==t.value.status?t.ok?w(this.createUserSnapshot(t.value.data)):Se(t,"Get user "+e):w(null)}))}createMessageSnapshotPreloaded(e,t,s){return{id:e.id,type:e.type,sender:t,referencedMessage:s,custom:e.custom,createdAt:e.createdAt,editedAt:e.editedAt,origin:e.origin,content:e.content,plaintext:fe(e.content,{})}}createReferencedMessageSnapshotPreloaded(e,t){return{id:e.id,type:e.type,sender:t,referencedMessageId:e.referencedMessageId,custom:e.custom,createdAt:e.createdAt,editedAt:e.editedAt,origin:e.origin,content:e.content,plaintext:fe(e.content,{})}}}function Se(e,t){return"server"===e.where?C(c(u({},e.value),{operation:t})):e}function Te(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(d(null!=(s=t.value.operation)?s:e,t.value))}class De{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get(){return l(this,null,(function*(){const e=yield this._realtimeClient.getUser(this.brandedId);return Te("Get user "+this.id,e)}))}set(e){return l(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("PUT",["users",this.brandedId],c(u({},e),{email:t,phone:s}));h("Set user "+this.id,n)}))}createIfNotExists(e){return l(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("POST",["users",this.brandedId],c(u({},e),{email:t,phone:s}));(n.ok||"server"!==n.where||409!=n.value.status)&&h(`Create user ${this.id} if not exists`,n)}))}subscribe(e){return this._realtimeClient.subscribe(["users",this.brandedId],e)}}class Ie{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 l(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],{}),t=yield this._realtimeClient.call("GET",["users",this.brandedUserId],{includePrivateFields:!1}),[s,n]=yield Promise.all([e,t]);if(!s.ok&&"server"===s.where&&404===s.value.status)return null;if(!n.ok&&"server"===n.where&&404===n.value.status)return null;const r=h(`Get participant ${this.userId} in conversation ${this.conversationId}`,s),i=h(`Get user ${this.userId}`,n),a=this._realtimeClient.createUserSnapshot(i);return this._realtimeClient.createParticipantSnapshotPreloaded(r,a)}))}set(){return l(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PUT",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);h(`Set participant ${this.userId} in conversation ${this.conversationId}`,t)}))}edit(){return l(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);h(`Edit participant ${this.userId} in conversation ${this.conversationId}`,t)}))}createIfNotExists(){return l(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("POST",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);(t.ok||"server"!==t.where||409!==t.value.status)&&h(`Add participant ${this.userId} to conversation ${this.conversationId}`,t)}))}delete(){return l(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"participants",this.brandedUserId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&h(`Remove participant ${this.userId} from conversation ${this.conversationId}`,e)}))}}function Fe(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 Be=(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:Be(e.children,t,e.type)}];case"link":return[{type:e.type,url:e.url,children:Be(e.children,t,e.type)}];case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return[{type:e.type,action:e.action,params:e.params,children:Be(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 Me(e,t){return s=>{const n=s;let r=0;const i=[];for(const a of ae(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 Re="’'()[]{}<>:,‒–—―…!.«»-‐?‘’“”;/⁄␠·&@*\\•^¤¢$€£¥₩₪†‡°¡¿¬#№%‰‱¶′§~¨_|¦⁂☞∴‽※".replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var Ne,Oe=((Ne=Oe||{})[Ne.italic=1]="italic",Ne[Ne.strikethrough=2]="strikethrough",Ne[Ne.bold=4]="bold",Ne);const Pe=[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")})),_e={_:1,"*":4,"~":2};function Ue(e){return je(e,0)}function je(e,t=0){const s=Pe[t],n=s?function(e){const t=Me($e.getOrCompute(e,(()=>new RegExp(`(?:^|[\\s${Re}])(?:${e.source})(?=[\\s${Re}]|$)`,"g"))),(e=>{const t=e[0][1],s=e[1]||e[2]||e[3]||e[4]||e[5]||e[6];return[" ",{type:Oe[_e[t]],children:[s]}]}));return e=>{const[s,...n]=t(" "+e);return s.length>1&&n.unshift(s.substring(1)),n}}(s):()=>[e];return Be(n(e),((e,s)=>"bold"===s||"italic"===s||"strikethrough"===s?je(e,t|Oe[s]):[e]))}const $e=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}}}();function We(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var s=0,n=e.length;s<n;s++)if(e[s]===t)return s;return-1}function qe(e,t){for(var s=e.length-1;s>=0;s--)!0===t(e[s])&&e.splice(s,1)}function He(e){throw new Error("Unhandled case for value: '"+e+"'")}var Ge=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.whitespaceRegex=/\s+/,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||(this.attrs={})},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,s=this.getClass(),n=this.whitespaceRegex,r=s?s.split(n):[],i=e.split(n);t=i.shift();)-1===We(r,t)&&r.push(t);return this.getAttrs().class=r.join(" "),this},e.prototype.removeClass=function(e){for(var t,s=this.getClass(),n=this.whitespaceRegex,r=s?s.split(n):[],i=e.split(n);r.length&&(t=i.shift());){var a=We(r,t);-1!==a&&r.splice(a,1)}return this.getAttrs().class=r.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(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var s in e)e.hasOwnProperty(s)&&t.push(s+'="'+e[s]+'"');return t.join(" ")},e}(),Le=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 Ge({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&&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||!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;null==s?(s="&hellip;",r=3,n=8):(r=s.length,n=s.length);var i=function(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},a=function(e,t){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};if(e.length<=t)return e;var o,u,c,l=t-r,h=(o={},(c=(u=e).match(/^([a-z]+):\/\//i))&&(o.scheme=c[1],u=u.substr(c[0].length)),(c=u.match(/^(.*?)(?=(\?|#|\/|$))/i))&&(o.host=c[1],u=u.substr(c[0].length)),(c=u.match(/^\/(.*?)(?=(\?|#|$))/i))&&(o.path=c[1],u=u.substr(c[0].length)),(c=u.match(/^\?(.*?)(?=(#|$))/i))&&(o.query=c[1],u=u.substr(c[0].length)),(c=u.match(/^#(.*?)$/i))&&(o.fragment=c[1]),o);if(h.query){var d=h.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);d&&(h.query=h.query.substr(0,d[1].length),e=i(h))}if(e.length<=t)return e;if(h.host&&(h.host=h.host.replace(/^www\./,""),e=i(h)),e.length<=t)return e;var p="";if(h.host&&(p+=h.host),p.length>=l)return h.host.length==t?(h.host.substr(0,t-r)+s).substr(0,l+n):a(p,l).substr(0,l+n);var f="";if(h.path&&(f+="/"+h.path),h.query&&(f+="?"+h.query),f){if((p+f).length>=l)return(p+f).length==t?(p+f).substr(0,t):(p+a(f,l-p.length)).substr(0,l+n);p+=f}if(h.fragment){var m="#"+h.fragment;if((p+m).length>=l)return(p+m).length==t?(p+m).substr(0,t):(p+a(m,l-p.length)).substr(0,l+n);p+=m}if(h.scheme&&h.host){var g=h.scheme+"://";if((p+g).length<l)return(g+p).substr(0,t)}if(p.length<=t)return p;var v="";return l>0&&(v=p.substr(-1*Math.floor(l/2))),(p.substr(0,Math.ceil(l/2))+s+v).substr(0,l+n)}(e,a):"middle"===o?function(e,t,s){if(e.length<=t)return e;var n,r;null==s?(s="&hellip;",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="&hellip;",i=3):i=r.length,s=s.substring(0,n-i)+r),s)},e}(),ze=function(){function e(e){this.__jsduckDummyDocProp=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.getType()]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}(),Je=function(e,t){return(Je=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])})(e,t)};function Ye(e,t){function s(){this.constructor=e}Je(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)}var Qe,Ve=function(){return Ve=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},Ve.apply(this,arguments)},Ze=function(e){function t(t){var s=e.call(this,t)||this;return s.email="",s.email=t.email,s}return Ye(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}(ze),Ke=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="",s.hashtag="",s.serviceName=t.serviceName,s.hashtag=t.hashtag,s}return Ye(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;default:throw new Error("Unknown service name to point hashtag to: "+e)}},t.prototype.getAnchorText=function(){return"#"+this.hashtag},t}(ze),Xe=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="twitter",s.mention="",s.mention=t.mention,s.serviceName=t.serviceName,s}return Ye(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;default:throw new Error("Unknown service name to point mention to: "+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}(ze),et=function(e){function t(t){var s=e.call(this,t)||this;return s.number="",s.plusSign=!1,s.number=t.number,s.plusSign=t.plusSign,s}return Ye(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}(ze),tt=function(e){function t(t){var s=e.call(this,t)||this;return s.url="",s.urlMatchType="scheme",s.protocolUrlMatch=!1,s.protocolRelativeMatch=!1,s.stripPrefix={scheme:!0,www:!0},s.stripTrailingSlash=!0,s.decodePercentEncoding=!0,s.schemePrefixRegex=/^(https?:\/\/)?/i,s.wwwPrefixRegex=/^(https?:\/\/)?(www\.)?/i,s.protocolRelativeRegex=/^\/\//,s.protocolPrepended=!1,s.urlMatchType=t.urlMatchType,s.url=t.url,s.protocolUrlMatch=t.protocolUrlMatch,s.protocolRelativeMatch=t.protocolRelativeMatch,s.stripPrefix=t.stripPrefix,s.stripTrailingSlash=t.stripTrailingSlash,s.decodePercentEncoding=t.decodePercentEncoding,s}return Ye(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||this.protocolUrlMatch||this.protocolPrepended||(e=this.url="http://"+e,this.protocolPrepended=!0),e},t.prototype.getAnchorHref=function(){return this.getUrl().replace(/&amp;/g,"&")},t.prototype.getAnchorText=function(){var e=this.getMatchedText();return this.protocolRelativeMatch&&(e=this.stripProtocolRelativePrefix(e)),this.stripPrefix.scheme&&(e=this.stripSchemePrefix(e)),this.stripPrefix.www&&(e=this.stripWwwPrefix(e)),this.stripTrailingSlash&&(e=this.removeTrailingSlash(e)),this.decodePercentEncoding&&(e=this.removePercentEncoding(e)),e},t.prototype.stripSchemePrefix=function(e){return e.replace(this.schemePrefixRegex,"")},t.prototype.stripWwwPrefix=function(e){return e.replace(this.wwwPrefixRegex,"$1")},t.prototype.stripProtocolRelativePrefix=function(e){return e.replace(this.protocolRelativeRegex,"")},t.prototype.removeTrailingSlash=function(e){return"/"===e.charAt(e.length-1)&&(e=e.slice(0,-1)),e},t.prototype.removePercentEncoding=function(e){var t=e.replace(/%22/gi,"&quot;").replace(/%26/gi,"&amp;").replace(/%27/gi,"&#39;").replace(/%3C/gi,"&lt;").replace(/%3E/gi,"&gt;");try{return decodeURIComponent(t)}catch(s){return t}},t}(ze),st=function(e){this.__jsduckDummyDocProp=null,this.tagBuilder=e.tagBuilder},nt=/[A-Za-z]/,rt=/[\d]/,it=/[\D]/,at=/\s/,ot=/['"]/,ut=/[\x00-\x1F\x7F]/,ct=/A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC/.source,lt=ct+/\u2700-\u27bf\udde6-\uddff\ud800-\udbff\udc00-\udfff\ufe0e\ufe0f\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0\ud83c\udffb-\udfff\u200d\u3299\u3297\u303d\u3030\u24c2\ud83c\udd70-\udd71\udd7e-\udd7f\udd8e\udd91-\udd9a\udde6-\uddff\ude01-\ude02\ude1a\ude2f\ude32-\ude3a\ude50-\ude51\u203c\u2049\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u00a9\u00ae\u2122\u2139\udc04\u2600-\u26FF\u2b05\u2b06\u2b07\u2b1b\u2b1c\u2b50\u2b55\u231a\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\udccf\u2935\u2934\u2190-\u21ff/.source+/\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F/.source,ht=/0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19/.source,dt=lt+ht,pt=lt+ht,ft="(?:["+ht+"]{1,3}\\.){3}["+ht+"]{1,3}",mt="["+pt+"](?:["+pt+"\\-]{0,61}["+pt+"])?",gt=function(e){return"(?=("+mt+"))\\"+e},vt=function(e){return"(?:"+gt(e)+"(?:\\."+gt(e+1)+"){0,126}|"+ft+")"},bt=new RegExp("["+pt+"]"),yt=/(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|vermögensberatung|xn--3oq18vl8pn36a|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbaakc7dvf|xn--mgbc0a9azcg|xn--nqv7fs00ema|afamilycompany|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|spreadbetting|travelchannel|wolterskluwer|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|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|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|rightathome|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--estv75g|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--kpu716f|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pbt977c|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|nationwide|newholland|nextdirect|onyourside|properties|protection|prudential|realestate|republican|restaurant|schaeffler|swiftcover|tatamotors|technology|telefonica|university|vistaprint|vlaanderen|volkswagen|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--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|fujixerox|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|honeywell|institute|insurance|kuokgroup|ladbrokes|lancaster|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|passagens|pramerica|richardli|scjohnson|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--tckwe|xn--vhquv|yodobashi|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|budapest|builders|business|capetown|catering|catholic|chrysler|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|esurance|etisalat|everbank|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|merckmsd|mortgage|movistar|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|symantec|training|uconnect|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|cartier|channel|charity|chintai|citadel|clubmed|college|cologne|comcast|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|hoteles|hotmail|hyundai|iselect|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lancome|lanxess|lasalle|latrobe|leclerc|liaison|limited|lincoln|markets|metlife|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|shriram|singles|staples|starhub|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|католик|اتصالات|الجزائر|العليان|پاکستان|كاثوليك|موبايلي|இந்தியா|abarth|abbott|abbvie|active|africa|agency|airbus|airtel|alipay|alsace|alstom|anquan|aramco|author|bayern|beauty|berlin|bharti|blanco|bostik|boston|broker|camera|career|caseih|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|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|mobily|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|piaget|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|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|vuelos|walter|warman|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|dabur|dance|deals|delta|dodge|drive|dubai|earth|edeka|email|epost|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glade|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|intel|irish|iveco|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|lixil|loans|locus|lotte|lotto|lupin|macys|mango|media|miami|money|mopar|movie|nadex|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|zippo|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|adac|aero|aigo|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|doha|duck|duns|dvag|erni|fage|fail|fans|farm|fast|fiat|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|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|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|raid|read|reit|rent|rest|rich|rmit|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scor|scot|seat|seek|sexy|shaw|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|bnl|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceb|ceo|cfa|cfd|com|crs|csc|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|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|jcp|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|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|off|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|qvc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|srl|srt|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|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|ελ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|工行|广东|微博|慈善|手机|手表|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|珠宝|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)/,wt=new RegExp("["+pt+"!#$%&'*+/=?^_`{|}~-]"),At=new RegExp("^"+yt.source+"$"),Ct=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.localPartCharRegex=wt,t.strictTldRegex=At,t}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t=this.tagBuilder,s=this.localPartCharRegex,n=this.strictTldRegex,r=[],i=e.length,a=new Et,o={m:"a",a:"i",i:"l",l:"t",t:"o",o:":"},u=0,c=0,l=a;u<i;){var h=e.charAt(u);switch(c){case 0:"m"===(d=h)?w(1):s.test(d)&&w();break;case 1:p(e.charAt(u-1),h);break;case 2:f(h);break;case 3:m(h);break;case 4:g(h);break;case 5:v(h);break;case 6:b(h);break;case 7:y(h);break;default:He(c)}u++}var d;return C(),r;function p(e,t){":"===e?s.test(t)?(c=2,l=new Et(Ve(Ve({},l),{hasMailtoPrefix:!0}))):A():o[e]===t||(s.test(t)?c=2:"."===t?c=3:"@"===t?c=4:A())}function f(e){"."===e?c=3:"@"===e?c=4:s.test(e)||A()}function m(e){"."===e||"@"===e?A():s.test(e)?c=2:A()}function g(e){bt.test(e)?c=5:A()}function v(e){"."===e?c=7:"-"===e?c=6:bt.test(e)||C()}function b(e){"-"===e||"."===e?C():bt.test(e)?c=5:C()}function y(e){"."===e||"-"===e?C():bt.test(e)?(c=5,l=new Et(Ve(Ve({},l),{hasDomainDot:!0}))):C()}function w(e){void 0===e&&(e=2),c=e,l=new Et({idx:u})}function A(){c=0,l=a}function C(){if(l.hasDomainDot){var s=e.slice(l.idx,u);/[-.]$/.test(s)&&(s=s.slice(0,-1));var i=l.hasMailtoPrefix?s.slice(7):s;(function(e){var t=(e.split(".").pop()||"").toLowerCase();return n.test(t)})(i)&&r.push(new Ze({tagBuilder:t,matchedText:s,offset:l.idx,email:i}))}A()}},t}(st),Et=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.hasMailtoPrefix=!!e.hasMailtoPrefix,this.hasDomainDot=!!e.hasDomainDot},kt=function(){function e(){}return e.isValid=function(e,t){return!(t&&!this.isValidUriScheme(t)||this.urlMatchDoesNotHaveProtocolOrDot(e,t)||this.urlMatchDoesNotHaveAtLeastOneWordChar(e,t)&&!this.isValidIpAddress(e)||this.containsMultipleDots(e))},e.isValidIpAddress=function(e){var t=new RegExp(this.hasFullProtocolRegex.source+this.ipRegex.source);return null!==e.match(t)},e.containsMultipleDots=function(e){var t=e;return this.hasFullProtocolRegex.test(e)&&(t=e.split("://")[1]),t.split("/")[0].indexOf("..")>-1},e.isValidUriScheme=function(e){var t=e.match(this.uriSchemeRegex),s=t&&t[0].toLowerCase();return"javascript:"!==s&&"vbscript:"!==s},e.urlMatchDoesNotHaveProtocolOrDot=function(e,t){return!(!e||t&&this.hasFullProtocolRegex.test(t)||-1!==e.indexOf("."))},e.urlMatchDoesNotHaveAtLeastOneWordChar=function(e,t){return!(!e||!t||this.hasFullProtocolRegex.test(t)||this.hasWordCharAfterProtocolRegex.test(e))},e.hasFullProtocolRegex=/^[A-Za-z][-.+A-Za-z0-9]*:\/\//,e.uriSchemeRegex=/^[A-Za-z][-.+A-Za-z0-9]*:/,e.hasWordCharAfterProtocolRegex=new RegExp(":[^\\s]*?["+ct+"]"),e.ipRegex=/[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/,e}(),xt=(Qe=new RegExp("[/?#](?:["+pt+"\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*["+pt+"\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"),new RegExp(["(?:","(",/(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source,vt(2),")","|","(","(//)?",/(?:www\.)/.source,vt(6),")","|","(","(//)?",vt(10)+"\\.",yt.source,"(?![-"+dt+"])",")",")","(?::[0-9]+)?","(?:"+Qe.source+")?"].join(""),"gi")),St=new RegExp("["+pt+"]"),Tt=function(e){function t(t){var s=e.call(this,t)||this;return s.stripPrefix={scheme:!0,www:!0},s.stripTrailingSlash=!0,s.decodePercentEncoding=!0,s.matcherRegex=xt,s.wordCharRegExp=St,s.stripPrefix=t.stripPrefix,s.stripTrailingSlash=t.stripTrailingSlash,s.decodePercentEncoding=t.decodePercentEncoding,s}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t,s=this.matcherRegex,n=this.stripPrefix,r=this.stripTrailingSlash,i=this.decodePercentEncoding,a=this.tagBuilder,o=[],u=function(){var s=t[0],u=t[1],l=t[4],h=t[5],d=t[9],p=t.index,f=h||d,m=e.charAt(p-1);if(!kt.isValid(s,u))return"continue";if(p>0&&"@"===m)return"continue";if(p>0&&f&&c.wordCharRegExp.test(m))return"continue";if(/\?$/.test(s)&&(s=s.substr(0,s.length-1)),c.matchHasUnbalancedClosingParen(s))s=s.substr(0,s.length-1);else{var g=c.matchHasInvalidCharAfterTld(s,u);g>-1&&(s=s.substr(0,g))}var v=["http://","https://"].find((function(e){return!!u&&-1!==u.indexOf(e)}));if(v){var b=s.indexOf(v);s=s.substr(b),u=u.substr(b),p+=b}var y=u?"scheme":l?"www":"tld",w=!!u;o.push(new tt({tagBuilder:a,matchedText:s,offset:p,urlMatchType:y,url:s,protocolUrlMatch:w,protocolRelativeMatch:!!f,stripPrefix:n,stripTrailingSlash:r,decodePercentEncoding:i}))},c=this;null!==(t=s.exec(e));)u();return o},t.prototype.matchHasUnbalancedClosingParen=function(e){var t,s=e.charAt(e.length-1);if(")"===s)t="(";else if("]"===s)t="[";else{if("}"!==s)return!1;t="{"}for(var n=0,r=0,i=e.length-1;r<i;r++){var a=e.charAt(r);a===t?n++:a===s&&(n=Math.max(n-1,0))}return 0===n},t.prototype.matchHasInvalidCharAfterTld=function(e,t){if(!e)return-1;var s=0;t&&(s=e.indexOf(":"),e=e.slice(s));var n=new RegExp("^((.?//)?[-."+pt+"]*[-"+pt+"]\\.[-"+pt+"]+)").exec(e);return null===n?-1:(s+=n[1].length,e=e.slice(n[1].length),/^[^-.A-Za-z0-9:\/?#]/.test(e)?s:-1)},t}(st),Dt=new RegExp("#[_"+pt+"]{1,139}(?![_"+pt+"])","g"),It=new RegExp("[^"+pt+"]"),Ft=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="twitter",s.matcherRegex=Dt,s.nonWordCharRegex=It,s.serviceName=t.serviceName,s}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t,s=this.matcherRegex,n=this.nonWordCharRegex,r=this.serviceName,i=this.tagBuilder,a=[];null!==(t=s.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||n.test(u)){var c=t[0],l=t[0].slice(1);a.push(new Ke({tagBuilder:i,matchedText:c,offset:o,serviceName:r,hashtag:l}))}}return a},t}(st),Bt=new RegExp(/(?:(?:(?:(\+)?\d{1,3}[-\040.]?)?\(?\d{3}\)?[-\040.]?\d{3}[-\040.]?\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)[-\040.]?(?:\d[-\040.]?){6,12}\d+))([,;]+[0-9]+#?)*/.source+"|"+/(0([1-9]{1}-?[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,"g"),Mt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.matcherRegex=Bt,t}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t,s=this.matcherRegex,n=this.tagBuilder,r=[];null!==(t=s.exec(e));){var i=t[0],a=i.replace(/[^0-9,;#]/g,""),o=!(!t[1]&&!t[2]),u=0==t.index?"":e.substr(t.index-1,1),c=e.substr(t.index+i.length,1),l=!u.match(/\d/)&&!c.match(/\d/);this.testMatch(t[3])&&this.testMatch(i)&&l&&r.push(new et({tagBuilder:n,matchedText:i,offset:t.index,number:a,plusSign:o}))}return r},t.prototype.testMatch=function(e){return it.test(e)},t}(st),Rt=new RegExp("@[_"+pt+"]{1,50}(?![_"+pt+"])","g"),Nt=new RegExp("@[_."+pt+"]{1,30}(?![_"+pt+"])","g"),Ot=new RegExp("@[-_."+pt+"]{1,50}(?![-_"+pt+"])","g"),Pt=new RegExp("[^"+pt+"]"),_t=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="twitter",s.matcherRegexes={twitter:Rt,instagram:Nt,soundcloud:Ot},s.nonWordCharRegex=Pt,s.serviceName=t.serviceName,s}return Ye(t,e),t.prototype.parseMatches=function(e){var t,s=this.serviceName,n=this.matcherRegexes[this.serviceName],r=this.nonWordCharRegex,i=this.tagBuilder,a=[];if(!n)return a;for(;null!==(t=n.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||r.test(u)){var c=t[0].replace(/\.+$/g,""),l=c.slice(1);a.push(new Xe({tagBuilder:i,matchedText:c,offset:o,serviceName:s,mention:l}))}}return a},t}(st);var Ut=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},jt=function(){function e(t){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.matchers=null,this.tagBuilder=null,this.urls=this.normalizeUrlsCfg(t.urls),this.email="boolean"==typeof t.email?t.email:this.email,this.phone="boolean"==typeof t.phone?t.phone:this.phone,this.hashtag=t.hashtag||this.hashtag,this.mention=t.mention||this.mention,this.newWindow="boolean"==typeof t.newWindow?t.newWindow:this.newWindow,this.stripPrefix=this.normalizeStripPrefixCfg(t.stripPrefix),this.stripTrailingSlash="boolean"==typeof t.stripTrailingSlash?t.stripTrailingSlash:this.stripTrailingSlash,this.decodePercentEncoding="boolean"==typeof t.decodePercentEncoding?t.decodePercentEncoding:this.decodePercentEncoding,this.sanitizeHtml=t.sanitizeHtml||!1;var s=this.mention;if(!1!==s&&"twitter"!==s&&"instagram"!==s&&"soundcloud"!==s)throw new Error("invalid `mention` cfg - see docs");var n=this.hashtag;if(!1!==n&&"twitter"!==n&&"facebook"!==n&&"instagram"!==n)throw new Error("invalid `hashtag` cfg - see docs");this.truncate=this.normalizeTruncateCfg(t.truncate),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.normalizeUrlsCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{schemeMatches:e,wwwMatches:e,tldMatches:e}:{schemeMatches:"boolean"!=typeof e.schemeMatches||e.schemeMatches,wwwMatches:"boolean"!=typeof e.wwwMatches||e.wwwMatches,tldMatches:"boolean"!=typeof e.tldMatches||e.tldMatches}},e.prototype.normalizeStripPrefixCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{scheme:e,www:e}:{scheme:"boolean"!=typeof e.scheme||e.scheme,www:"boolean"!=typeof e.www||e.www}},e.prototype.normalizeTruncateCfg=function(e){return"number"==typeof e?{length:e,location:"end"}:function(e,t){for(var s in t)t.hasOwnProperty(s)&&void 0===e[s]&&(e[s]=t[s]);return e}(e||{},{length:Number.POSITIVE_INFINITY,location:"end"})},e.prototype.parse=function(e){var t=this,s=["a","style","script"],n=0,r=[];return function(e,t){for(var s,n=t.onOpenTag,r=t.onCloseTag,i=t.onText,a=t.onComment,o=t.onDoctype,u=new Ut,c=0,l=e.length,h=0,d=0,p=u;c<l;){var f=e.charAt(c);switch(h){case 0:"<"===f&&O();break;case 1:m(f);break;case 2:v(f);break;case 3:g(f);break;case 4:b(f);break;case 5:y(f);break;case 6:w(f);break;case 7:A(f);break;case 8:C(f);break;case 9:E(f);break;case 10:k(f);break;case 11:x(f);break;case 12:S(f);break;case 13:"--"===e.substr(c,2)?(c+=2,p=new Ut(Ve(Ve({},p),{type:"comment"})),h=14):"DOCTYPE"===e.substr(c,7).toUpperCase()?(c+=7,p=new Ut(Ve(Ve({},p),{type:"doctype"})),h=20):N();break;case 14:T(f);break;case 15:D(f);break;case 16:I(f);break;case 17:F(f);break;case 18:B(f);break;case 19:M(f);break;case 20:R(f);break;default:He(h)}c++}function m(e){"!"===e?h=13:"/"===e?(h=2,p=new Ut(Ve(Ve({},p),{isClosing:!0}))):"<"===e?O():nt.test(e)?(h=3,p=new Ut(Ve(Ve({},p),{isOpening:!0}))):(h=0,p=u)}function g(e){at.test(e)?(p=new Ut(Ve(Ve({},p),{name:_()})),h=4):"<"===e?O():"/"===e?(p=new Ut(Ve(Ve({},p),{name:_()})),h=12):">"===e?(p=new Ut(Ve(Ve({},p),{name:_()})),P()):nt.test(e)||rt.test(e)||":"===e||N()}function v(e){">"===e?N():nt.test(e)?h=3:N()}function b(e){at.test(e)||("/"===e?h=12:">"===e?P():"<"===e?O():"="===e||ot.test(e)||ut.test(e)?N():h=5)}function y(e){at.test(e)?h=6:"/"===e?h=12:"="===e?h=7:">"===e?P():"<"===e?O():ot.test(e)&&N()}function w(e){at.test(e)||("/"===e?h=12:"="===e?h=7:">"===e?P():"<"===e?O():ot.test(e)?N():h=5)}function A(e){at.test(e)||('"'===e?h=8:"'"===e?h=9:/[>=`]/.test(e)?N():"<"===e?O():h=10)}function C(e){'"'===e&&(h=11)}function E(e){"'"===e&&(h=11)}function k(e){at.test(e)?h=4:">"===e?P():"<"===e&&O()}function x(e){at.test(e)?h=4:"/"===e?h=12:">"===e?P():"<"===e?O():(h=4,c--)}function S(e){">"===e?(p=new Ut(Ve(Ve({},p),{isClosing:!0})),P()):h=4}function T(e){"-"===e?h=15:">"===e?N():h=16}function D(e){"-"===e?h=18:">"===e?N():h=16}function I(e){"-"===e&&(h=17)}function F(e){h="-"===e?18:16}function B(e){">"===e?P():"!"===e?h=19:"-"===e||(h=16)}function M(e){"-"===e?h=17:">"===e?P():h=16}function R(e){">"===e?P():"<"===e&&O()}function N(){h=0,p=u}function O(){h=1,p=new Ut({idx:c})}function P(){var t=e.slice(d,p.idx);t&&i(t,d),"comment"===p.type?a(p.idx):"doctype"===p.type?o(p.idx):(p.isOpening&&n(p.name,p.idx),p.isClosing&&r(p.name,p.idx)),N(),d=c+1}function _(){var t=p.idx+(p.isClosing?2:1);return e.slice(t,c).toLowerCase()}d<c&&(s=e.slice(d,c),i(s,d),d=c+1)}(e,{onOpenTag:function(e){s.indexOf(e)>=0&&n++},onText:function(e,s){if(0===n){var i=function(e,t){if(!t.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var s,n=[],r=0;s=t.exec(e);)n.push(e.substring(r,s.index)),n.push(s[0]),r=s.index+s[0].length;return n.push(e.substring(r)),n}(e,/(&nbsp;|&#160;|&lt;|&#60;|&gt;|&#62;|&quot;|&#34;|&#39;)/gi),a=s;i.forEach((function(e,s){if(s%2==0){var n=t.parseText(e,a);r.push.apply(r,n)}a+=e.length}))}},onCloseTag:function(e){s.indexOf(e)>=0&&(n=Math.max(n-1,0))},onComment:function(e){},onDoctype:function(e){}}),r=this.compactMatches(r),r=this.removeUnwantedMatches(r)},e.prototype.compactMatches=function(e){e.sort((function(e,t){return e.getOffset()-t.getOffset()}));for(var t=0;t<e.length-1;t++){var s=e[t],n=s.getOffset(),r=s.getMatchedText().length,i=n+r;if(t+1<e.length){if(e[t+1].getOffset()===n){var a=e[t+1].getMatchedText().length>r?t:t+1;e.splice(a,1);continue}e[t+1].getOffset()<i&&e.splice(t+1,1)}}return e},e.prototype.removeUnwantedMatches=function(e){return this.hashtag||qe(e,(function(e){return"hashtag"===e.getType()})),this.email||qe(e,(function(e){return"email"===e.getType()})),this.phone||qe(e,(function(e){return"phone"===e.getType()})),this.mention||qe(e,(function(e){return"mention"===e.getType()})),this.urls.schemeMatches||qe(e,(function(e){return"url"===e.getType()&&"scheme"===e.getUrlMatchType()})),this.urls.wwwMatches||qe(e,(function(e){return"url"===e.getType()&&"www"===e.getUrlMatchType()})),this.urls.tldMatches||qe(e,(function(e){return"url"===e.getType()&&"tld"===e.getUrlMatchType()})),e},e.prototype.parseText=function(e,t){void 0===t&&(t=0),t=t||0;for(var s=this.getMatchers(),n=[],r=0,i=s.length;r<i;r++){for(var a=s[r].parseMatches(e),o=0,u=a.length;o<u;o++)a[o].setOffset(t+a[o].getOffset());n.push.apply(n,a)}return n},e.prototype.link=function(e){if(!e)return"";this.sanitizeHtml&&(e=e.replace(/</g,"&lt;").replace(/>/g,"&gt;"));for(var t=this.parse(e),s=[],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 Ge?t.toAnchorString():e.buildTag().toAnchorString()},e.prototype.getMatchers=function(){if(this.matchers)return this.matchers;var e=this.getTagBuilder(),t=[new Ft({tagBuilder:e,serviceName:this.hashtag}),new Ct({tagBuilder:e}),new Mt({tagBuilder:e}),new _t({tagBuilder:e,serviceName:this.mention}),new Tt({tagBuilder:e,stripPrefix:this.stripPrefix,stripTrailingSlash:this.stripTrailingSlash,decodePercentEncoding:this.decodePercentEncoding})];return this.matchers=t},e.prototype.getTagBuilder=function(){var e=this.tagBuilder;return e||(e=this.tagBuilder=new Le({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),e},e.version="3.14.3",e.AnchorTagBuilder=Le,e.HtmlTag=Ge,e.matcher={Email:Ct,Hashtag:Ft,Matcher:st,Mention:_t,Phone:Mt,Url:Tt},e.match={Email:Ze,Hashtag:Ke,Match:ze,Mention:Xe,Phone:et,Url:tt},e}();function $t(e,t=e){return{type:"autolink",url:e,text:t}}Object.assign((function(e,t){return{type:"emoji",kind:e,text:t}}),{emoticon:e=>({type:"emoji",kind:"emoticon",text:e}),unicode:e=>({type:"emoji",kind:"unicode",text:e})});const Wt=Me(/<!!mention:([^>\s]*?)\|(.*?)>/gm,(([e,t,s])=>function(e,t){return{type:"mention",id:e,text:t}}(decodeURIComponent(t),s))),qt=Me(/<!!customemoji:(.*?)>/gm,(([e,t])=>function(e){return{type:"customemoji",text:e}}(t))),Ht=Me(/<((?:https?|mailto):.*?)\|(.*?)>/gi,(([e,t,s])=>function(e,t=[]){return{type:"link",url:e,children:t}}(t,[s]))),Gt=Me(/<actionlink:([^|]+)[|]([^>]*)>/gi,(([e,t,s])=>{const{action:n,params:r}=zt(t);return function(e,t,s=[]){return{type:"actionlink",action:e,params:t,children:s}}(n,r,[s])})),Lt=Me(/<actionbutton:([^|]+)[|]([^>]*)>/gi,(([e,t,s])=>{const{action:n,params:r}=zt(t);return function(e,t,s=[]){return{type:"actionbutton",action:e,params:t,children:s}}(n,r,[s])}));function zt(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 Jt=Me(/(?:^|\n)(?:\s*[-*+]\s+[^\n]+(?:\n|$))+/g,(([e])=>function(e=[]){return{type:"bulletlist",children:e}}([e.startsWith("\n")?e.slice(1):e]))),Yt=Me(/^\s*[-*+]\s+([^\n]+)(?:\n|$)/gm,(([e,t])=>({type:"bulletpoint",children:[t]}))),Qt=e=>{const t=/(?:^|[^-:/\w])([(+]?[0-9](?:[-_+ ().]?[0-9]){5,11}[0-9])(?:[^-:/\w]|$)/g;let s=0;const n=[];for(const r of ae(e,t)){const t=r[0],i=r[1],a=t.startsWith(i)?r.index:r.index+1;a-s>0&&n.push(e.substring(s,a));const o=$t("tel:"+i.replace(/[^0-9+]/g,""),i);n.push(o),s=a+i.length}return s<e.length&&n.push(e.substring(s)),n},Vt=e=>Ht(e).flatMap((e=>"string"==typeof e?Zt(e):["<",...Zt(e.url),...Zt("|"+e.children[0]+">")])),Zt=e=>{const t=jt.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 Ze?o="mailto:"+r.getEmail():r instanceof tt&&(o=r.getUrl()),t>n&&s.push(e.substring(n,t)),s.push($t(o,i)),n=t+a}return n<e.length&&s.push(e.substring(n)),s},Kt=["Codeblock","Codespan","FormattedLink","Wikitext","Autolink","Actions","Mention","Mention","BulletPoint","CustomEmoji"];const Xt=function(){const e=RegExp("[^\n]+\n?|\n","g");return t=>Array.from(t.match(e)||[])}();function es(e,t={except:[]}){let s=function(e,t){let s=[e];return s=ts(s,t.multilineSteps),s=ts(s,[Xt]),s=ts(s,t.singlelineSteps),s=ss(s),s}(e,function(e={except:[]}){var t;const s={multilineSteps:[],singlelineSteps:[]},n=null!=(t=e.except)?t:Kt.filter((t=>!e.only.includes(t)));return n.includes("BulletPoint")||s.multilineSteps.push(Jt,Yt),n.includes("Mention")||s.singlelineSteps.push(Wt),n.includes("CustomEmoji")||s.singlelineSteps.push(qt),n.includes("Codespan")||s.multilineSteps.push(Me(/```([^]+?)```/g,(([e,t])=>({type:"codespan",text:t})))),n.includes("FormattedLink")||s.singlelineSteps.push(Ht),n.includes("Actions")||(s.singlelineSteps.push(Gt),s.singlelineSteps.push(Lt)),n.includes("Wikitext")||s.singlelineSteps.push(Ue),n.includes("Autolink")||s.singlelineSteps.push(Vt,Qt),s}(t));return s=ns(s,!1),s}function ts(e,t){return t.reduce(((e,t)=>Be(e,t)),e)}function ss(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?c(u({},n),{children:ss(n.children)}):n;return t}function ns(e,t){const s=[];let n=[];for(let r=0;r<e.length;r++){const i=e[r];"string"==typeof i?n.push(i):"children"in i?(n.length>0&&(s.push(n.join("")),n=[]),i.children=ns(i.children,t||"link"===i.type||"actionbutton"===i.type||"actionlink"===i.type),s.push(i)):"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}class rs{constructor(e,t,s){this.id=e,this.conversationId=t,this._realtimeClient=s}get brandedId(){return this.id}get brandedConversationId(){return this.conversationId}get(){return l(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"messages",this.brandedId],{});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=h("Get message "+this.id,e),s=yield this._realtimeClient.createMessageSnapshot(t,this.brandedConversationId);return Te("Get message "+this.id,s)}))}edit(e){return l(this,null,(function*(){const t={content:is(e),custom:"string"==typeof e?void 0:e.custom},s=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"messages",this.brandedId],t);h(`Edit message ${this.id} in conversation ${this.conversationId}`,s)}))}delete(){return l(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"messages",this.brandedId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&h(`Delete message ${this.id} in conversation ${this.conversationId}`,e)}))}}function is(e){return"string"==typeof e?[{type:"text",children:es(e)}]:"text"in e&&e.text?[{type:"text",children:es(e.text)}]:"content"in e&&e.content?e.content:void 0}class as{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get brandedUserId(){return this._realtimeClient.userId}participant(e){return new Ie("string"==typeof e?e:e.id,this.id,this._realtimeClient)}message(e){return new rs(e,this.brandedId,this._realtimeClient)}get(){return l(this,null,(function*(){const e=this._realtimeClient.listMessages(this.brandedId,{limit:1}),t=yield this._realtimeClient.call("GET",["me","conversations",this.brandedId],{});if(!t.ok&&"server"===t.where&&404===t.value.status)return null;const s=h("Get conversation "+this.id,t),n=Te("Get last message in conversation "+this.id,yield e),r=0===n.length?null:n[0];return this._realtimeClient.createConversationSnapshotPreloaded(s,r)}))}set(e){return l(this,null,(function*(){const t=this._realtimeClient.call("PUT",["conversations",this.brandedId],e),s=this._realtimeClient.call("PUT",["conversations",this.brandedId,"participants",this.brandedUserId],e),n=yield t;!n.ok&&"server"===n.where&&403===n.value.status&&"UNAUTHORIZED_TO_EDIT"===n.value.errorCode&&function(e){return void 0===e.subject&&(void 0===e.photoUrl&&(void 0===e.welcomeMessages&&(null!==e.custom&&(void 0===e.custom||!Object.values(e.custom).some((e=>void 0!==e))))))}(e)||h("Set conversation "+this.id,n);const r=yield s;!r.ok&&"server"===r.where&&403===r.value.status&&"UNAUTHORIZED_TO_EDIT_PARTICIPANT"===r.value.errorCode&&function(e){return void 0===e.access&&void 0===e.notify}(e)||h("Set your participation in conversation "+this.id,r)}))}createIfNotExists(){return l(this,arguments,(function*(e={}){const t=this._realtimeClient.call("POST",["conversations",this.brandedId],e),s=this._realtimeClient.call("POST",["conversations",this.brandedId,"participants",this.brandedUserId],e),n=yield t;(n.ok||"server"!==n.where||409!==n.value.status)&&h("Create conversation "+this.id,yield t);const r=yield s;(r.ok||"server"!==r.where||409!==r.value.status)&&h("Join conversation "+this.id,yield s)}))}markAsRead(){return l(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"read"],{});h(`Mark ${this.id} as read`,e)}))}markAsUnread(){return l(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"unread"],{});h(`Mark ${this.id} as unread`,e)}))}send(e){return l(this,null,(function*(){const t={content:os(e),referencedMessageId:us(e),custom:"string"==typeof e?void 0:e.custom,idempotencyKey:Fe((new Date).getTime())},s=yield this._realtimeClient.call("POST",["conversations",this.brandedId,"messages"],t),n=h("Send message to conversation "+this.id,s);return new rs("string"==typeof n?n:n.id,this.brandedId,this._realtimeClient)}))}subscribeMessages(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"messages"],e)}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId],e)}}function os(e){return"string"==typeof e?[{type:"text",children:es(e)}]:"text"in e?[{type:"text",children:es(e.text)}]:e.content}function us(e){if("string"==typeof e)return;const t=e.referencedMessage;return void 0!==t?"string"==typeof t?t:t.id:void 0}class cs{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){const r=encodeURIComponent(t);return this.realtimeWsApiUrl+`/${e}/realtime/${r}?talkjs-client-build=${null!=n?n:"standalone"}&talkjs-core=${s}`}}function ls({method:e,url:t,data:s,options:n,attempts:r,shouldRetry:i,authProvider:a}){var o;(!r||r<=0)&&(r=1);const u={"x-talkjs-client-build":"jssdk-dev","x-talkjs-client-date":"2025-04-29T08:55:37.472Z"};return s instanceof FormData||(u["Content-Type"]=null!=(o=null==n?void 0:n.contentType)?o:"application/json"),v(r,(()=>l(this,null,(function*(){if(a){const e=yield a.getToken();u.Authorization=`Bearer ${e}`}return fetch(t,{method:e,headers:u,body:s}).then((e=>{if(e.ok)return e;throw e}))}))),{initialDelay:.2,log:void 0,shouldRetry:s=>l(this,null,(function*(){return a&&401===s.status?(bs.log(`401 error from ${e} ${t}, ${yield a.getToken()}`),a.refreshToken(),!0):i?i(s):!("status"in s&&s.status>=400&&s.status<500)}))}).catch((s=>{if(!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=>bs.log(`${n} ${s.status} ${e}`))):bs.log(`${n} ${s}`)),console.error("[TalkJS]",n)}throw s}))}const{cdnHost:hs,appHost:ds,restHost:ps,realtimeHost:fs,appProtocol:ms,appWsProtocol:gs}=function(){if("undefined"==typeof window)return{cdnHost:"test-hostname",appHost:"test-hostname",appProtocol:"http:",appWsProtocol:"ws:"};const e=function(){if(document.currentScript)return document.currentScript.src;try{throw new Error}catch(o){const t=o.stack.match(/https?:\/\/.*\.(js|jsx|ts|tsx)/);return t?t[0]:""}}(),t=document.createElement("a");t.href=e;const s=t.host,n=(o=s).match(/^cdn[.-]/)?o.replace(/^cdn/,"app"):"talkjs.com"===o?"app.talkjs.com":o,r=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"api"):e+"/public_api"}(n),i=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"realtime"):e+"/public_api"}(n),a=t.protocol;var o;return{cdnHost:s,appHost:n,restHost:r,realtimeHost:i,appProtocol:a,appWsProtocol:"https:"===a?"wss:":"ws:"}}(),vs=ds.startsWith("app.talkjs.com"),bs="undefined"==typeof window?{log:e=>Promise.resolve(),setData:e=>{}}:new class{constructor(e){this._timeCreated=Date.now(),this._enabled=vs,this._trackJSData={customer:{application:"",correlationId:"",sessionId:"",token:"",userId:"",version:"dev-2025-04-29T08:55:37.472Z"},entry:"direct",environment:{age:Date.now()-this._timeCreated,dependencies:{},originalUrl:window.location.href,referrer:document.referrer,userAgent:window.navigator.userAgent},metadata:[],nav:[],network:[],url:window.location.href,stack:"",timestamp:(new Date).toISOString(),version:"dev-2025-04-29T08:55:37.472Z",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 l(this,null,(function*(){try{if(!this._enabled)return Promise.resolve();const t=c(u({},this._trackJSData),{message:e});yield ls({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)}}))}}("970cd0be0fb74630b75c8451051299dc");class ys{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 l(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 ws{constructor(e,t,s,n,r,i){if(this.appId=t,this.userId=s,this.tokenFetcher=r,this.usingBokens=!1,this.requestInProgress=!1,this.eventEmitter=new ys({tokenChanged(e){},tokenRefreshFailed(e){},tokenAccepted(e){}}),this.sessionExpiryWarningTimeoutId=void 0,i&&(n||r))throw new Error("[TalkJS] If providing a signature for authentication, you must not provide a token or tokenFetcher.");n?this.fetchToken((()=>n)):(r||(this.usingBokens=!0,this.tokenFetcher=()=>this.sendBokenRequest(e,i)),this.refreshToken())}get canRefreshToken(){return this.usingBokens||!!this.tokenFetcher}getToken(){return this.token}refreshToken(){if(!this.requestInProgress){if(!this.tokenFetcher)throw this.emitTokenRefreshFailed("no `tokenFetcher` provided"),new Error("[TalkJS] Cannot refresh token, no `tokenFetcher` provided.");this.fetchToken(this.tokenFetcher)}}onTokenChanged(e){return this.eventEmitter.on("tokenChanged",e),()=>{this.eventEmitter.off("tokenChanged",e)}}emitTokenChanged(e){this.eventEmitter.emit("tokenChanged",e)}onTokenRefreshFailed(e){return this.eventEmitter.on("tokenRefreshFailed",e),()=>{this.eventEmitter.off("tokenRefreshFailed",e)}}emitTokenRefreshFailed(e){this.eventEmitter.emit("tokenRefreshFailed",e),console.error(`[TalkJS] Could not authenticate, cannot recover automatically: ${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.tokenFetcher;if(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 \`tokenFetcher\` was provided when creating the session. 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, provide a \`tokenFetcher\` when creating the session, so that tokens can be refreshed when they expire.`),void 0!==this.tokenFetcher){const t=e>600?e-300:e/2,s=Math.min(1728e6,1e3*t);this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.refreshToken()}),s)}else e<2e6&&(this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.emitTokenRefreshFailed("Token has expired and no `tokenFetcher` was provided when creating the session, so it cannot be refreshed.")}),1e3*e))}fetchToken(e){return l(this,null,(function*(){if(this.requestInProgress)return;this.requestInProgress=!0;const t=()=>l(this,null,(function*(){const t=yield e();return this.checkJwt(t),t}));try{const e=void 0!==this.token;this.token=t(),yield this.token.then((t=>{e&&this.emitTokenChanged(t)})).catch((e=>{this.emitTokenRefreshFailed(e)}))}catch(s){this.emitTokenRefreshFailed(s)}finally{this.requestInProgress=!1}}))}checkJwt(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:As(t[0]),payload:As(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)bs.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(e,t){return l(this,null,(function*(){let s=0;const n=e.getBokensUrl(this.appId,this.userId,t),r=yield ls({method:"GET",url:n,attempts:1e4,shouldRetry:e=>{if(e instanceof Error)return!0;if(401===e.status)throw"Check that you provided a valid signature.";if(404===e.status)throw"Check that you specified the correct App ID.";if(429===e.status||502===e.status)return!0;if(e.status>=400&&e.status<500)throw`Unexpected HTTP ${e.status} response when fetching auth token. Check that you configured the session correctly.`;if(s++,s>=5)throw`Unexpected HTTP ${e.status} response when fetching auth token, retrying did not help.`;return!0}});return(yield r.json()).boken}))}}function As(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.`}}const Cs=new cs("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");class Es{constructor(e){this.target=e}deref(){return this.target}}const ks=new class{constructor(){this.registry={}}getOrCreate(e){var t;const s=this.key(e),n=null==(t=this.registry[s])?void 0:t.deref();if(n)return n;const r=new xs(e),i=globalThis.WeakRef?new WeakRef(r):new Es(r);return this.registry[s]=i,r}deregister(e,t){const s=this.key({appId:e,userId:t});delete this.registry[s]}key({appId:e,userId:t}){return`${e}:${t}`}};class xs{constructor(e){!function(e){function t(e,t){if(!e)throw new Error("[TalkJS] TalkSession: "+t)}t(e&&"object"==typeof e,"Expected an object argument in TalkSession#constructor."),t(e.appId&&"string"==typeof e.appId,"The `appId` property of TalkSession#constructor is required and it must be a non-empty string."),t("string"==typeof e.userId,"The `userId` property of TalkSession#constructor is required and it must be a string."),void 0!==e.token&&t(e.token&&"string"==typeof e.token,"The `token` property of TalkSession#constructor must be a non-empty string."),void 0!==e.tokenFetcher&&t("function"==typeof e.tokenFetcher,"The `tokenFetcher` property of TalkSession#constructor 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 cs(e.apiUrls.realtimeWsApiUrl,e.apiUrls.internalHttpApiUrl,e.apiUrls.restApiHttpUrl):Cs,this._authProvider=new ws(this._apiUrls,t,s,n,r,i),this._realtimeClient=new xe(this._apiUrls.getRealtimeWsUrl(t,s,"1.0.0",e.clientBuild),s,this._authProvider),this.currentUser=new De(this._realtimeClient.userId,this._realtimeClient),this._terminationReason=b(),this._terminationReason.promise.then((e=>{console.error(`[TalkSession] ${e}`)})),function(e,t,s){return l(this,null,(function*(){return ls({method:"GET",url:`${t}/${e}/app`,authProvider:s}).then((e=>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,this._authProvider).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}`))}))}onError(e){const t=b();return Promise.race([t.promise,this._terminationReason.promise]).then((t=>{"UNSUBSCRIBED"!==t&&e(t)})),{unsubscribe:()=>t.resolve("UNSUBSCRIBED")}}user(e){return new De(e,this._realtimeClient)}conversation(e){return new as(e,this._realtimeClient)}terminate(e){ks.deregister(this._appId,this.currentUser.id),this._terminationReason.resolve(e),this._realtimeClient.destroy()}_isConnected(){return this._realtimeClient.isConnected()}uploadFile(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,t)}uploadImage(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"image"},t))}uploadVideo(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"video"},t))}uploadAudio(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"audio"},t))}uploadVoice(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"voice"},t))}}function Ss(e,t,s,n){return l(this,arguments,(function*(e,t,s,{subtype:n,filename:r,width:i,height:a,duration:o}){const u=new FormData;return u.set("file",s,r),void 0!==n&&u.set("subtype",n),void 0!==i&&u.set("width",i.toString()),void 0!==a&&u.set("height",a.toString()),void 0!==o&&u.set("duration",o.toString()),ls({method:"POST",url:e,data:u,authProvider:t}).then((e=>e.json())).then((e=>e.attachmentToken)).catch((e=>l(this,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}))))}))}exports.getTalkSession=function(e){return e.forceCreateNew?new xs(e):ks.getOrCreate(e)},exports.registerPolyfills=function({WebSocket:e}){k=e};
1
+ "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(Ne){r(Ne)}},a=e=>{try{o(s.throw(e))}catch(Ne){r(Ne)}},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 g(e,t){return e*(1-t+2*Math.random()*t)}Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=()=>!0;function v(e,t,s){return c(this,arguments,(function*(e,t,{initialDelay:s,maxDelay:n,log:r,shouldRetry:i=m}){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=g(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 A(e){return{ok:!1,where:"client",value:e}}function C(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(A(e)),e.serverErr=e=>t(C(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.throttler=new S,this.stateMachine=new y("ReconnectingSocket",["STOPPED","WAITING_FOR_THROTTLER","CONNECTING","READY","TERMINATED"],{queueAutoReconnect:{from:["READY","CONNECTING"],to:"WAITING_FOR_THROTTLER",afterTransition:({from:e})=>{"READY"===e&&this.handlers.onClose(),this.throttler.request((()=>{this.stateMachine.transition("connect")}))}},stop:{from:["WAITING_FOR_THROTTLER","CONNECTING","READY"],to:"STOPPED",afterTransition:({from:e})=>{var t;"READY"===e&&this.handlers.onClose(),null==(t=null==this?void 0:this.socket)||t.close(1e3),this.socket=null,this.throttler.resetDelay()}},connect:{from:["STOPPED","WAITING_FOR_THROTTLER"],to:"CONNECTING",afterTransition:()=>this.createWebSocket()},ready:{from:["CONNECTING"],to:"READY",afterTransition:()=>{this.throttler.resetDelay(),this.handlers.onOpen()}},destroy:{from:"ANY",to:"TERMINATED",afterTransition:()=>{var e;null==(e=this.socket)||e.close(1e3)}}})}stopWs(){"TERMINATED"!==this.stateMachine.state&&this.stateMachine.transition("stop")}startWs(){this.stateMachine.canTransition("connect")&&this.stateMachine.transition("connect")}createWebSocket(){var e;null==(e=null==this?void 0:this.socket)||e.close(1e3);const t=new(function(){if(k)return k;if(globalThis.WebSocket)return globalThis.WebSocket;throw new Error("Missing WebSocket implementation")}())(this.realtimeUrl);this.socket=t;const s=()=>this.stateMachine.transition("ready");t.addEventListener("open",s),t.addEventListener("message",this.handlers.onMessage);const n=()=>{t.removeEventListener("open",s),t.removeEventListener("close",n),t.removeEventListener("message",this.handlers.onMessage),"TERMINATED"!==this.stateMachine.state&&"STOPPED"!==this.stateMachine.state&&this.stateMachine.transition("queueAutoReconnect")};t.addEventListener("close",n)}send(e){return"READY"===this.stateMachine.state?(this.socket.send(e),w(void 0)):A("SOCKET_NOT_READY")}terminate(){if(this.socket)if("terminate"in this.socket)this.socket.terminate();else if("dispatchEvent"in this.socket){this.socket.close(1e3);const e=new Event("close"),t=Object.assign(e,{code:1e3,reason:"",wasClean:!0});this.socket.dispatchEvent(t)}else this.socket.close(1e3)}destroy(){this.stateMachine.transition("destroy")}}let S=class{constructor(){this.initialDelayMs=200+200*Math.random(),this.exponentialFactor=1.2,this.maxDelayMs=1e4,this.currentDelayMs=this.initialDelayMs}request(e){const t=g(this.currentDelayMs,.05);f(this.currentDelayMs).then((()=>e())),this.currentDelayMs=Math.min(t*this.exponentialFactor,this.maxDelayMs)}resetDelay(){this.currentDelayMs=this.initialDelayMs}};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 D{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 F{constructor(e,t){this.handlers=t,this.seqCounter=new I,this.responseHandlers={},this.heartbeats=new B(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 B{constructor(e){this.connection=e,this.clientInactivityTimer=new D(25e3),this.serverInactivityTimer=new D(1e4),this.serverTimeoutTimer=new D(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 M{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 F(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 R{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 D(3e3),this.connection=new M(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 N{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 R(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*(){for(;"PROCESSING_QUEUE"===this.stateMachine.state;){const e=this.dequeue();if(!e)return void this.stateMachine.transition("ready");this.connection.call(e.method,e.path,e.data).then((t=>{e.deferred.resolve(t)})),yield new Promise((e=>setTimeout(e,100)))}}))}isConnected(){return"READY"===this.stateMachine.state||"PROCESSING_QUEUE"===this.stateMachine.state}}const O="undefined"!=typeof window&&null!=(e=window.queueMicrotask)?e:setTimeout;class P{constructor(e,t){this.clearPendingBatch=e,this.sendCalls=t,this.sent=!1,O((()=>this.send()))}send(){this.sent||(this.sent=!0,this.clearPendingBatch(),this.sendCalls())}destroy(){this.sent=!0}}class _ extends P{constructor(e,t){super(t,(()=>{this.sendSubscribe(),this.sendGet()})),this.connection=e,this.getCalls=[],this.subscribeCalls=[]}canPush(e,t){return _.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 U extends P{constructor(e,t,s){super(s,(()=>this.sendMutate())),this.conversationId=e,this.connection=t,this.calls=[]}canPush(e,t){return!!U.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 j{constructor(e,t,s){this.pendingBatch=null,this.connection=new N(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(_.isCorrectBatchTypeFor(e,t))return new _(this.connection,(()=>this.pendingBatch=null));if(U.isCorrectBatchTypeFor(e,t)){const e=t[1];return new U(e,this.connection,(()=>this.pendingBatch=null))}return null}}const $={200:"RESOLVE",400:"RESOLVE",401:"RETRY",402:"RESOLVE",403:"RESOLVE",404:"RESOLVE",405:"RESOLVE",409:"RESOLVE",429:"DELAY",500:"DELAY"};class W{constructor(e,t,s){this.throttler=new q,this.alive=!0,this.connection=new j(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=$[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 A("SESSION_DESTROYED");"WEBSOCKET_DISCONNECTED"!==r.value&&("SOCKET_NOT_READY"!==r.value?r.value:yield this.throttler.wait())}return A("SESSION_DESTROYED")}))}destroy(){this.alive=!1,this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class q{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=g(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 H(e){return e.map((e=>encodeURIComponent(e))).join()}class G{constructor(){this.paths={}}add(e){this.paths[H(e)]=e}delete(e){delete this.paths[H(e)]}has(e){return Object.hasOwnProperty.call(this.paths,H(e))}clear(){this.paths={}}forEach(e){Object.values(this.paths).forEach((t=>e(t)))}}class L{constructor(e,t,s){this.handlers=s,this.targetSubscriptions=new G,this.connection=new W(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 z(e,t){return void 0===t?e:t}function J(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 Y(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(!Y(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(!Y(e[n],t[n]))return!1}}return!0}class Q{constructor(){this.prev=Promise.resolve()}runExclusive(e){return c(this,null,(function*(){const t=this.prev.then((()=>e()));return this.prev=t,t}))}}class V{constructor(e,t){this.onTeardown=t,this.error=null,this.lastLoadedState=void 0,this.lastGoodState=Promise.resolve(void 0),this.initialised=!1,this.getDeepMutex=new Q,this.lastDeep=void 0;const s={seq:0,resultPromise:new Promise((e=>setTimeout(e))).then((()=>c(this,null,(function*(){const e=yield this.fetchInitial(0);return this.initialised=!0,e}))))};this.lastState=s,this.states=[s],this.lastLoadedState=void 0}set lastState(e){const t=this.lastGoodState;this.lastGoodState=e.resultPromise.then((e=>e.ok?e.value:t)),e.resultPromise.then((e=>{e.ok||this.setError(e)})),this._lastState=e}get lastState(){return this._lastState}refetchInitial(e){return c(this,null,(function*(){const t=this.lastGoodState,s=this.fetchInitial(e),[n,r]=yield Promise.all([t,s]);return void 0===n?r:r.ok&&this.equal(n,r.value)?w(n):r}))}refetch(e){if(this.error)return;const t={seq:e,resultPromise:this.refetchInitial(e)};this.lastState=t,this.states.push(t)}mutate(e,t){if(this.error)return void console.warn("[TalkJS] Attempting to mutate a terminated store");if(!this.initialised&&e>this._lastState.seq)return;if(e<this.lastState.seq)throw"Seq is in the past";const s={seq:e,resultPromise:this.lastState.resultPromise.then((e=>e.ok?t(e):e))};this.lastState=s,this.states.push(s)}getDeep(e){return c(this,null,(function*(){return this.getDeepMutex.runExclusive((()=>c(this,null,(function*(){if(this.error)return this.error;if(this.lastLoadedState&&e<this.lastLoadedState.seq)throw`Trying to load state ${e} when we have previously loaded ${this.lastLoadedState.seq}`;for(;this.states.length&&this.states[0].seq<=e;)this.lastLoadedState=this.states.shift();if(void 0===this.lastLoadedState)throw`[TalkJS] Tried to load state ${e} which is before the store was created`;const t=yield this.lastLoadedState.resultPromise;if(!t.ok)return t;const s=yield this.loadNested(e,t.value);return s.ok&&this.lastDeep&&s.value.lastChanged===this.lastDeep.value.lastChanged?this.lastDeep:(s.ok?this.lastDeep=s:this.setError(s),s)}))))}))}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,t,s){super(e,s),this.emitMutex=t,this.unsubscribeTimer=new K,this.referencedByOtherStores=0,this.listeners=[],this.lastEmitSeq=void 0,this.lastEmitResult=void 0,t.runExclusive((()=>c(this,null,(function*(){yield this.emit(e)}))))}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(A("UNSUBSCRIBED"))}),this.unsubscribeDebounceMs)}emit(e){return c(this,null,(function*(){var t;if(this.lastEmitSeq&&this.lastEmitSeq>=e)return;if(!1===(null==(t=this.lastEmitResult)?void 0:t.ok))return;const s=this.lastEmitSeq;this.lastEmitSeq=e;const n=yield this.getDeep(e);this.lastEmitResult,this.lastEmitResult=n,n.ok?(void 0===s||s<n.value.lastChanged)&&this.listeners.forEach((e=>e(n))):this.listeners.forEach((e=>e(n)))}))}}class K{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 X extends Z{constructor(e,t,s,n,r){super(e,n,r),this.userId=t,this.realtimeClient=s,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 Y(e.snapshot,t.snapshot)}loadNested(e,t){return c(this,null,(function*(){return w(t)}))}userCreated(e,t){this.mutate(e,(()=>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:z(n.name,t.diff.name),custom:J(n.custom,t.diff.custom),locale:z(n.locale,t.diff.locale),photoUrl:z(n.photoUrl,t.diff.photoUrl),role:z(n.role,t.diff.role),welcomeMessage:z(n.welcomeMessage,t.diff.welcomeMessage)},lastChanged:e})}))}getFromCache(){return c(this,null,(function*(){const e=yield this.lastState.resultPromise;return e.ok?null===e.value.snapshot?C({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}}):A("NOT_IN_CACHE")}))}teardownNested(e){}}const ee=/\uFE0F/g,te=String.fromCharCode(8205);const se={":)":"1f642",":o":"1f62e",":]":"1f60f",":d":"1f600",xd:"1f61d",":p":"1f61c",":@":"1f621",":[":"1f621",":(":"1f626",":'(":"1f62d",":’(":"1f62d",":*":"1f618",":/":"1f614",":s":"1f616",":|":"1f633",":$":"263a",":x":"1f637","<3":"2764","</3":"1f494"},ne={":thumbsup:":"1f44d",":thumbsdown:":"1f44e",":poop:":"1f4a9"};var re,ie={};function ae(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 oe(e){const t=e.replace(/%2F/g,"/").replace(/^.*?\/([^/]+?)(?:\?.*)?$/,"$1");return decodeURIComponent(t)}function ue(e,t){e()||t||(t=e.toString().replace(/^function\s*\(\)\s*\{\s*return\s*(.*);\s*\}\s*$/,"`$1`")+" was not true")}!function(){if(re)return ie;function e(e){return String.fromCharCode(parseInt(e.slice(1),16))}function t(e){return`%${`00${e.charCodeAt(0).toString(16)}`.slice(-2)}`}re=1,Object.defineProperty(ie,"__esModule",{value:!0}),ie.encode=function(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,e))},ie.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){}})(ue||(ue={}));const le=ue,ce=/^\/.*[^\\]\/[im]*$/;function he(e){return!!ce.test(e)&&!de(e).test("")}function de(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 pe{constructor({mode:e,allowedHostnames:t,allowedPhoneNrs:s,allowedMatches:n,forbiddenMatches:r,suppressLinks:i,suppressEmailAddresses:a,suppressPhoneNumbers:o,replacement:u}){le.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(he).map((e=>de(e))),this.forbiddenMatches=(r||[]).filter(he).map((e=>de(e))),le((()=>this.allowedMatches.every((e=>e.flags.includes("g")))),"All regexes in `suppressContactInfo.allowedMatches` must be global. Check `allowedMatches`!"),le((()=>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 fe(e,t){return e.map((e=>function(e,t){if("text"===e.type)return ge(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:[],emojis:null!=(i=e.emojis)&&i,highlight:null!=(a=e.highlight)?a:[],contactInfo:null!=(o=e.contactInfo)&&o,suppression:null!=(u=e.suppression)?u:new pe({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`🎥 ${oe(e.url)}`;if("file"===e.type&&"image"===e.subtype)return`📷 ${oe(e.url)}`;if("file"===e.type&&"audio"===e.subtype)return`🎧 ${oe(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,`📎 ${oe(e.url)}`):"location"===e.type?"📍":""}(e,t))).join("\n\n")}function ge(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 ge(e.children,t);case"bulletlist":case"bulletList":return"\n"+ge(e.children,t);case"bulletpoint":case"bulletPoint":return"- "+ge(e.children,t)+"\n";case"autolink":case"autoLink":case"codeblock":case"codeBlock":case"codespan":case"codeSpan":case"customemoji":case"customEmoji":return e.text;case"suppressed":return t.contactInfoHiddenText;case"mention":return`@${e.text}`;case"emoji":return"images"===t.emojis?"":"unicode"===t.emojis?function(e){if(":arslan:"===e.text)return":arslan:";const t=function({text:e,kind:t}){var s,n,r;return"unicode"===t?function(e){const t=[];let s=0,n=0,r=0;for(;r<e.length;)s=e.charCodeAt(r++),n?(t.push((65536+(n-55296<<10)+(s-56320)).toString(16)),n=0):55296<=s&&s<=56319?n=s:t.push(s.toString(16));return t.join("-")}((r=e).indexOf(te)<0?r.replace(ee,""):r):null!=(s=ne[e])?s:/;-?\)/.test(n=e)?"1f609":(n=n.replace(/;/g,":"),/:-o/i.test(n)?"1f631":(n=n.replace(/-/g,"").toLowerCase(),se[n]))}(e);return t?String.fromCodePoint(parseInt(t,16)):e.text}(e):e.text}})).join("")}class me extends V{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 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:fe(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 Y(e.data,t.data)}teardownNested(e){var t;null==(t=e.sender)||t.unsubscribe()}loadNested(e,t){return c(this,null,(function*(){var s,n,r,i;const a=yield null==(n=null==(s=t.sender)?void 0:s.store)?void 0:n.getDeep(e);if(!1===(null==a?void 0:a.ok))return a;if(null===t.data)return w({lastChanged:t.lastChanged,snapshot:null});const o=null==a?void 0:a.value;return w({lastChanged:Math.max(t.lastChanged,null!=(r=null==o?void 0:o.lastChanged)?r:0),snapshot:{sender:null!=(i=null==o?void 0:o.snapshot)?i: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:fe(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:z(s.value.data.editedAt,t.diff.editedAt),custom:J(s.value.data.custom,t.diff.custom),content:z(s.value.data.content,t.diff.content)}})))}messageDeleted(e,t){this.mutate(e,(s=>null===s.value.data?s:this.messageId===t.messageId?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.lastState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.data)return C({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 ve extends V{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 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){}loadNested(e,t){return c(this,null,(function*(){var s,n,r,i;const a=yield t.dataStore.getDeep(e);if(!a.ok)return a;const o=a.value;if(null===o.snapshot)return w({lastChanged:a.value.lastChanged,snapshot:null});const u=yield null==(s=t.referencedDataStore)?void 0:s.getDeep(e);if(u&&!u.ok)return u;const l=null!=(n=null==u?void 0:u.value)?n:null,c=null!=(r=null==l?void 0:l.snapshot)?r:null;return w({lastChanged:Math.max(o.lastChanged,null!=(i=null==l?void 0:l.lastChanged)?i:0),snapshot:{id:o.snapshot.id,type:o.snapshot.type,sender:o.snapshot.sender,custom:o.snapshot.custom,createdAt:o.snapshot.createdAt,editedAt:o.snapshot.editedAt,referencedMessage:c,origin:o.snapshot.origin,plaintext:o.snapshot.plaintext,content:o.snapshot.content}})}))}}class be extends Z{constructor(e,t,s,n,r){super(e,t,r),this.conversationId=s,this.realtimeClient=n,this.unsubscribeDebounceMs=1e3,this.pendingLoadMore=void 0}listen(e){return this.onlyUsedInternally&&this.lastState.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 ye({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}):we({seq:e,messages:s.value.messages,cursor:s.value.nextCursor,conversationId:this.conversationId,realtimeClient:this.realtimeClient}):s}))}teardownNested(e){Ae(e)}equal(e,t){return null===e.stores&&null===t.stores||null!==e.stores&&null!==t.stores&&!!Y(Object.keys(e.stores),Object.keys(t.stores))&&!!Y(e.inWindow.map((e=>e.messageId)),t.inWindow.map((e=>e.messageId)))&&Y(e.windowEnd,t.windowEnd)}loadNested(e,t){return c(this,null,(function*(){var s,n;if(null===t.stores)return w({snapshot:null,loadedAll:!0,lastChanged:t.lastChanged,lastMessageChanged:t.lastMessageChanged});const r=yield Promise.all(t.inWindow.map((t=>t.getDeep(e)))),i=r.find((e=>!e.ok));if(i)return i;const a=r,o=a.filter((e=>null!==e.value.snapshot)).map((e=>e.value.snapshot)),u=Math.max(t.lastChanged,...a.map((e=>e.value.lastChanged))),l=null==(s=a[0])?void 0:s.value,c=Math.max(t.lastMessageChanged,null!=(n=null==l?void 0:l.lastChanged)?n:-1);return w({snapshot:o,loadedAll:null===t.windowEnd,lastChanged:u,lastMessageChanged:c})}))}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.lastState.resultPromise;if(!t.ok)return;if(null===t.value.windowEnd)return;const s=t.value.windowEnd.cursor,n=yield ye({count:e,cursor:s,conversationId:this.conversationId,realtimeClient:this.realtimeClient}),r=this.lastState.seq+1e-6;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):we({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 me(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 me(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new ve(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 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 s=new me(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 me(e,this.conversationId,i,this.realtimeClient),n[i]=a);const o=new ve(e,t.newLastMessage.createdAt,s,a);r.push(o)}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:(Ae(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&&Ae(e.value)})),e):s))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.stores?t:(Ae(t.value),w({lastChanged:e,lastMessageChanged:e,stores:null,inWindow:null,windowEnd:null}))))}getMessageFromCache(e){return c(this,null,(function*(){const t=yield this.lastState.resultPromise;if(!t.ok)return A("NOT_IN_CACHE");if(null===t.value.stores)return A("NOT_IN_CACHE");const s=t.value.stores[e];return void 0===s?A("NOT_IN_CACHE"):s.getFromCache()}))}}function ye(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 we({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 t=new me(e,r,u,i);h[t.messageId]=t}for(const u of s){const t=u.referencedMessageId;if(t&&void 0===h[t]){const s=new me(e,r,t,i);h[s.messageId]=s}}const d=t?[...t.inWindow]:[];for(const u of s)d.push(new ve(e,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}})}function Ae(e){if(e.stores){const t=A("TERMINATED");Object.values(e.stores).forEach((e=>e.setError(t))),e.inWindow.forEach((e=>e.setError(t)))}}class Ce extends Z{constructor(e,t,s,n,r){super(e,t,r),this.conversationId=s,this.realtimeClient=n,this.unsubscribeDebounceMs=5e3}fetchInitial(e){return c(this,null,(function*(){const t=this.realtimeClient.internalSubscribe(["me","conversations",this.conversationId,"messages"]),s=yield this.realtimeClient.call("GET",["me","conversations",this.conversationId],{},{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 w({lastChanged:e,snapshot:n,messageWindowStore:t})}))}teardownNested(e){var t;null==(t=e.messageWindowStore)||t.unsubscribe()}equal(e,t){return Y(e.snapshot,t.snapshot)}loadNested(e,t){return c(this,null,(function*(){var s;if(!t.snapshot)return w({lastChanged:t.lastChanged,snapshot:null,loadedAll:!0});const n=yield t.messageWindowStore.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 w({lastChanged:Math.max(t.lastChanged,n.value.lastMessageChanged),snapshot:l(u({},t.snapshot),{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):w({lastChanged:e,snapshot:Ee(s.value.snapshot,t.diff),messageWindowStore:s.value.messageWindowStore})))}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):w({lastChanged:e,snapshot:Ee(s.value.snapshot,t.diff),messageWindowStore:s.value.messageWindowStore})))}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):w({lastChanged:e,snapshot:Ee(s.value.snapshot,t.diff),messageWindowStore:s.value.messageWindowStore})))}sideCreated(e,t){this.mutate(e,(s=>s.value.snapshot?s:w({lastChanged:e,snapshot:t.state,messageWindowStore:s.value.messageWindowStore})))}sideDeleted(e,t){this.mutate(e,(t=>null===t.value.snapshot?t:w({lastChanged:e,snapshot:null,messageWindowStore:t.value.messageWindowStore})))}getFromCache(){return c(this,null,(function*(){const e=yield this.lastState.resultPromise;return e.ok&&e.value.snapshot?w({status:200,data:e.value.snapshot}):A("NOT_IN_CACHE")}))}}function Ee(e,t){const s=t;return{id:e.id,createdAt:e.createdAt,subject:z(e.subject,s.subject),photoUrl:z(e.photoUrl,s.photoUrl),welcomeMessages:z(e.welcomeMessages,s.welcomeMessages),custom:J(e.custom,s.custom),lastMessageAt:z(e.lastMessageAt,s.lastMessageAt),unreadMessageCount:z(e.unreadMessageCount,s.unreadMessageCount),isUnread:z(e.isUnread,s.isUnread),access:z(e.access,s.access),notify:z(e.notify,s.notify),readUntil:z(e.readUntil,s.readUntil),joinedAt:e.joinedAt}}class ke{constructor(e,t,s){this.realtimeClient=s,this.userStores={},this.messageWindowStores={},this.conversationStores={},this.emitMutex=new Q,this.seqOffset=0,this.seqInThisConnection=0,this.refetchOnNextNetworkLoss=!0,this.connection=new L(e,t,{onUpstreamRestarting:()=>{this.refetchOnNextNetworkLoss=!1},onReady:()=>{this.refetchOnNextNetworkLoss=!0},onResubscribeSent:()=>{if(this.seqOffset+=this.seq,this.seqInThisConnection=0,this.refetchOnNextNetworkLoss){this.seqOffset++;const e=this.seq;this.refetchAll(e),this.emitAll(e)}},onResubscribeError:(e,t)=>{var s;null==(s=this.getStoreIfExists(e))||s.setError(t)},onPublish:(e,t)=>{this.seqInThisConnection=e;const s=this.seq;for(const n of t)this.handlePublish(s,n);this.emitAll(s)}})}get seq(){return this.seqOffset+this.seqInThisConnection}refetchAll(e){for(const t of Object.values(this.userStores))t.refetch(e);for(const t of Object.values(this.messageWindowStores))t.refetch(e);for(const t of Object.values(this.conversationStores))t.refetch(e)}emitAll(e){return this.emitMutex.runExclusive((()=>c(this,null,(function*(){yield Promise.all([...Object.values(this.userStores).map((t=>t.emit(e))),...Object.values(this.messageWindowStores).map((t=>t.emit(e))),...Object.values(this.conversationStores).map((t=>t.emit(e)))])}))))}handlePublish(e,t){switch(t.type){case"user.created":return this.handleUserCreated(e,t);case"user.edited":return this.handleUserEdited(e,t);case"side.created":return this.handleSideCreated(e,t);case"side.edited":return this.handleSideEdited(e,t);case"side.deleted":return this.handleSideDeleted(e,t);case"participant.edited":return this.handleParticipantEdited(e,t);case"conversation.edited":return this.handleConversationEdited(e,t);case"message.created":return this.handleMessageCreated(e,t);case"message.edited":return this.handleMessageEdited(e,t);case"message.deleted":return this.handleMessageDeleted(e,t);case"messages.cleared":case"conversation.cleared":return this.handleConversationCleared(e,t)}}handleUserCreated(e,t){const s=this.userStores[t.userId];s&&s.userCreated(e,t)}handleUserEdited(e,t){const s=this.userStores[t.userId];s&&s.userEdited(e,t)}handleSideCreated(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.sideCreated(e,t);const n=this.conversationStores[t.conversationId];n&&n.sideCreated(e,t)}handleSideEdited(e,t){const s=this.conversationStores[t.conversationId];s&&s.sideEdited(e,t)}handleParticipantEdited(e,t){const s=this.conversationStores[t.conversationId];s&&s.participantEdited(e,t)}handleConversationEdited(e,t){const s=this.conversationStores[t.conversationId];s&&s.conversationEdited(e,t)}handleSideDeleted(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.sideDeleted(e,t);const n=this.conversationStores[t.conversationId];n&&n.sideDeleted(e,t)}handleMessageCreated(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.messageCreated(e,t)}handleMessageEdited(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.messageEdited(e,t)}handleMessageDeleted(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.messageDeleted(e,t)}handleConversationCleared(e,t){const s=this.messageWindowStores[t.conversationId];s&&s.conversationCleared(e,t)}call(e,t,s,n){return c(this,null,(function*(){if(!n.bypassCache){if("GET"===e&&p(t,["users","*"])){const e=t[1],s=this.userStores[e];if(s){const e=yield s.getFromCache();if("NOT_IN_CACHE"!==e.value)return e}}if("GET"===e&&p(t,["me","conversations","*","messages","*"])){const e=t[2],s=this.messageWindowStores[e];if(s){const e=t[3],n=yield s.getMessageFromCache(e);if("NOT_IN_CACHE"!==n.value)return n}}}return this.connection.call(e,t,s)}))}subscribe(e,t){const s=this.getOrCreateStore(e),n=b(),r=b();n.promise.catch((()=>{})),r.promise.catch((()=>{}));const i={state:{type:"pending",latestSnapshot:void 0},connected:n.promise,terminated:r.promise,loadMore:e=>c(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(d(`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}getOrCreateStore(e){if(p(e,["users","*"])){const t=e[1];if(Object.hasOwnProperty.call(this.userStores,t))return this.userStores[t];{this.connection.subscribe(["users",t]).then((e=>{e.ok||s.setError(e)}));const e=this.seq,s=new X(e,t,this.realtimeClient,this.emitMutex,(()=>{delete this.userStores[t],this.connection.unsubscribe(["users",t])}));return this.userStores[t]=s,s}}if(p(e,["me","conversations","*"])){const t=e[2];if(Object.hasOwnProperty.call(this.conversationStores,t))return this.conversationStores[t];{this.connection.subscribe(["me","conversations",t]).then((t=>{t.ok||e.setError(t)}));const e=new Ce(this.seq,this.emitMutex,t,this.realtimeClient,(()=>{delete this.conversationStores[t],this.connection.unsubscribe(["me","conversations",t])}));return this.conversationStores[t]=e,e}}if(p(e,["me","conversations","*","messages"])){const t=e[2];if(Object.hasOwnProperty.call(this.messageWindowStores,t))return this.messageWindowStores[t];{this.connection.subscribe(["me","conversations",t,"messages"]).then((t=>{t.ok||e.setError(t)}));const e=new be(this.seq,this.emitMutex,t,this.realtimeClient,(()=>{delete this.messageWindowStores[t],this.connection.unsubscribe(["me","conversations",t,"messages"])}));return this.messageWindowStores[t]=e,e}}throw new Error("Unrecognised subscribe path: "+e)}getStoreIfExists(e){var t,s;if(p(e,["users","*"])){const s=e[1];return null!=(t=this.userStores[s])?t:null}if(p(e,["me","conversations","*","messages"])){const t=e[2];return null!=(s=this.messageWindowStores[t])?s:null}throw new Error("Unrecognised subscribe path: "+e)}destroy(){this.userStores={},this.messageWindowStores={},this.connection.destroy()}isConnected(){return this.connection.isConnected()}}class xe{constructor(e,t,s){this.userId=t,this.alive=!0,this.connection=new ke(e,s,this),s.onTokenRefreshFailed((()=>{this.destroy()}))}call(e,t,s){return c(this,arguments,(function*(e,t,s,n={}){return this.alive?this.connection.call(e,t,s,n):A("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()}listMessages(e,t){return c(this,null,(function*(){const s=yield this.call("GET",["me","conversations",e,"messages"],t);if(!s.ok)return Se(s,"Listing messages in "+e);const n=s.value.data.data,r=yield Promise.all(n.map((t=>this.createMessageSnapshot(t,e)))),i=r.find((e=>!e.ok));return void 0===i||i.ok?w(r.map((({value:e})=>e))):i}))}createConversationSnapshotPreloaded(e,t){return{id:e.id,subject:e.subject,photoUrl:e.photoUrl,welcomeMessages:e.welcomeMessages,custom:e.custom,createdAt:e.createdAt,joinedAt:e.joinedAt,lastMessageAt:e.lastMessageAt,unreadMessageCount:e.unreadMessageCount,isUnread:e.isUnread,access:e.access,notify:e.notify,lastMessage:t,readUntil:e.readUntil}}createUserSnapshot(e){return{id:e.id,name:e.name,custom:e.custom,locale:e.locale,photoUrl:e.photoUrl,role:e.role,welcomeMessage:e.welcomeMessage}}createParticipantSnapshotPreloaded(e,t){return"None"===e.access?null:{user:t,access:e.access,notify:e.notify,joinedAt:e.joinedAt}}createMessageSnapshot(e,t){return c(this,null,(function*(){const s=null===e.senderId?Promise.resolve(w(null)):this.getUser(e.senderId),n=null===e.referencedMessageId?Promise.resolve(w(null)):this.getReferencedMessage(t,e.referencedMessageId),r=yield s;if(!r.ok)return r;const i=yield n;return i.ok?w(this.createMessageSnapshotPreloaded(e,r.value,i.value)):i}))}getReferencedMessage(e,t){return c(this,null,(function*(){const s=yield this.call("GET",["me","conversations",e,"messages",t],{});if(!s.ok&&"server"===s.where&&404===s.value.status)return w(null);if(!s.ok&&"server"===s.where&&403===s.value.status&&"NOT_A_PARTICIPANT"===s.value.errorCode)return w(null);if(!s.ok)return Se(s,`Fetching referenced message ${t} in conversation ${e}`);const n=s.value.data,r=yield this.getUser(n.senderId);if(!r.ok)return r;const i=r.value;return w(this.createReferencedMessageSnapshotPreloaded(n,i))}))}getUser(e){return c(this,null,(function*(){const t=yield this.call("GET",["users",e],{includePrivateFields:!1});return t.ok||"server"!==t.where||404!==t.value.status?t.ok?w(this.createUserSnapshot(t.value.data)):Se(t,"Get user "+e):w(null)}))}createMessageSnapshotPreloaded(e,t,s){return{id:e.id,type:e.type,sender:t,referencedMessage:s,custom:e.custom,createdAt:e.createdAt,editedAt:e.editedAt,origin:e.origin,content:e.content,plaintext:fe(e.content,{})}}createReferencedMessageSnapshotPreloaded(e,t){return{id:e.id,type:e.type,sender:t,referencedMessageId:e.referencedMessageId,custom:e.custom,createdAt:e.createdAt,editedAt:e.editedAt,origin:e.origin,content:e.content,plaintext:fe(e.content,{})}}}function Se(e,t){return"server"===e.where?C(l(u({},e.value),{operation:t})):e}function Te(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(d(null!=(s=t.value.operation)?s:e,t.value))}class De{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get(){return c(this,null,(function*(){const e=yield this._realtimeClient.getUser(this.brandedId);return Te("Get user "+this.id,e)}))}set(e){return c(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("PUT",["users",this.brandedId],l(u({},e),{email:t,phone:s}));h("Set user "+this.id,n)}))}createIfNotExists(e){return c(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("POST",["users",this.brandedId],l(u({},e),{email:t,phone:s}));(n.ok||"server"!==n.where||409!=n.value.status)&&h(`Create user ${this.id} if not exists`,n)}))}subscribe(e){return this._realtimeClient.subscribe(["users",this.brandedId],e)}}class Ie{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 c(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"participants",this.brandedUserId],{}),t=yield this._realtimeClient.call("GET",["users",this.brandedUserId],{includePrivateFields:!1}),[s,n]=yield Promise.all([e,t]);if(!s.ok&&"server"===s.where&&404===s.value.status)return null;if(!n.ok&&"server"===n.where&&404===n.value.status)return null;const r=h(`Get participant ${this.userId} in conversation ${this.conversationId}`,s),i=h(`Get user ${this.userId}`,n),a=this._realtimeClient.createUserSnapshot(i);return this._realtimeClient.createParticipantSnapshotPreloaded(r,a)}))}set(){return c(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PUT",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);h(`Set participant ${this.userId} in conversation ${this.conversationId}`,t)}))}edit(){return c(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);h(`Edit participant ${this.userId} in conversation ${this.conversationId}`,t)}))}createIfNotExists(){return c(this,arguments,(function*(e={}){const t=yield this._realtimeClient.call("POST",["conversations",this.brandedConversationId,"participants",this.brandedUserId],e);(t.ok||"server"!==t.where||409!==t.value.status)&&h(`Add participant ${this.userId} to conversation ${this.conversationId}`,t)}))}delete(){return c(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"participants",this.brandedUserId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&h(`Remove participant ${this.userId} from conversation ${this.conversationId}`,e)}))}}function Fe(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 Be=(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:Be(e.children,t,e.type)}];case"link":return[{type:e.type,url:e.url,children:Be(e.children,t,e.type)}];case"actionlink":case"actionLink":case"actionbutton":case"actionButton":return[{type:e.type,action:e.action,params:e.params,children:Be(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 Me(e,t){return s=>{const n=s;let r=0;const i=[];for(const a of ae(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 Re="’'()[]{}<>:,‒–—―…!.«»-‐?‘’“”;/⁄␠·&@*\\•^¤¢$€£¥₩₪†‡°¡¿¬#№%‰‱¶′§~¨_|¦⁂☞∴‽※".replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var Ne,Oe=((Ne=Oe||{})[Ne.italic=1]="italic",Ne[Ne.strikethrough=2]="strikethrough",Ne[Ne.bold=4]="bold",Ne);const Pe=[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")})),_e={_:1,"*":4,"~":2};function Ue(e){return je(e,0)}function je(e,t=0){const s=Pe[t],n=s?function(e){const t=Me($e.getOrCompute(e,(()=>new RegExp(`(?:^|[\\s${Re}])(?:${e.source})(?=[\\s${Re}]|$)`,"g"))),(e=>{const t=e[0][1],s=e[1]||e[2]||e[3]||e[4]||e[5]||e[6];return[" ",{type:Oe[_e[t]],children:[s]}]}));return e=>{const[s,...n]=t(" "+e);return s.length>1&&n.unshift(s.substring(1)),n}}(s):()=>[e];return Be(n(e),((e,s)=>"bold"===s||"italic"===s||"strikethrough"===s?je(e,t|Oe[s]):[e]))}const $e=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}}}();function We(e,t){if(Array.prototype.indexOf)return e.indexOf(t);for(var s=0,n=e.length;s<n;s++)if(e[s]===t)return s;return-1}function qe(e,t){for(var s=e.length-1;s>=0;s--)!0===t(e[s])&&e.splice(s,1)}function He(e){throw new Error("Unhandled case for value: '"+e+"'")}var Ge=function(){function e(e){void 0===e&&(e={}),this.tagName="",this.attrs={},this.innerHTML="",this.whitespaceRegex=/\s+/,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||(this.attrs={})},e.prototype.setClass=function(e){return this.setAttr("class",e)},e.prototype.addClass=function(e){for(var t,s=this.getClass(),n=this.whitespaceRegex,r=s?s.split(n):[],i=e.split(n);t=i.shift();)-1===We(r,t)&&r.push(t);return this.getAttrs().class=r.join(" "),this},e.prototype.removeClass=function(e){for(var t,s=this.getClass(),n=this.whitespaceRegex,r=s?s.split(n):[],i=e.split(n);r.length&&(t=i.shift());){var a=We(r,t);-1!==a&&r.splice(a,1)}return this.getAttrs().class=r.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(){if(!this.attrs)return"";var e=this.getAttrs(),t=[];for(var s in e)e.hasOwnProperty(s)&&t.push(s+'="'+e[s]+'"');return t.join(" ")},e}(),Le=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 Ge({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&&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||!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;null==s?(s="&hellip;",r=3,n=8):(r=s.length,n=s.length);var i=function(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},a=function(e,t){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};if(e.length<=t)return e;var o,u,l,c=t-r,h=(o={},(l=(u=e).match(/^([a-z]+):\/\//i))&&(o.scheme=l[1],u=u.substr(l[0].length)),(l=u.match(/^(.*?)(?=(\?|#|\/|$))/i))&&(o.host=l[1],u=u.substr(l[0].length)),(l=u.match(/^\/(.*?)(?=(\?|#|$))/i))&&(o.path=l[1],u=u.substr(l[0].length)),(l=u.match(/^\?(.*?)(?=(#|$))/i))&&(o.query=l[1],u=u.substr(l[0].length)),(l=u.match(/^#(.*?)$/i))&&(o.fragment=l[1]),o);if(h.query){var d=h.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);d&&(h.query=h.query.substr(0,d[1].length),e=i(h))}if(e.length<=t)return e;if(h.host&&(h.host=h.host.replace(/^www\./,""),e=i(h)),e.length<=t)return e;var p="";if(h.host&&(p+=h.host),p.length>=c)return h.host.length==t?(h.host.substr(0,t-r)+s).substr(0,c+n):a(p,c).substr(0,c+n);var f="";if(h.path&&(f+="/"+h.path),h.query&&(f+="?"+h.query),f){if((p+f).length>=c)return(p+f).length==t?(p+f).substr(0,t):(p+a(f,c-p.length)).substr(0,c+n);p+=f}if(h.fragment){var g="#"+h.fragment;if((p+g).length>=c)return(p+g).length==t?(p+g).substr(0,t):(p+a(g,c-p.length)).substr(0,c+n);p+=g}if(h.scheme&&h.host){var m=h.scheme+"://";if((p+m).length<c)return(m+p).substr(0,t)}if(p.length<=t)return p;var v="";return c>0&&(v=p.substr(-1*Math.floor(c/2))),(p.substr(0,Math.ceil(c/2))+s+v).substr(0,c+n)}(e,a):"middle"===o?function(e,t,s){if(e.length<=t)return e;var n,r;null==s?(s="&hellip;",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="&hellip;",i=3):i=r.length,s=s.substring(0,n-i)+r),s)},e}(),ze=function(){function e(e){this.__jsduckDummyDocProp=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.getType()]},e.prototype.buildTag=function(){return this.tagBuilder.build(this)},e}(),Je=function(e,t){return(Je=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var s in t)t.hasOwnProperty(s)&&(e[s]=t[s])})(e,t)};function Ye(e,t){function s(){this.constructor=e}Je(e,t),e.prototype=null===t?Object.create(t):(s.prototype=t.prototype,new s)}var Qe,Ve=function(){return Ve=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},Ve.apply(this,arguments)},Ze=function(e){function t(t){var s=e.call(this,t)||this;return s.email="",s.email=t.email,s}return Ye(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}(ze),Ke=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="",s.hashtag="",s.serviceName=t.serviceName,s.hashtag=t.hashtag,s}return Ye(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;default:throw new Error("Unknown service name to point hashtag to: "+e)}},t.prototype.getAnchorText=function(){return"#"+this.hashtag},t}(ze),Xe=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="twitter",s.mention="",s.mention=t.mention,s.serviceName=t.serviceName,s}return Ye(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;default:throw new Error("Unknown service name to point mention to: "+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}(ze),et=function(e){function t(t){var s=e.call(this,t)||this;return s.number="",s.plusSign=!1,s.number=t.number,s.plusSign=t.plusSign,s}return Ye(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}(ze),tt=function(e){function t(t){var s=e.call(this,t)||this;return s.url="",s.urlMatchType="scheme",s.protocolUrlMatch=!1,s.protocolRelativeMatch=!1,s.stripPrefix={scheme:!0,www:!0},s.stripTrailingSlash=!0,s.decodePercentEncoding=!0,s.schemePrefixRegex=/^(https?:\/\/)?/i,s.wwwPrefixRegex=/^(https?:\/\/)?(www\.)?/i,s.protocolRelativeRegex=/^\/\//,s.protocolPrepended=!1,s.urlMatchType=t.urlMatchType,s.url=t.url,s.protocolUrlMatch=t.protocolUrlMatch,s.protocolRelativeMatch=t.protocolRelativeMatch,s.stripPrefix=t.stripPrefix,s.stripTrailingSlash=t.stripTrailingSlash,s.decodePercentEncoding=t.decodePercentEncoding,s}return Ye(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||this.protocolUrlMatch||this.protocolPrepended||(e=this.url="http://"+e,this.protocolPrepended=!0),e},t.prototype.getAnchorHref=function(){return this.getUrl().replace(/&amp;/g,"&")},t.prototype.getAnchorText=function(){var e=this.getMatchedText();return this.protocolRelativeMatch&&(e=this.stripProtocolRelativePrefix(e)),this.stripPrefix.scheme&&(e=this.stripSchemePrefix(e)),this.stripPrefix.www&&(e=this.stripWwwPrefix(e)),this.stripTrailingSlash&&(e=this.removeTrailingSlash(e)),this.decodePercentEncoding&&(e=this.removePercentEncoding(e)),e},t.prototype.stripSchemePrefix=function(e){return e.replace(this.schemePrefixRegex,"")},t.prototype.stripWwwPrefix=function(e){return e.replace(this.wwwPrefixRegex,"$1")},t.prototype.stripProtocolRelativePrefix=function(e){return e.replace(this.protocolRelativeRegex,"")},t.prototype.removeTrailingSlash=function(e){return"/"===e.charAt(e.length-1)&&(e=e.slice(0,-1)),e},t.prototype.removePercentEncoding=function(e){var t=e.replace(/%22/gi,"&quot;").replace(/%26/gi,"&amp;").replace(/%27/gi,"&#39;").replace(/%3C/gi,"&lt;").replace(/%3E/gi,"&gt;");try{return decodeURIComponent(t)}catch(s){return t}},t}(ze),st=function(e){this.__jsduckDummyDocProp=null,this.tagBuilder=e.tagBuilder},nt=/[A-Za-z]/,rt=/[\d]/,it=/[\D]/,at=/\s/,ot=/['"]/,ut=/[\x00-\x1F\x7F]/,lt=/A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC/.source,ct=lt+/\u2700-\u27bf\udde6-\uddff\ud800-\udbff\udc00-\udfff\ufe0e\ufe0f\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0\ud83c\udffb-\udfff\u200d\u3299\u3297\u303d\u3030\u24c2\ud83c\udd70-\udd71\udd7e-\udd7f\udd8e\udd91-\udd9a\udde6-\uddff\ude01-\ude02\ude1a\ude2f\ude32-\ude3a\ude50-\ude51\u203c\u2049\u25aa-\u25ab\u25b6\u25c0\u25fb-\u25fe\u00a9\u00ae\u2122\u2139\udc04\u2600-\u26FF\u2b05\u2b06\u2b07\u2b1b\u2b1c\u2b50\u2b55\u231a\u231b\u2328\u23cf\u23e9-\u23f3\u23f8-\u23fa\udccf\u2935\u2934\u2190-\u21ff/.source+/\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F/.source,ht=/0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19/.source,dt=ct+ht,pt=ct+ht,ft="(?:["+ht+"]{1,3}\\.){3}["+ht+"]{1,3}",gt="["+pt+"](?:["+pt+"\\-]{0,61}["+pt+"])?",mt=function(e){return"(?=("+gt+"))\\"+e},vt=function(e){return"(?:"+mt(e)+"(?:\\."+mt(e+1)+"){0,126}|"+ft+")"},bt=new RegExp("["+pt+"]"),yt=/(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|vermögensberatung|xn--3oq18vl8pn36a|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|vermögensberater|xn--fzys8d69uvgm|xn--mgba7c0bbn0a|xn--xkc2al3hye2a|americanexpress|kerryproperties|sandvikcoromant|xn--i1b6b1a6a2e|xn--kcrx77d1x4a|xn--lgbbat1ad8j|xn--mgba3a4f16a|xn--mgbaakc7dvf|xn--mgbc0a9azcg|xn--nqv7fs00ema|afamilycompany|americanfamily|bananarepublic|cancerresearch|cookingchannel|kerrylogistics|weatherchannel|xn--54b7fta0cc|xn--6qq986b3xl|xn--80aqecdr1a|xn--b4w605ferd|xn--fiq228c5hs|xn--h2breg3eve|xn--jlq61u9w7b|xn--mgba3a3ejt|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--mgbb9fbpob|xn--mgbbh1a71e|xn--mgbca7dzdo|xn--mgbi4ecexp|xn--mgbx4cd0ab|xn--rvc1e0am3e|international|lifeinsurance|spreadbetting|travelchannel|wolterskluwer|xn--eckvdtc9d|xn--fpcrj9c3d|xn--fzc2c9e2c|xn--h2brj9c8c|xn--tiq49xqyj|xn--yfro4i67o|xn--ygbi2ammx|construction|lplfinancial|scholarships|versicherung|xn--3e0b707e|xn--45br5cyl|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|foodnetwork|investments|kerryhotels|lamborghini|motorcycles|olayangroup|photography|playstation|productions|progressive|redumbrella|rightathome|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--estv75g|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--kpu716f|xn--mgbbh1a|xn--mgbtx2b|xn--mix891f|xn--nyqy26a|xn--otu796d|xn--pbt977c|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|nationwide|newholland|nextdirect|onyourside|properties|protection|prudential|realestate|republican|restaurant|schaeffler|swiftcover|tatamotors|technology|telefonica|university|vistaprint|vlaanderen|volkswagen|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--unup4y|xn--wgbh1c|xn--wgbl6a|xn--y9a3aq|accenture|alfaromeo|allfinanz|amsterdam|analytics|aquarelle|barcelona|bloomberg|christmas|community|directory|education|equipment|fairwinds|financial|firestone|fresenius|frontdoor|fujixerox|furniture|goldpoint|hisamitsu|homedepot|homegoods|homesense|honeywell|institute|insurance|kuokgroup|ladbrokes|lancaster|landrover|lifestyle|marketing|marshalls|melbourne|microsoft|panasonic|passagens|pramerica|richardli|scjohnson|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--tckwe|xn--vhquv|yodobashi|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|budapest|builders|business|capetown|catering|catholic|chrysler|cipriani|cityeats|cleaning|clinique|clothing|commbank|computer|delivery|deloitte|democrat|diamonds|discount|discover|download|engineer|ericsson|esurance|etisalat|everbank|exchange|feedback|fidelity|firmdale|football|frontier|goodyear|grainger|graphics|guardian|hdfcbank|helsinki|holdings|hospital|infiniti|ipiranga|istanbul|jpmorgan|lighting|lundbeck|marriott|maserati|mckinsey|memorial|merckmsd|mortgage|movistar|observer|partners|pharmacy|pictures|plumbing|property|redstone|reliance|saarland|samsclub|security|services|shopping|showtime|softbank|software|stcgroup|supplies|symantec|training|uconnect|vanguard|ventures|verisign|woodside|xn--90ae|xn--node|xn--p1ai|xn--qxam|yokohama|السعودية|abogado|academy|agakhan|alibaba|android|athleta|auction|audible|auspost|avianca|banamex|bauhaus|bentley|bestbuy|booking|brother|bugatti|capital|caravan|careers|cartier|channel|charity|chintai|citadel|clubmed|college|cologne|comcast|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|hoteles|hotmail|hyundai|iselect|ismaili|jewelry|juniper|kitchen|komatsu|lacaixa|lancome|lanxess|lasalle|latrobe|leclerc|liaison|limited|lincoln|markets|metlife|monster|netbank|netflix|network|neustar|okinawa|oldnavy|organic|origins|philips|pioneer|politie|realtor|recipes|rentals|reviews|rexroth|samsung|sandvik|schmidt|schwarz|science|shiksha|shriram|singles|staples|starhub|storage|support|surgery|systems|temasek|theater|theatre|tickets|tiffany|toshiba|trading|walmart|wanggou|watches|weather|website|wedding|whoswho|windows|winners|xfinity|yamaxun|youtube|zuerich|католик|اتصالات|الجزائر|العليان|پاکستان|كاثوليك|موبايلي|இந்தியா|abarth|abbott|abbvie|active|africa|agency|airbus|airtel|alipay|alsace|alstom|anquan|aramco|author|bayern|beauty|berlin|bharti|blanco|bostik|boston|broker|camera|career|caseih|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|kinder|kindle|kosher|lancia|latino|lawyer|lefrak|living|locker|london|luxury|madrid|maison|makeup|market|mattel|mobile|mobily|monash|mormon|moscow|museum|mutual|nagoya|natura|nissan|nissay|norton|nowruz|office|olayan|online|oracle|orange|otsuka|pfizer|photos|physio|piaget|pictet|quebec|racing|realty|reisen|repair|report|review|rocher|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|vuelos|walter|warman|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|dabur|dance|deals|delta|dodge|drive|dubai|earth|edeka|email|epost|epson|faith|fedex|final|forex|forum|gallo|games|gifts|gives|glade|glass|globo|gmail|green|gripe|group|gucci|guide|homes|honda|horse|house|hyatt|ikano|intel|irish|iveco|jetzt|koeln|kyoto|lamer|lease|legal|lexus|lilly|linde|lipsy|lixil|loans|locus|lotte|lotto|lupin|macys|mango|media|miami|money|mopar|movie|nadex|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|zippo|ایران|بازار|بھارت|سودان|سورية|همراه|भारोत|संगठन|বাংলা|భారత్|ഭാരതം|嘉里大酒店|aarp|able|adac|aero|aigo|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|doha|duck|duns|dvag|erni|fage|fail|fans|farm|fast|fiat|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|hgtv|host|hsbc|icbc|ieee|imdb|immo|info|itau|java|jeep|jobs|jprs|kddi|kiwi|kpmg|kred|land|lego|lgbt|lidl|life|like|limo|link|live|loan|loft|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|raid|read|reit|rent|rest|rich|rmit|room|rsvp|ruhr|safe|sale|sarl|save|saxo|scor|scot|seat|seek|sexy|shaw|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|bnl|bom|boo|bot|box|buy|bzh|cab|cal|cam|car|cat|cba|cbn|cbs|ceb|ceo|cfa|cfd|com|crs|csc|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|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|jcp|jio|jll|jmp|jnj|jot|joy|kfh|kia|kim|kpn|krd|lat|law|lds|llc|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|off|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|qvc|red|ren|ril|rio|rip|run|rwe|sap|sas|sbi|sbs|sca|scb|ses|sew|sex|sfr|ski|sky|soy|srl|srt|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|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|ελ|бг|ею|рф|გე|닷넷|닷컴|삼성|한국|コム|世界|中信|中国|中國|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|嘉里|在线|大拿|娱乐|家電|工行|广东|微博|慈善|手机|手表|招聘|政务|政府|新闻|时尚|書籍|机构|游戏|澳門|点看|珠宝|移动|网址|网店|网站|网络|联通|谷歌|购物|通販|集团|食品|餐厅|香港)/,wt=new RegExp("["+pt+"!#$%&'*+/=?^_`{|}~-]"),At=new RegExp("^"+yt.source+"$"),Ct=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.localPartCharRegex=wt,t.strictTldRegex=At,t}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t=this.tagBuilder,s=this.localPartCharRegex,n=this.strictTldRegex,r=[],i=e.length,a=new Et,o={m:"a",a:"i",i:"l",l:"t",t:"o",o:":"},u=0,l=0,c=a;u<i;){var h=e.charAt(u);switch(l){case 0:"m"===(d=h)?w(1):s.test(d)&&w();break;case 1:p(e.charAt(u-1),h);break;case 2:f(h);break;case 3:g(h);break;case 4:m(h);break;case 5:v(h);break;case 6:b(h);break;case 7:y(h);break;default:He(l)}u++}var d;return C(),r;function p(e,t){":"===e?s.test(t)?(l=2,c=new Et(Ve(Ve({},c),{hasMailtoPrefix:!0}))):A():o[e]===t||(s.test(t)?l=2:"."===t?l=3:"@"===t?l=4:A())}function f(e){"."===e?l=3:"@"===e?l=4:s.test(e)||A()}function g(e){"."===e||"@"===e?A():s.test(e)?l=2:A()}function m(e){bt.test(e)?l=5:A()}function v(e){"."===e?l=7:"-"===e?l=6:bt.test(e)||C()}function b(e){"-"===e||"."===e?C():bt.test(e)?l=5:C()}function y(e){"."===e||"-"===e?C():bt.test(e)?(l=5,c=new Et(Ve(Ve({},c),{hasDomainDot:!0}))):C()}function w(e){void 0===e&&(e=2),l=e,c=new Et({idx:u})}function A(){l=0,c=a}function C(){if(c.hasDomainDot){var s=e.slice(c.idx,u);/[-.]$/.test(s)&&(s=s.slice(0,-1));var i=c.hasMailtoPrefix?s.slice(7):s;(function(e){var t=(e.split(".").pop()||"").toLowerCase();return n.test(t)})(i)&&r.push(new Ze({tagBuilder:t,matchedText:s,offset:c.idx,email:i}))}A()}},t}(st),Et=function(e){void 0===e&&(e={}),this.idx=void 0!==e.idx?e.idx:-1,this.hasMailtoPrefix=!!e.hasMailtoPrefix,this.hasDomainDot=!!e.hasDomainDot},kt=function(){function e(){}return e.isValid=function(e,t){return!(t&&!this.isValidUriScheme(t)||this.urlMatchDoesNotHaveProtocolOrDot(e,t)||this.urlMatchDoesNotHaveAtLeastOneWordChar(e,t)&&!this.isValidIpAddress(e)||this.containsMultipleDots(e))},e.isValidIpAddress=function(e){var t=new RegExp(this.hasFullProtocolRegex.source+this.ipRegex.source);return null!==e.match(t)},e.containsMultipleDots=function(e){var t=e;return this.hasFullProtocolRegex.test(e)&&(t=e.split("://")[1]),t.split("/")[0].indexOf("..")>-1},e.isValidUriScheme=function(e){var t=e.match(this.uriSchemeRegex),s=t&&t[0].toLowerCase();return"javascript:"!==s&&"vbscript:"!==s},e.urlMatchDoesNotHaveProtocolOrDot=function(e,t){return!(!e||t&&this.hasFullProtocolRegex.test(t)||-1!==e.indexOf("."))},e.urlMatchDoesNotHaveAtLeastOneWordChar=function(e,t){return!(!e||!t||this.hasFullProtocolRegex.test(t)||this.hasWordCharAfterProtocolRegex.test(e))},e.hasFullProtocolRegex=/^[A-Za-z][-.+A-Za-z0-9]*:\/\//,e.uriSchemeRegex=/^[A-Za-z][-.+A-Za-z0-9]*:/,e.hasWordCharAfterProtocolRegex=new RegExp(":[^\\s]*?["+lt+"]"),e.ipRegex=/[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/,e}(),xt=(Qe=new RegExp("[/?#](?:["+pt+"\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*["+pt+"\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"),new RegExp(["(?:","(",/(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source,vt(2),")","|","(","(//)?",/(?:www\.)/.source,vt(6),")","|","(","(//)?",vt(10)+"\\.",yt.source,"(?![-"+dt+"])",")",")","(?::[0-9]+)?","(?:"+Qe.source+")?"].join(""),"gi")),St=new RegExp("["+pt+"]"),Tt=function(e){function t(t){var s=e.call(this,t)||this;return s.stripPrefix={scheme:!0,www:!0},s.stripTrailingSlash=!0,s.decodePercentEncoding=!0,s.matcherRegex=xt,s.wordCharRegExp=St,s.stripPrefix=t.stripPrefix,s.stripTrailingSlash=t.stripTrailingSlash,s.decodePercentEncoding=t.decodePercentEncoding,s}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t,s=this.matcherRegex,n=this.stripPrefix,r=this.stripTrailingSlash,i=this.decodePercentEncoding,a=this.tagBuilder,o=[],u=function(){var s=t[0],u=t[1],c=t[4],h=t[5],d=t[9],p=t.index,f=h||d,g=e.charAt(p-1);if(!kt.isValid(s,u))return"continue";if(p>0&&"@"===g)return"continue";if(p>0&&f&&l.wordCharRegExp.test(g))return"continue";if(/\?$/.test(s)&&(s=s.substr(0,s.length-1)),l.matchHasUnbalancedClosingParen(s))s=s.substr(0,s.length-1);else{var m=l.matchHasInvalidCharAfterTld(s,u);m>-1&&(s=s.substr(0,m))}var v=["http://","https://"].find((function(e){return!!u&&-1!==u.indexOf(e)}));if(v){var b=s.indexOf(v);s=s.substr(b),u=u.substr(b),p+=b}var y=u?"scheme":c?"www":"tld",w=!!u;o.push(new tt({tagBuilder:a,matchedText:s,offset:p,urlMatchType:y,url:s,protocolUrlMatch:w,protocolRelativeMatch:!!f,stripPrefix:n,stripTrailingSlash:r,decodePercentEncoding:i}))},l=this;null!==(t=s.exec(e));)u();return o},t.prototype.matchHasUnbalancedClosingParen=function(e){var t,s=e.charAt(e.length-1);if(")"===s)t="(";else if("]"===s)t="[";else{if("}"!==s)return!1;t="{"}for(var n=0,r=0,i=e.length-1;r<i;r++){var a=e.charAt(r);a===t?n++:a===s&&(n=Math.max(n-1,0))}return 0===n},t.prototype.matchHasInvalidCharAfterTld=function(e,t){if(!e)return-1;var s=0;t&&(s=e.indexOf(":"),e=e.slice(s));var n=new RegExp("^((.?//)?[-."+pt+"]*[-"+pt+"]\\.[-"+pt+"]+)").exec(e);return null===n?-1:(s+=n[1].length,e=e.slice(n[1].length),/^[^-.A-Za-z0-9:\/?#]/.test(e)?s:-1)},t}(st),Dt=new RegExp("#[_"+pt+"]{1,139}(?![_"+pt+"])","g"),It=new RegExp("[^"+pt+"]"),Ft=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="twitter",s.matcherRegex=Dt,s.nonWordCharRegex=It,s.serviceName=t.serviceName,s}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t,s=this.matcherRegex,n=this.nonWordCharRegex,r=this.serviceName,i=this.tagBuilder,a=[];null!==(t=s.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||n.test(u)){var l=t[0],c=t[0].slice(1);a.push(new Ke({tagBuilder:i,matchedText:l,offset:o,serviceName:r,hashtag:c}))}}return a},t}(st),Bt=new RegExp(/(?:(?:(?:(\+)?\d{1,3}[-\040.]?)?\(?\d{3}\)?[-\040.]?\d{3}[-\040.]?\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)[-\040.]?(?:\d[-\040.]?){6,12}\d+))([,;]+[0-9]+#?)*/.source+"|"+/(0([1-9]{1}-?[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,"g"),Mt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.matcherRegex=Bt,t}return Ye(t,e),t.prototype.parseMatches=function(e){for(var t,s=this.matcherRegex,n=this.tagBuilder,r=[];null!==(t=s.exec(e));){var i=t[0],a=i.replace(/[^0-9,;#]/g,""),o=!(!t[1]&&!t[2]),u=0==t.index?"":e.substr(t.index-1,1),l=e.substr(t.index+i.length,1),c=!u.match(/\d/)&&!l.match(/\d/);this.testMatch(t[3])&&this.testMatch(i)&&c&&r.push(new et({tagBuilder:n,matchedText:i,offset:t.index,number:a,plusSign:o}))}return r},t.prototype.testMatch=function(e){return it.test(e)},t}(st),Rt=new RegExp("@[_"+pt+"]{1,50}(?![_"+pt+"])","g"),Nt=new RegExp("@[_."+pt+"]{1,30}(?![_"+pt+"])","g"),Ot=new RegExp("@[-_."+pt+"]{1,50}(?![-_"+pt+"])","g"),Pt=new RegExp("[^"+pt+"]"),_t=function(e){function t(t){var s=e.call(this,t)||this;return s.serviceName="twitter",s.matcherRegexes={twitter:Rt,instagram:Nt,soundcloud:Ot},s.nonWordCharRegex=Pt,s.serviceName=t.serviceName,s}return Ye(t,e),t.prototype.parseMatches=function(e){var t,s=this.serviceName,n=this.matcherRegexes[this.serviceName],r=this.nonWordCharRegex,i=this.tagBuilder,a=[];if(!n)return a;for(;null!==(t=n.exec(e));){var o=t.index,u=e.charAt(o-1);if(0===o||r.test(u)){var l=t[0].replace(/\.+$/g,""),c=l.slice(1);a.push(new Xe({tagBuilder:i,matchedText:l,offset:o,serviceName:s,mention:c}))}}return a},t}(st);var Ut=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},jt=function(){function e(t){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.matchers=null,this.tagBuilder=null,this.urls=this.normalizeUrlsCfg(t.urls),this.email="boolean"==typeof t.email?t.email:this.email,this.phone="boolean"==typeof t.phone?t.phone:this.phone,this.hashtag=t.hashtag||this.hashtag,this.mention=t.mention||this.mention,this.newWindow="boolean"==typeof t.newWindow?t.newWindow:this.newWindow,this.stripPrefix=this.normalizeStripPrefixCfg(t.stripPrefix),this.stripTrailingSlash="boolean"==typeof t.stripTrailingSlash?t.stripTrailingSlash:this.stripTrailingSlash,this.decodePercentEncoding="boolean"==typeof t.decodePercentEncoding?t.decodePercentEncoding:this.decodePercentEncoding,this.sanitizeHtml=t.sanitizeHtml||!1;var s=this.mention;if(!1!==s&&"twitter"!==s&&"instagram"!==s&&"soundcloud"!==s)throw new Error("invalid `mention` cfg - see docs");var n=this.hashtag;if(!1!==n&&"twitter"!==n&&"facebook"!==n&&"instagram"!==n)throw new Error("invalid `hashtag` cfg - see docs");this.truncate=this.normalizeTruncateCfg(t.truncate),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.normalizeUrlsCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{schemeMatches:e,wwwMatches:e,tldMatches:e}:{schemeMatches:"boolean"!=typeof e.schemeMatches||e.schemeMatches,wwwMatches:"boolean"!=typeof e.wwwMatches||e.wwwMatches,tldMatches:"boolean"!=typeof e.tldMatches||e.tldMatches}},e.prototype.normalizeStripPrefixCfg=function(e){return null==e&&(e=!0),"boolean"==typeof e?{scheme:e,www:e}:{scheme:"boolean"!=typeof e.scheme||e.scheme,www:"boolean"!=typeof e.www||e.www}},e.prototype.normalizeTruncateCfg=function(e){return"number"==typeof e?{length:e,location:"end"}:function(e,t){for(var s in t)t.hasOwnProperty(s)&&void 0===e[s]&&(e[s]=t[s]);return e}(e||{},{length:Number.POSITIVE_INFINITY,location:"end"})},e.prototype.parse=function(e){var t=this,s=["a","style","script"],n=0,r=[];return function(e,t){for(var s,n=t.onOpenTag,r=t.onCloseTag,i=t.onText,a=t.onComment,o=t.onDoctype,u=new Ut,l=0,c=e.length,h=0,d=0,p=u;l<c;){var f=e.charAt(l);switch(h){case 0:"<"===f&&O();break;case 1:g(f);break;case 2:v(f);break;case 3:m(f);break;case 4:b(f);break;case 5:y(f);break;case 6:w(f);break;case 7:A(f);break;case 8:C(f);break;case 9:E(f);break;case 10:k(f);break;case 11:x(f);break;case 12:S(f);break;case 13:"--"===e.substr(l,2)?(l+=2,p=new Ut(Ve(Ve({},p),{type:"comment"})),h=14):"DOCTYPE"===e.substr(l,7).toUpperCase()?(l+=7,p=new Ut(Ve(Ve({},p),{type:"doctype"})),h=20):N();break;case 14:T(f);break;case 15:D(f);break;case 16:I(f);break;case 17:F(f);break;case 18:B(f);break;case 19:M(f);break;case 20:R(f);break;default:He(h)}l++}function g(e){"!"===e?h=13:"/"===e?(h=2,p=new Ut(Ve(Ve({},p),{isClosing:!0}))):"<"===e?O():nt.test(e)?(h=3,p=new Ut(Ve(Ve({},p),{isOpening:!0}))):(h=0,p=u)}function m(e){at.test(e)?(p=new Ut(Ve(Ve({},p),{name:_()})),h=4):"<"===e?O():"/"===e?(p=new Ut(Ve(Ve({},p),{name:_()})),h=12):">"===e?(p=new Ut(Ve(Ve({},p),{name:_()})),P()):nt.test(e)||rt.test(e)||":"===e||N()}function v(e){">"===e?N():nt.test(e)?h=3:N()}function b(e){at.test(e)||("/"===e?h=12:">"===e?P():"<"===e?O():"="===e||ot.test(e)||ut.test(e)?N():h=5)}function y(e){at.test(e)?h=6:"/"===e?h=12:"="===e?h=7:">"===e?P():"<"===e?O():ot.test(e)&&N()}function w(e){at.test(e)||("/"===e?h=12:"="===e?h=7:">"===e?P():"<"===e?O():ot.test(e)?N():h=5)}function A(e){at.test(e)||('"'===e?h=8:"'"===e?h=9:/[>=`]/.test(e)?N():"<"===e?O():h=10)}function C(e){'"'===e&&(h=11)}function E(e){"'"===e&&(h=11)}function k(e){at.test(e)?h=4:">"===e?P():"<"===e&&O()}function x(e){at.test(e)?h=4:"/"===e?h=12:">"===e?P():"<"===e?O():(h=4,l--)}function S(e){">"===e?(p=new Ut(Ve(Ve({},p),{isClosing:!0})),P()):h=4}function T(e){"-"===e?h=15:">"===e?N():h=16}function D(e){"-"===e?h=18:">"===e?N():h=16}function I(e){"-"===e&&(h=17)}function F(e){h="-"===e?18:16}function B(e){">"===e?P():"!"===e?h=19:"-"===e||(h=16)}function M(e){"-"===e?h=17:">"===e?P():h=16}function R(e){">"===e?P():"<"===e&&O()}function N(){h=0,p=u}function O(){h=1,p=new Ut({idx:l})}function P(){var t=e.slice(d,p.idx);t&&i(t,d),"comment"===p.type?a(p.idx):"doctype"===p.type?o(p.idx):(p.isOpening&&n(p.name,p.idx),p.isClosing&&r(p.name,p.idx)),N(),d=l+1}function _(){var t=p.idx+(p.isClosing?2:1);return e.slice(t,l).toLowerCase()}d<l&&(s=e.slice(d,l),i(s,d),d=l+1)}(e,{onOpenTag:function(e){s.indexOf(e)>=0&&n++},onText:function(e,s){if(0===n){var i=function(e,t){if(!t.global)throw new Error("`splitRegex` must have the 'g' flag set");for(var s,n=[],r=0;s=t.exec(e);)n.push(e.substring(r,s.index)),n.push(s[0]),r=s.index+s[0].length;return n.push(e.substring(r)),n}(e,/(&nbsp;|&#160;|&lt;|&#60;|&gt;|&#62;|&quot;|&#34;|&#39;)/gi),a=s;i.forEach((function(e,s){if(s%2==0){var n=t.parseText(e,a);r.push.apply(r,n)}a+=e.length}))}},onCloseTag:function(e){s.indexOf(e)>=0&&(n=Math.max(n-1,0))},onComment:function(e){},onDoctype:function(e){}}),r=this.compactMatches(r),r=this.removeUnwantedMatches(r)},e.prototype.compactMatches=function(e){e.sort((function(e,t){return e.getOffset()-t.getOffset()}));for(var t=0;t<e.length-1;t++){var s=e[t],n=s.getOffset(),r=s.getMatchedText().length,i=n+r;if(t+1<e.length){if(e[t+1].getOffset()===n){var a=e[t+1].getMatchedText().length>r?t:t+1;e.splice(a,1);continue}e[t+1].getOffset()<i&&e.splice(t+1,1)}}return e},e.prototype.removeUnwantedMatches=function(e){return this.hashtag||qe(e,(function(e){return"hashtag"===e.getType()})),this.email||qe(e,(function(e){return"email"===e.getType()})),this.phone||qe(e,(function(e){return"phone"===e.getType()})),this.mention||qe(e,(function(e){return"mention"===e.getType()})),this.urls.schemeMatches||qe(e,(function(e){return"url"===e.getType()&&"scheme"===e.getUrlMatchType()})),this.urls.wwwMatches||qe(e,(function(e){return"url"===e.getType()&&"www"===e.getUrlMatchType()})),this.urls.tldMatches||qe(e,(function(e){return"url"===e.getType()&&"tld"===e.getUrlMatchType()})),e},e.prototype.parseText=function(e,t){void 0===t&&(t=0),t=t||0;for(var s=this.getMatchers(),n=[],r=0,i=s.length;r<i;r++){for(var a=s[r].parseMatches(e),o=0,u=a.length;o<u;o++)a[o].setOffset(t+a[o].getOffset());n.push.apply(n,a)}return n},e.prototype.link=function(e){if(!e)return"";this.sanitizeHtml&&(e=e.replace(/</g,"&lt;").replace(/>/g,"&gt;"));for(var t=this.parse(e),s=[],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 Ge?t.toAnchorString():e.buildTag().toAnchorString()},e.prototype.getMatchers=function(){if(this.matchers)return this.matchers;var e=this.getTagBuilder(),t=[new Ft({tagBuilder:e,serviceName:this.hashtag}),new Ct({tagBuilder:e}),new Mt({tagBuilder:e}),new _t({tagBuilder:e,serviceName:this.mention}),new Tt({tagBuilder:e,stripPrefix:this.stripPrefix,stripTrailingSlash:this.stripTrailingSlash,decodePercentEncoding:this.decodePercentEncoding})];return this.matchers=t},e.prototype.getTagBuilder=function(){var e=this.tagBuilder;return e||(e=this.tagBuilder=new Le({newWindow:this.newWindow,truncate:this.truncate,className:this.className})),e},e.version="3.14.3",e.AnchorTagBuilder=Le,e.HtmlTag=Ge,e.matcher={Email:Ct,Hashtag:Ft,Matcher:st,Mention:_t,Phone:Mt,Url:Tt},e.match={Email:Ze,Hashtag:Ke,Match:ze,Mention:Xe,Phone:et,Url:tt},e}();function $t(e,t=e){return{type:"autolink",url:e,text:t}}Object.assign((function(e,t){return{type:"emoji",kind:e,text:t}}),{emoticon:e=>({type:"emoji",kind:"emoticon",text:e}),unicode:e=>({type:"emoji",kind:"unicode",text:e})});const Wt=Me(/<!!mention:([^>\s]*?)\|(.*?)>/gm,(([e,t,s])=>function(e,t){return{type:"mention",id:e,text:t}}(decodeURIComponent(t),s))),qt=Me(/<!!customemoji:(.*?)>/gm,(([e,t])=>function(e){return{type:"customemoji",text:e}}(t))),Ht=Me(/<((?:https?|mailto):.*?)\|(.*?)>/gi,(([e,t,s])=>function(e,t=[]){return{type:"link",url:e,children:t}}(t,[s]))),Gt=Me(/<actionlink:([^|]+)[|]([^>]*)>/gi,(([e,t,s])=>{const{action:n,params:r}=zt(t);return function(e,t,s=[]){return{type:"actionlink",action:e,params:t,children:s}}(n,r,[s])})),Lt=Me(/<actionbutton:([^|]+)[|]([^>]*)>/gi,(([e,t,s])=>{const{action:n,params:r}=zt(t);return function(e,t,s=[]){return{type:"actionbutton",action:e,params:t,children:s}}(n,r,[s])}));function zt(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 Jt=Me(/(?:^|\n)(?:\s*[-*+]\s+[^\n]+(?:\n|$))+/g,(([e])=>function(e=[]){return{type:"bulletlist",children:e}}([e.startsWith("\n")?e.slice(1):e]))),Yt=Me(/^\s*[-*+]\s+([^\n]+)(?:\n|$)/gm,(([e,t])=>({type:"bulletpoint",children:[t]}))),Qt=e=>{const t=/(?:^|[^-:/\w])([(+]?[0-9](?:[-_+ ().]?[0-9]){5,11}[0-9])(?:[^-:/\w]|$)/g;let s=0;const n=[];for(const r of ae(e,t)){const t=r[0],i=r[1],a=t.startsWith(i)?r.index:r.index+1;a-s>0&&n.push(e.substring(s,a));const o=$t("tel:"+i.replace(/[^0-9+]/g,""),i);n.push(o),s=a+i.length}return s<e.length&&n.push(e.substring(s)),n},Vt=e=>Ht(e).flatMap((e=>"string"==typeof e?Zt(e):["<",...Zt(e.url),...Zt("|"+e.children[0]+">")])),Zt=e=>{const t=jt.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 Ze?o="mailto:"+r.getEmail():r instanceof tt&&(o=r.getUrl()),t>n&&s.push(e.substring(n,t)),s.push($t(o,i)),n=t+a}return n<e.length&&s.push(e.substring(n)),s},Kt=["Codeblock","Codespan","FormattedLink","Wikitext","Autolink","Actions","Mention","Mention","BulletPoint","CustomEmoji"];const Xt=function(){const e=RegExp("[^\n]+\n?|\n","g");return t=>Array.from(t.match(e)||[])}();function es(e,t={except:[]}){let s=function(e,t){let s=[e];return s=ts(s,t.multilineSteps),s=ts(s,[Xt]),s=ts(s,t.singlelineSteps),s=ss(s),s}(e,function(e={except:[]}){var t;const s={multilineSteps:[],singlelineSteps:[]},n=null!=(t=e.except)?t:Kt.filter((t=>!e.only.includes(t)));return n.includes("BulletPoint")||s.multilineSteps.push(Jt,Yt),n.includes("Mention")||s.singlelineSteps.push(Wt),n.includes("CustomEmoji")||s.singlelineSteps.push(qt),n.includes("Codespan")||s.multilineSteps.push(Me(/```([^]+?)```/g,(([e,t])=>({type:"codespan",text:t})))),n.includes("FormattedLink")||s.singlelineSteps.push(Ht),n.includes("Actions")||(s.singlelineSteps.push(Gt),s.singlelineSteps.push(Lt)),n.includes("Wikitext")||s.singlelineSteps.push(Ue),n.includes("Autolink")||s.singlelineSteps.push(Vt,Qt),s}(t));return s=ns(s,!1),s}function ts(e,t){return t.reduce(((e,t)=>Be(e,t)),e)}function ss(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?l(u({},n),{children:ss(n.children)}):n;return t}function ns(e,t){const s=[];let n=[];for(let r=0;r<e.length;r++){const i=e[r];"string"==typeof i?n.push(i):"children"in i?(n.length>0&&(s.push(n.join("")),n=[]),i.children=ns(i.children,t||"link"===i.type||"actionbutton"===i.type||"actionlink"===i.type),s.push(i)):"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}class rs{constructor(e,t,s){this.id=e,this.conversationId=t,this._realtimeClient=s}get brandedId(){return this.id}get brandedConversationId(){return this.conversationId}get(){return c(this,null,(function*(){const e=yield this._realtimeClient.call("GET",["me","conversations",this.brandedConversationId,"messages",this.brandedId],{});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=h("Get message "+this.id,e),s=yield this._realtimeClient.createMessageSnapshot(t,this.brandedConversationId);return Te("Get message "+this.id,s)}))}edit(e){return c(this,null,(function*(){const t={content:is(e),custom:"string"==typeof e?void 0:e.custom},s=yield this._realtimeClient.call("PATCH",["conversations",this.brandedConversationId,"messages",this.brandedId],t);h(`Edit message ${this.id} in conversation ${this.conversationId}`,s)}))}delete(){return c(this,null,(function*(){const e=yield this._realtimeClient.call("DELETE",["conversations",this.brandedConversationId,"messages",this.brandedId],{});(e.ok||"server"!==e.where||404!==e.value.status)&&h(`Delete message ${this.id} in conversation ${this.conversationId}`,e)}))}}function is(e){return"string"==typeof e?[{type:"text",children:es(e)}]:"text"in e&&e.text?[{type:"text",children:es(e.text)}]:"content"in e&&e.content?e.content:void 0}class as{constructor(e,t){this.id=e,this._realtimeClient=t}get brandedId(){return this.id}get brandedUserId(){return this._realtimeClient.userId}participant(e){return new Ie("string"==typeof e?e:e.id,this.id,this._realtimeClient)}message(e){return new rs(e,this.brandedId,this._realtimeClient)}get(){return c(this,null,(function*(){const e=this._realtimeClient.listMessages(this.brandedId,{limit:1}),t=yield this._realtimeClient.call("GET",["me","conversations",this.brandedId],{});if(!t.ok&&"server"===t.where&&404===t.value.status)return null;const s=h("Get conversation "+this.id,t),n=Te("Get last message in conversation "+this.id,yield e),r=0===n.length?null:n[0];return this._realtimeClient.createConversationSnapshotPreloaded(s,r)}))}set(e){return c(this,null,(function*(){const t=this._realtimeClient.call("PUT",["conversations",this.brandedId],e),s=this._realtimeClient.call("PUT",["conversations",this.brandedId,"participants",this.brandedUserId],e),n=yield t;!n.ok&&"server"===n.where&&403===n.value.status&&"UNAUTHORIZED_TO_EDIT"===n.value.errorCode&&function(e){return void 0===e.subject&&(void 0===e.photoUrl&&(void 0===e.welcomeMessages&&(null!==e.custom&&(void 0===e.custom||!Object.values(e.custom).some((e=>void 0!==e))))))}(e)||h("Set conversation "+this.id,n);const r=yield s;!r.ok&&"server"===r.where&&403===r.value.status&&"UNAUTHORIZED_TO_EDIT_PARTICIPANT"===r.value.errorCode&&function(e){return void 0===e.access&&void 0===e.notify}(e)||h("Set your participation in conversation "+this.id,r)}))}createIfNotExists(){return c(this,arguments,(function*(e={}){const t=this._realtimeClient.call("POST",["conversations",this.brandedId],e),s=this._realtimeClient.call("POST",["conversations",this.brandedId,"participants",this.brandedUserId],e),n=yield t;(n.ok||"server"!==n.where||409!==n.value.status)&&h("Create conversation "+this.id,yield t);const r=yield s;(r.ok||"server"!==r.where||409!==r.value.status)&&h("Join conversation "+this.id,yield s)}))}markAsRead(){return c(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"read"],{});h(`Mark ${this.id} as read`,e)}))}markAsUnread(){return c(this,null,(function*(){const e=yield this._realtimeClient.call("POST",["me","conversations",this.brandedId,"unread"],{});h(`Mark ${this.id} as unread`,e)}))}send(e){return c(this,null,(function*(){const t={content:os(e),referencedMessageId:us(e),custom:"string"==typeof e?void 0:e.custom,idempotencyKey:Fe((new Date).getTime())},s=yield this._realtimeClient.call("POST",["conversations",this.brandedId,"messages"],t),n=h("Send message to conversation "+this.id,s);return new rs("string"==typeof n?n:n.id,this.brandedId,this._realtimeClient)}))}subscribeMessages(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId,"messages"],e)}subscribe(e){return this._realtimeClient.subscribe(["me","conversations",this.brandedId],e)}}function os(e){return"string"==typeof e?[{type:"text",children:es(e)}]:"text"in e?[{type:"text",children:es(e.text)}]:e.content}function us(e){if("string"==typeof e)return;const t=e.referencedMessage;return void 0!==t?"string"==typeof t?t:t.id:void 0}class ls{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){const r=encodeURIComponent(t);return this.realtimeWsApiUrl+`/${e}/realtime/${r}?talkjs-client-build=${null!=n?n:"standalone"}&talkjs-core=${s}`}}function cs({method:e,url:t,data:s,options:n,attempts:r,shouldRetry:i,authProvider:a}){var o;(!r||r<=0)&&(r=1);const u={"x-talkjs-client-build":"jssdk-dev","x-talkjs-client-date":"2025-04-30T13:41:48.005Z"};return s instanceof FormData||(u["Content-Type"]=null!=(o=null==n?void 0:n.contentType)?o:"application/json"),v(r,(()=>c(this,null,(function*(){if(a){const e=yield a.getToken();u.Authorization=`Bearer ${e}`}return fetch(t,{method:e,headers:u,body:s}).then((e=>{if(e.ok)return e;throw e}))}))),{initialDelay:.2,log:void 0,shouldRetry:s=>c(this,null,(function*(){return a&&401===s.status?(bs.log(`401 error from ${e} ${t}, ${yield a.getToken()}`),a.refreshToken(),!0):i?i(s):!("status"in s&&s.status>=400&&s.status<500)}))}).catch((s=>{if(!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=>bs.log(`${n} ${s.status} ${e}`))):bs.log(`${n} ${s}`)),console.error("[TalkJS]",n)}throw s}))}const{cdnHost:hs,appHost:ds,restHost:ps,realtimeHost:fs,appProtocol:gs,appWsProtocol:ms}=function(){if("undefined"==typeof window)return{cdnHost:"test-hostname",appHost:"test-hostname",appProtocol:"http:",appWsProtocol:"ws:"};const e=function(){if(document.currentScript)return document.currentScript.src;try{throw new Error}catch(o){const t=o.stack.match(/https?:\/\/.*\.(js|jsx|ts|tsx)/);return t?t[0]:""}}(),t=document.createElement("a");t.href=e;const s=t.host,n=(o=s).match(/^cdn[.-]/)?o.replace(/^cdn/,"app"):"talkjs.com"===o?"app.talkjs.com":o,r=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"api"):e+"/public_api"}(n),i=function(e){return e.match(/^app[.-]/)?e.replace(/^app/,"realtime"):e+"/public_api"}(n),a=t.protocol;var o;return{cdnHost:s,appHost:n,restHost:r,realtimeHost:i,appProtocol:a,appWsProtocol:"https:"===a?"wss:":"ws:"}}(),vs=ds.startsWith("app.talkjs.com"),bs="undefined"==typeof window?{log:e=>Promise.resolve(),setData:e=>{}}:new class{constructor(e){this._timeCreated=Date.now(),this._enabled=vs,this._trackJSData={customer:{application:"",correlationId:"",sessionId:"",token:"",userId:"",version:"dev-2025-04-30T13:41:48.005Z"},entry:"direct",environment:{age:Date.now()-this._timeCreated,dependencies:{},originalUrl:window.location.href,referrer:document.referrer,userAgent:window.navigator.userAgent},metadata:[],nav:[],network:[],url:window.location.href,stack:"",timestamp:(new Date).toISOString(),version:"dev-2025-04-30T13:41:48.005Z",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 c(this,null,(function*(){try{if(!this._enabled)return Promise.resolve();const t=l(u({},this._trackJSData),{message:e});yield cs({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)}}))}}("970cd0be0fb74630b75c8451051299dc");class ys{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 c(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 ws{constructor(e,t,s,n,r,i){if(this.appId=t,this.userId=s,this.tokenFetcher=r,this.usingBokens=!1,this.requestInProgress=!1,this.eventEmitter=new ys({tokenChanged(e){},tokenRefreshFailed(e){},tokenAccepted(e){}}),this.sessionExpiryWarningTimeoutId=void 0,i&&(n||r))throw new Error("[TalkJS] If providing a signature for authentication, you must not provide a token or tokenFetcher.");n?this.fetchToken((()=>n)):(r||(this.usingBokens=!0,this.tokenFetcher=()=>this.sendBokenRequest(e,i)),this.refreshToken())}get canRefreshToken(){return this.usingBokens||!!this.tokenFetcher}getToken(){return this.token}refreshToken(){if(!this.requestInProgress){if(!this.tokenFetcher)throw this.emitTokenRefreshFailed("no `tokenFetcher` provided"),new Error("[TalkJS] Cannot refresh token, no `tokenFetcher` provided.");this.fetchToken(this.tokenFetcher)}}onTokenChanged(e){return this.eventEmitter.on("tokenChanged",e),()=>{this.eventEmitter.off("tokenChanged",e)}}emitTokenChanged(e){this.eventEmitter.emit("tokenChanged",e)}onTokenRefreshFailed(e){return this.eventEmitter.on("tokenRefreshFailed",e),()=>{this.eventEmitter.off("tokenRefreshFailed",e)}}emitTokenRefreshFailed(e){this.eventEmitter.emit("tokenRefreshFailed",e),console.error(`[TalkJS] Could not authenticate, cannot recover automatically: ${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.tokenFetcher;if(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 \`tokenFetcher\` was provided when creating the session. 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, provide a \`tokenFetcher\` when creating the session, so that tokens can be refreshed when they expire.`),void 0!==this.tokenFetcher){const t=e>600?e-300:e/2,s=Math.min(1728e6,1e3*t);this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.refreshToken()}),s)}else e<2e6&&(this.sessionExpiryWarningTimeoutId=setTimeout((()=>{this.emitTokenRefreshFailed("Token has expired and no `tokenFetcher` was provided when creating the session, so it cannot be refreshed.")}),1e3*e))}fetchToken(e){return c(this,null,(function*(){if(this.requestInProgress)return;this.requestInProgress=!0;const t=()=>c(this,null,(function*(){const t=yield e();return this.checkJwt(t),t}));try{const e=void 0!==this.token;this.token=t(),yield this.token.then((t=>{e&&this.emitTokenChanged(t)})).catch((e=>{this.emitTokenRefreshFailed(e)}))}catch(s){this.emitTokenRefreshFailed(s)}finally{this.requestInProgress=!1}}))}checkJwt(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:As(t[0]),payload:As(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)bs.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(e,t){return c(this,null,(function*(){let s=0;const n=e.getBokensUrl(this.appId,this.userId,t),r=yield cs({method:"GET",url:n,attempts:1e4,shouldRetry:e=>{if(e instanceof Error)return!0;if(401===e.status)throw"Check that you provided a valid signature.";if(404===e.status)throw"Check that you specified the correct App ID.";if(429===e.status||502===e.status)return!0;if(e.status>=400&&e.status<500)throw`Unexpected HTTP ${e.status} response when fetching auth token. Check that you configured the session correctly.`;if(s++,s>=5)throw`Unexpected HTTP ${e.status} response when fetching auth token, retrying did not help.`;return!0}});return(yield r.json()).boken}))}}function As(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.`}}const Cs=new ls("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");class Es{constructor(e){this.target=e}deref(){return this.target}}const ks=new class{constructor(){this.registry={}}getOrCreate(e){var t;const s=this.key(e),n=null==(t=this.registry[s])?void 0:t.deref();if(n)return n;const r=new xs(e),i=globalThis.WeakRef?new WeakRef(r):new Es(r);return this.registry[s]=i,r}deregister(e,t){const s=this.key({appId:e,userId:t});delete this.registry[s]}key({appId:e,userId:t}){return`${e}:${t}`}};class xs{constructor(e){!function(e){function t(e,t){if(!e)throw new Error("[TalkJS] TalkSession: "+t)}t(e&&"object"==typeof e,"Expected an object argument in TalkSession#constructor."),t(e.appId&&"string"==typeof e.appId,"The `appId` property of TalkSession#constructor is required and it must be a non-empty string."),t("string"==typeof e.userId,"The `userId` property of TalkSession#constructor is required and it must be a string."),void 0!==e.token&&t(e.token&&"string"==typeof e.token,"The `token` property of TalkSession#constructor must be a non-empty string."),void 0!==e.tokenFetcher&&t("function"==typeof e.tokenFetcher,"The `tokenFetcher` property of TalkSession#constructor 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 ls(e.apiUrls.realtimeWsApiUrl,e.apiUrls.internalHttpApiUrl,e.apiUrls.restApiHttpUrl):Cs,this._authProvider=new ws(this._apiUrls,t,s,n,r,i),this._realtimeClient=new xe(this._apiUrls.getRealtimeWsUrl(t,s,"1.0.1",e.clientBuild),s,this._authProvider),this.currentUser=new De(this._realtimeClient.userId,this._realtimeClient),this._terminationReason=b(),this._terminationReason.promise.then((e=>{console.error(`[TalkSession] ${e}`)})),function(e,t,s){return c(this,null,(function*(){return cs({method:"GET",url:`${t}/${e}/app`,authProvider:s}).then((e=>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,this._authProvider).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}`))}))}onError(e){const t=b();return Promise.race([t.promise,this._terminationReason.promise]).then((t=>{"UNSUBSCRIBED"!==t&&e(t)})),{unsubscribe:()=>t.resolve("UNSUBSCRIBED")}}user(e){return new De(e,this._realtimeClient)}conversation(e){return new as(e,this._realtimeClient)}terminate(e){ks.deregister(this._appId,this.currentUser.id),this._terminationReason.resolve(e),this._realtimeClient.destroy()}_isConnected(){return this._realtimeClient.isConnected()}uploadFile(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,t)}uploadImage(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"image"},t))}uploadVideo(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"video"},t))}uploadAudio(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"audio"},t))}uploadVoice(e,t){return Ss(`${this._apiUrls.restApiHttpUrl}/${this._appId}/files`,this._authProvider,e,u({subtype:"voice"},t))}}function Ss(e,t,s,n){return c(this,arguments,(function*(e,t,s,{subtype:n,filename:r,width:i,height:a,duration:o}){const u=new FormData;return u.set("file",s,r),void 0!==n&&u.set("subtype",n),void 0!==i&&u.set("width",i.toString()),void 0!==a&&u.set("height",a.toString()),void 0!==o&&u.set("duration",o.toString()),cs({method:"POST",url:e,data:u,authProvider:t}).then((e=>e.json())).then((e=>e.attachmentToken)).catch((e=>c(this,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}))))}))}exports.getTalkSession=function(e){return e.forceCreateNew?new xs(e):ks.getOrCreate(e)},exports.registerPolyfills=function({WebSocket:e}){k=e};
2
2
  //# sourceMappingURL=talkSession.cjs.map
@@ -84,7 +84,7 @@ export declare interface AudioBlock {
84
84
  duration?: number;
85
85
  }
86
86
 
87
- declare interface AudioFileMetadata {
87
+ export declare interface AudioFileMetadata {
88
88
  /**
89
89
  * The name of the file including extension.
90
90
  */
@@ -755,7 +755,7 @@ export declare interface GenericFileBlock {
755
755
  filename: string;
756
756
  }
757
757
 
758
- declare interface GenericFileMetadata {
758
+ export declare interface GenericFileMetadata {
759
759
  /**
760
760
  * The name of the file including extension.
761
761
  */
@@ -816,7 +816,7 @@ export declare interface ImageBlock {
816
816
  height?: number;
817
817
  }
818
818
 
819
- declare interface ImageFileMetadata {
819
+ export declare interface ImageFileMetadata {
820
820
  /**
821
821
  * The name of the file including extension.
822
822
  */
@@ -1978,7 +1978,7 @@ export declare interface VideoBlock {
1978
1978
  duration?: number;
1979
1979
  }
1980
1980
 
1981
- declare interface VideoFileMetadata {
1981
+ export declare interface VideoFileMetadata {
1982
1982
  /**
1983
1983
  * The name of the file including extension.
1984
1984
  */
@@ -2041,7 +2041,7 @@ export declare interface VoiceBlock {
2041
2041
  duration?: number;
2042
2042
  }
2043
2043
 
2044
- declare interface VoiceRecordingFileMetadata {
2044
+ export declare interface VoiceRecordingFileMetadata {
2045
2045
  /**
2046
2046
  * The name of the file including extension.
2047
2047
  */
@@ -128,9 +128,9 @@ let p = null;
128
128
  function f({ WebSocket: e2 }) {
129
129
  p = e2;
130
130
  }
131
- class m {
131
+ class g {
132
132
  constructor(e2, t2) {
133
- this.realtimeUrl = e2, this.handlers = t2, this.socket = null, this.throttler = new g(), this.stateMachine = new u("ReconnectingSocket", ["STOPPED", "WAITING_FOR_THROTTLER", "CONNECTING", "READY", "TERMINATED"], { queueAutoReconnect: { from: ["READY", "CONNECTING"], to: "WAITING_FOR_THROTTLER", afterTransition: ({ from: e3 }) => {
133
+ this.realtimeUrl = e2, this.handlers = t2, this.socket = null, this.throttler = new m(), this.stateMachine = new u("ReconnectingSocket", ["STOPPED", "WAITING_FOR_THROTTLER", "CONNECTING", "READY", "TERMINATED"], { queueAutoReconnect: { from: ["READY", "CONNECTING"], to: "WAITING_FOR_THROTTLER", afterTransition: ({ from: e3 }) => {
134
134
  "READY" === e3 && this.handlers.onClose(), this.throttler.request(() => {
135
135
  this.stateMachine.transition("connect");
136
136
  });
@@ -181,7 +181,7 @@ class m {
181
181
  this.stateMachine.transition("destroy");
182
182
  }
183
183
  }
184
- let g = class {
184
+ let m = class {
185
185
  constructor() {
186
186
  this.initialDelayMs = 200 + 200 * Math.random(), this.exponentialFactor = 1.2, this.maxDelayMs = 1e4, this.currentDelayMs = this.initialDelayMs;
187
187
  }
@@ -195,7 +195,7 @@ let g = class {
195
195
  };
196
196
  class v {
197
197
  constructor(e2, t2) {
198
- this.handlers = t2, this.socket = new m(e2, { onOpen: () => this.handlers.onOpen(), onClose: () => this.handlers.onClose(), onMessage: (e3) => this.onWebSocketMessage(e3) });
198
+ this.handlers = t2, this.socket = new g(e2, { onOpen: () => this.handlers.onOpen(), onClose: () => this.handlers.onClose(), onMessage: (e3) => this.onWebSocketMessage(e3) });
199
199
  }
200
200
  call(e2, t2, s2, n2) {
201
201
  const r2 = `/${s2.map((e3) => encodeURIComponent(e3)).join("/")}`, i2 = JSON.stringify([e2, t2, r2, n2]);
@@ -1166,7 +1166,7 @@ class ce extends W {
1166
1166
  fetchInitial(e2) {
1167
1167
  return __async(this, null, function* () {
1168
1168
  const t2 = this.onlyUsedInternally ? 1 : 30, s2 = yield le({ realtimeClient: this.realtimeClient, conversationId: this.conversationId, count: t2 });
1169
- return s2.ok ? null === s2.value.messages ? c({ lastChanged: e2, stores: null, inWindow: null, windowEnd: null }) : he({ seq: e2, messages: s2.value.messages, cursor: s2.value.nextCursor, conversationId: this.conversationId, realtimeClient: this.realtimeClient }) : s2;
1169
+ return s2.ok ? null === s2.value.messages ? c({ lastChanged: e2, lastMessageChanged: e2, stores: null, inWindow: null, windowEnd: null }) : he({ seq: e2, messages: s2.value.messages, cursor: s2.value.nextCursor, conversationId: this.conversationId, realtimeClient: this.realtimeClient }) : s2;
1170
1170
  });
1171
1171
  }
1172
1172
  teardownNested(e2) {
@@ -1177,11 +1177,12 @@ class ce extends W {
1177
1177
  }
1178
1178
  loadNested(e2, t2) {
1179
1179
  return __async(this, null, function* () {
1180
- if (null === t2.stores) return c({ snapshot: null, loadedAll: true, lastChanged: t2.lastChanged });
1180
+ var _a2, _b;
1181
+ if (null === t2.stores) return c({ snapshot: null, loadedAll: true, lastChanged: t2.lastChanged, lastMessageChanged: t2.lastMessageChanged });
1181
1182
  const s2 = yield Promise.all(t2.inWindow.map((t3) => t3.getDeep(e2))), n2 = s2.find((e3) => !e3.ok);
1182
1183
  if (n2) return n2;
1183
- const r2 = s2, i2 = r2.filter((e3) => null !== e3.value.snapshot).map((e3) => e3.value.snapshot), a2 = Math.max(t2.lastChanged, ...r2.map((e3) => e3.value.lastChanged));
1184
- return c({ snapshot: i2, loadedAll: null === t2.windowEnd, lastChanged: a2 });
1184
+ const r2 = s2, i2 = r2.filter((e3) => null !== e3.value.snapshot).map((e3) => e3.value.snapshot), a2 = Math.max(t2.lastChanged, ...r2.map((e3) => e3.value.lastChanged)), o2 = (_a2 = r2[0]) == null ? void 0 : _a2.value, u2 = Math.max(t2.lastMessageChanged, (_b = o2 == null ? void 0 : o2.lastChanged) != null ? _b : -1);
1185
+ return c({ snapshot: i2, loadedAll: null === t2.windowEnd, lastChanged: a2, lastMessageChanged: u2 });
1185
1186
  });
1186
1187
  }
1187
1188
  loadMore(e2) {
@@ -1212,7 +1213,8 @@ class ce extends W {
1212
1213
  null === i2 ? a2 = null : i2 in n2 ? a2 = n2[i2] : (a2 = new oe(e2, this.conversationId, i2, this.realtimeClient), n2[i2] = a2);
1213
1214
  const o2 = new ue(e2, t2.state.createdAt, r2, a2), u2 = [...s2.value.inWindow, o2];
1214
1215
  u2.sort((e3, t3) => t3.createdAt - e3.createdAt);
1215
- return c({ lastChanged: e2, stores: n2, inWindow: u2, windowEnd: s2.value.windowEnd });
1216
+ const l2 = u2[0].messageId === t2.messageId ? e2 : s2.value.lastMessageChanged;
1217
+ return c({ lastChanged: e2, lastMessageChanged: l2, stores: n2, inWindow: u2, windowEnd: s2.value.windowEnd });
1216
1218
  });
1217
1219
  }
1218
1220
  messageEdited(e2, t2) {
@@ -1231,17 +1233,21 @@ class ce extends W {
1231
1233
  if (t2.newLastMessage && 0 === r2.length) {
1232
1234
  const s3 = new oe(e2, this.conversationId, t2.newLastMessage, this.realtimeClient);
1233
1235
  n2[s3.messageId] = s3;
1234
- const i2 = t2.newLastMessage.referencedMessageId;
1236
+ const i3 = t2.newLastMessage.referencedMessageId;
1235
1237
  let a2;
1236
- null === i2 ? a2 = null : i2 in n2 ? a2 = n2[i2] : (a2 = new oe(e2, this.conversationId, i2, this.realtimeClient), n2[i2] = a2);
1238
+ null === i3 ? a2 = null : i3 in n2 ? a2 = n2[i3] : (a2 = new oe(e2, this.conversationId, i3, this.realtimeClient), n2[i3] = a2);
1237
1239
  const o2 = new ue(e2, t2.newLastMessage.createdAt, s3, a2);
1238
1240
  r2.push(o2);
1239
1241
  }
1240
- return c({ lastChanged: e2, stores: n2, inWindow: r2, windowEnd: s2.value.windowEnd });
1242
+ const i2 = void 0 !== t2.newLastMessage ? e2 : s2.value.lastMessageChanged;
1243
+ return c({ lastChanged: e2, lastMessageChanged: i2, stores: n2, inWindow: r2, windowEnd: s2.value.windowEnd });
1241
1244
  });
1242
1245
  }
1243
1246
  conversationCleared(e2, t2) {
1244
- this.mutate(e2, (t3) => (de(t3.value), c({ lastChanged: e2, stores: {}, inWindow: [], windowEnd: null })));
1247
+ this.mutate(e2, (t3) => {
1248
+ var _a2;
1249
+ return 0 === ((_a2 = t3.value.inWindow) == null ? void 0 : _a2.length) && null === t3.value.windowEnd ? t3 : (de(t3.value), c({ lastChanged: e2, lastMessageChanged: e2, stores: {}, inWindow: [], windowEnd: null }));
1250
+ });
1245
1251
  }
1246
1252
  sideCreated(e2, t2) {
1247
1253
  const s2 = this.fetchInitial(e2);
@@ -1250,7 +1256,7 @@ class ce extends W {
1250
1256
  }), e3) : s2);
1251
1257
  }
1252
1258
  sideDeleted(e2, t2) {
1253
- this.mutate(e2, (t3) => (de(t3.value), c({ lastChanged: e2, stores: null, inWindow: null, windowEnd: null })));
1259
+ this.mutate(e2, (t3) => null === t3.value.stores ? t3 : (de(t3.value), c({ lastChanged: e2, lastMessageChanged: e2, stores: null, inWindow: null, windowEnd: null })));
1254
1260
  }
1255
1261
  getMessageFromCache(e2) {
1256
1262
  return __async(this, null, function* () {
@@ -1273,6 +1279,7 @@ function le(_0) {
1273
1279
  });
1274
1280
  }
1275
1281
  function he({ seq: e2, prevState: t2, messages: s2, cursor: n2, conversationId: r2, realtimeClient: i2 }) {
1282
+ var _a2, _b, _c, _d;
1276
1283
  const a2 = t2 ? __spreadValues({}, t2.stores) : {};
1277
1284
  for (const t3 of s2) if (void 0 === a2[t3.id]) {
1278
1285
  const s3 = new oe(e2, r2, t3, i2);
@@ -1287,8 +1294,10 @@ function he({ seq: e2, prevState: t2, messages: s2, cursor: n2, conversationId:
1287
1294
  }
1288
1295
  const o2 = t2 ? [...t2.inWindow] : [];
1289
1296
  for (const t3 of s2) o2.push(new ue(e2, t3.createdAt, a2[t3.id], t3.referencedMessageId ? a2[t3.referencedMessageId] : null));
1290
- if (o2.sort((e3, t3) => t3.createdAt - e3.createdAt), null === n2) return c({ lastChanged: e2, stores: a2, inWindow: o2, windowEnd: null });
1291
- return c({ lastChanged: e2, stores: a2, inWindow: o2, windowEnd: { cursor: n2, oldestMessageTs: s2[s2.length - 1].createdAt } });
1297
+ o2.sort((e3, t3) => t3.createdAt - e3.createdAt);
1298
+ const u2 = (_b = (_a2 = t2 == null ? void 0 : t2.inWindow) == null ? void 0 : _a2[0]) == null ? void 0 : _b.messageId, l2 = (_c = o2 == null ? void 0 : o2[0]) == null ? void 0 : _c.messageId, h2 = u2 === l2 ? (_d = t2 == null ? void 0 : t2.lastMessageChanged) != null ? _d : e2 : e2;
1299
+ if (null === n2) return c({ lastChanged: e2, lastMessageChanged: h2, stores: a2, inWindow: o2, windowEnd: null });
1300
+ return c({ lastChanged: e2, lastMessageChanged: h2, stores: a2, inWindow: o2, windowEnd: { cursor: n2, oldestMessageTs: s2[s2.length - 1].createdAt } });
1292
1301
  }
1293
1302
  function de(e2) {
1294
1303
  if (e2.stores) {
@@ -1327,7 +1336,7 @@ class pe extends W {
1327
1336
  const s2 = yield t2.messageWindowStore.store.getDeep(e2);
1328
1337
  if (!s2.ok) return s2;
1329
1338
  const n2 = s2.value.snapshot, r2 = (_a2 = n2 == null ? void 0 : n2[0]) != null ? _a2 : null;
1330
- return c({ lastChanged: Math.max(t2.lastChanged, s2.value.lastChanged), snapshot: __spreadProps(__spreadValues({}, t2.snapshot), { lastMessage: r2 }) });
1339
+ return c({ lastChanged: Math.max(t2.lastChanged, s2.value.lastMessageChanged), snapshot: __spreadProps(__spreadValues({}, t2.snapshot), { lastMessage: r2 }) });
1331
1340
  });
1332
1341
  }
1333
1342
  participantEdited(e2, t2) {
@@ -1356,7 +1365,7 @@ function fe(e2, t2) {
1356
1365
  const s2 = t2;
1357
1366
  return { id: e2.id, createdAt: e2.createdAt, subject: P(e2.subject, s2.subject), photoUrl: P(e2.photoUrl, s2.photoUrl), welcomeMessages: P(e2.welcomeMessages, s2.welcomeMessages), custom: O(e2.custom, s2.custom), lastMessageAt: P(e2.lastMessageAt, s2.lastMessageAt), unreadMessageCount: P(e2.unreadMessageCount, s2.unreadMessageCount), isUnread: P(e2.isUnread, s2.isUnread), access: P(e2.access, s2.access), notify: P(e2.notify, s2.notify), readUntil: P(e2.readUntil, s2.readUntil), joinedAt: e2.joinedAt };
1358
1367
  }
1359
- class me {
1368
+ class ge {
1360
1369
  constructor(e2, t2, s2) {
1361
1370
  this.realtimeClient = s2, this.userStores = {}, this.messageWindowStores = {}, this.conversationStores = {}, this.emitMutex = new j(), this.seqOffset = 0, this.seqInThisConnection = 0, this.refetchOnNextNetworkLoss = true, this.connection = new _(e2, t2, { onUpstreamRestarting: () => {
1362
1371
  this.refetchOnNextNetworkLoss = false;
@@ -1582,9 +1591,9 @@ class me {
1582
1591
  return this.connection.isConnected();
1583
1592
  }
1584
1593
  }
1585
- class ge {
1594
+ class me {
1586
1595
  constructor(e2, t2, s2) {
1587
- this.userId = t2, this.alive = true, this.connection = new me(e2, s2, this), s2.onTokenRefreshFailed(() => {
1596
+ this.userId = t2, this.alive = true, this.connection = new ge(e2, s2, this), s2.onTokenRefreshFailed(() => {
1588
1597
  this.destroy();
1589
1598
  });
1590
1599
  }
@@ -2157,10 +2166,10 @@ var je, $e = function() {
2157
2166
  f2(h2);
2158
2167
  break;
2159
2168
  case 3:
2160
- m2(h2);
2169
+ g2(h2);
2161
2170
  break;
2162
2171
  case 4:
2163
- g2(h2);
2172
+ m2(h2);
2164
2173
  break;
2165
2174
  case 5:
2166
2175
  v2(h2);
@@ -2186,10 +2195,10 @@ var je, $e = function() {
2186
2195
  function f2(e4) {
2187
2196
  "." === e4 ? c2 = 3 : "@" === e4 ? c2 = 4 : s2.test(e4) || A2();
2188
2197
  }
2189
- function m2(e4) {
2198
+ function g2(e4) {
2190
2199
  "." === e4 || "@" === e4 ? A2() : s2.test(e4) ? c2 = 2 : A2();
2191
2200
  }
2192
- function g2(e4) {
2201
+ function m2(e4) {
2193
2202
  ut.test(e4) ? c2 = 5 : A2();
2194
2203
  }
2195
2204
  function v2(e4) {
@@ -2241,21 +2250,21 @@ var je, $e = function() {
2241
2250
  }, e2.urlMatchDoesNotHaveAtLeastOneWordChar = function(e3, t2) {
2242
2251
  return !(!e3 || !t2) && (!this.hasFullProtocolRegex.test(t2) && !this.hasWordCharAfterProtocolRegex.test(e3));
2243
2252
  }, e2.hasFullProtocolRegex = /^[A-Za-z][-.+A-Za-z0-9]*:\/\//, e2.uriSchemeRegex = /^[A-Za-z][-.+A-Za-z0-9]*:/, e2.hasWordCharAfterProtocolRegex = new RegExp(":[^\\s]*?[" + Xe + "]"), e2.ipRegex = /[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?(:[0-9]*)?\/?$/, e2;
2244
- }(), mt = (je = new RegExp("[/?#](?:[" + nt + "\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*[" + nt + "\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"), new RegExp(["(?:", "(", /(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source, ot(2), ")", "|", "(", "(//)?", /(?:www\.)/.source, ot(6), ")", "|", "(", "(//)?", ot(10) + "\\.", ct.source, "(?![-" + st + "])", ")", ")", "(?::[0-9]+)?", "(?:" + je.source + ")?"].join(""), "gi")), gt = new RegExp("[" + nt + "]"), vt = function(e2) {
2253
+ }(), gt = (je = new RegExp("[/?#](?:[" + nt + "\\-+&@#/%=~_()|'$*\\[\\]{}?!:,.;^✓]*[" + nt + "\\-+&@#/%=~_()|'$*\\[\\]{}✓])?"), new RegExp(["(?:", "(", /(?:[A-Za-z][-.+A-Za-z0-9]{0,63}:(?![A-Za-z][-.+A-Za-z0-9]{0,63}:\/\/)(?!\d+\/?)(?:\/\/)?)/.source, ot(2), ")", "|", "(", "(//)?", /(?:www\.)/.source, ot(6), ")", "|", "(", "(//)?", ot(10) + "\\.", ct.source, "(?![-" + st + "])", ")", ")", "(?::[0-9]+)?", "(?:" + je.source + ")?"].join(""), "gi")), mt = new RegExp("[" + nt + "]"), vt = function(e2) {
2245
2254
  function t2(t3) {
2246
2255
  var s2 = e2.call(this, t3) || this;
2247
- return s2.stripPrefix = { scheme: true, www: true }, s2.stripTrailingSlash = true, s2.decodePercentEncoding = true, s2.matcherRegex = mt, s2.wordCharRegExp = gt, s2.stripPrefix = t3.stripPrefix, s2.stripTrailingSlash = t3.stripTrailingSlash, s2.decodePercentEncoding = t3.decodePercentEncoding, s2;
2256
+ return s2.stripPrefix = { scheme: true, www: true }, s2.stripTrailingSlash = true, s2.decodePercentEncoding = true, s2.matcherRegex = gt, s2.wordCharRegExp = mt, s2.stripPrefix = t3.stripPrefix, s2.stripTrailingSlash = t3.stripTrailingSlash, s2.decodePercentEncoding = t3.decodePercentEncoding, s2;
2248
2257
  }
2249
2258
  return Ue(t2, e2), t2.prototype.parseMatches = function(e3) {
2250
2259
  for (var t3, s2 = this.matcherRegex, n2 = this.stripPrefix, r2 = this.stripTrailingSlash, i2 = this.decodePercentEncoding, a2 = this.tagBuilder, o2 = [], u2 = function() {
2251
- var s3 = t3[0], u3 = t3[1], l2 = t3[4], h2 = t3[5], d2 = t3[9], p2 = t3.index, f2 = h2 || d2, m2 = e3.charAt(p2 - 1);
2260
+ var s3 = t3[0], u3 = t3[1], l2 = t3[4], h2 = t3[5], d2 = t3[9], p2 = t3.index, f2 = h2 || d2, g2 = e3.charAt(p2 - 1);
2252
2261
  if (!ft.isValid(s3, u3)) return "continue";
2253
- if (p2 > 0 && "@" === m2) return "continue";
2254
- if (p2 > 0 && f2 && c2.wordCharRegExp.test(m2)) return "continue";
2262
+ if (p2 > 0 && "@" === g2) return "continue";
2263
+ if (p2 > 0 && f2 && c2.wordCharRegExp.test(g2)) return "continue";
2255
2264
  if (/\?$/.test(s3) && (s3 = s3.substr(0, s3.length - 1)), c2.matchHasUnbalancedClosingParen(s3)) s3 = s3.substr(0, s3.length - 1);
2256
2265
  else {
2257
- var g2 = c2.matchHasInvalidCharAfterTld(s3, u3);
2258
- g2 > -1 && (s3 = s3.substr(0, g2));
2266
+ var m2 = c2.matchHasInvalidCharAfterTld(s3, u3);
2267
+ m2 > -1 && (s3 = s3.substr(0, m2));
2259
2268
  }
2260
2269
  var v2 = ["http://", "https://"].find(function(e4) {
2261
2270
  return !!u3 && -1 !== u3.indexOf(e4);
@@ -2340,10 +2349,10 @@ function Dt(e2, t2) {
2340
2349
  var f2 = e2.charAt(c2);
2341
2350
  switch (h2) {
2342
2351
  case 0:
2343
- m2(f2);
2352
+ g2(f2);
2344
2353
  break;
2345
2354
  case 1:
2346
- g2(f2);
2355
+ m2(f2);
2347
2356
  break;
2348
2357
  case 2:
2349
2358
  b2(f2);
@@ -2407,10 +2416,10 @@ function Dt(e2, t2) {
2407
2416
  }
2408
2417
  c2++;
2409
2418
  }
2410
- function m2(e3) {
2419
+ function g2(e3) {
2411
2420
  "<" === e3 && O2();
2412
2421
  }
2413
- function g2(e3) {
2422
+ function m2(e3) {
2414
2423
  "!" === e3 ? h2 = 13 : "/" === e3 ? (h2 = 2, p2 = new It($e($e({}, p2), { isClosing: true }))) : "<" === e3 ? O2() : Je.test(e3) ? (h2 = 3, p2 = new It($e($e({}, p2), { isOpening: true }))) : (h2 = 0, p2 = u2);
2415
2424
  }
2416
2425
  function v2(e3) {
@@ -2822,7 +2831,7 @@ class ts {
2822
2831
  function ss({ method: e2, url: t2, data: s2, options: n2, attempts: r2, shouldRetry: i2, authProvider: o2 }) {
2823
2832
  var _a2;
2824
2833
  (!r2 || r2 <= 0) && (r2 = 1);
2825
- const u2 = { "x-talkjs-client-build": "jssdk-dev", "x-talkjs-client-date": "2025-04-29T08:55:37.472Z" };
2834
+ const u2 = { "x-talkjs-client-build": "jssdk-dev", "x-talkjs-client-date": "2025-04-30T13:41:48.005Z" };
2826
2835
  s2 instanceof FormData || (u2["Content-Type"] = (_a2 = n2 == null ? void 0 : n2.contentType) != null ? _a2 : "application/json");
2827
2836
  return a(r2, () => __async(this, null, function* () {
2828
2837
  if (o2) {
@@ -2875,7 +2884,7 @@ const cs = rs.startsWith("app.talkjs.com");
2875
2884
  const ls = "undefined" == typeof window ? { log: (e2) => Promise.resolve(), setData: (e2) => {
2876
2885
  } } : new class {
2877
2886
  constructor(e2) {
2878
- this._timeCreated = Date.now(), this._enabled = cs, this._trackJSData = { customer: { application: "", correlationId: "", sessionId: "", token: "", userId: "", version: "dev-2025-04-29T08:55:37.472Z" }, entry: "direct", environment: { age: Date.now() - this._timeCreated, dependencies: {}, originalUrl: window.location.href, referrer: document.referrer, userAgent: window.navigator.userAgent }, metadata: [], nav: [], network: [], url: window.location.href, stack: "", timestamp: (/* @__PURE__ */ new Date()).toISOString(), version: "dev-2025-04-29T08:55:37.472Z", throttled: 0 }, this._url = `https://capture.trackjs.com/capture?token=${e2}`, this._trackJSData.customer.token = e2;
2887
+ this._timeCreated = Date.now(), this._enabled = cs, this._trackJSData = { customer: { application: "", correlationId: "", sessionId: "", token: "", userId: "", version: "dev-2025-04-30T13:41:48.005Z" }, entry: "direct", environment: { age: Date.now() - this._timeCreated, dependencies: {}, originalUrl: window.location.href, referrer: document.referrer, userAgent: window.navigator.userAgent }, metadata: [], nav: [], network: [], url: window.location.href, stack: "", timestamp: (/* @__PURE__ */ new Date()).toISOString(), version: "dev-2025-04-30T13:41:48.005Z", throttled: 0 }, this._url = `https://capture.trackjs.com/capture?token=${e2}`, this._trackJSData.customer.token = e2;
2879
2888
  }
2880
2889
  setData({ appId: e2, meId: t2, sessionId: s2 }) {
2881
2890
  this._trackJSData.customer.userId = e2, this._trackJSData.customer.sessionId = `${e2}/${t2}`, this._trackJSData.customer.correlationId = s2;
@@ -3091,7 +3100,7 @@ function ps(e2) {
3091
3100
  }
3092
3101
  }
3093
3102
  const fs = new ts("wss://realtime.talkjs.com/v1", "https://app.talkjs.com/api/v0", "https://api.talkjs.com/v1");
3094
- class ms {
3103
+ class gs {
3095
3104
  constructor(e2) {
3096
3105
  this.target = e2;
3097
3106
  }
@@ -3099,7 +3108,7 @@ class ms {
3099
3108
  return this.target;
3100
3109
  }
3101
3110
  }
3102
- const gs = new class {
3111
+ const ms = new class {
3103
3112
  constructor() {
3104
3113
  this.registry = {};
3105
3114
  }
@@ -3107,7 +3116,7 @@ const gs = new class {
3107
3116
  var _a2;
3108
3117
  const t2 = this.key(e2), s2 = (_a2 = this.registry[t2]) == null ? void 0 : _a2.deref();
3109
3118
  if (s2) return s2;
3110
- const n2 = new bs(e2), r2 = globalThis.WeakRef ? new WeakRef(n2) : new ms(n2);
3119
+ const n2 = new bs(e2), r2 = globalThis.WeakRef ? new WeakRef(n2) : new gs(n2);
3111
3120
  return this.registry[t2] = r2, n2;
3112
3121
  }
3113
3122
  deregister(e2, t2) {
@@ -3119,7 +3128,7 @@ const gs = new class {
3119
3128
  }
3120
3129
  }();
3121
3130
  function vs(e2) {
3122
- return e2.forceCreateNew ? new bs(e2) : gs.getOrCreate(e2);
3131
+ return e2.forceCreateNew ? new bs(e2) : ms.getOrCreate(e2);
3123
3132
  }
3124
3133
  class bs {
3125
3134
  constructor(e2) {
@@ -3131,7 +3140,7 @@ class bs {
3131
3140
  void 0 !== e3.tokenFetcher && t3("function" == typeof e3.tokenFetcher, "The `tokenFetcher` property of TalkSession#constructor must be a function.");
3132
3141
  }(e2);
3133
3142
  const { appId: t2, userId: s2, token: n2, tokenFetcher: r2, signature: i2 } = e2;
3134
- this._appId = t2, this._apiUrls = e2.apiUrls ? new ts(e2.apiUrls.realtimeWsApiUrl, e2.apiUrls.internalHttpApiUrl, e2.apiUrls.restApiHttpUrl) : fs, this._authProvider = new ds(this._apiUrls, t2, s2, n2, r2, i2), this._realtimeClient = new ge(this._apiUrls.getRealtimeWsUrl(t2, s2, "1.0.0", e2.clientBuild), s2, this._authProvider), this.currentUser = new we(this._realtimeClient.userId, this._realtimeClient), this._terminationReason = o(), this._terminationReason.promise.then((e3) => {
3143
+ this._appId = t2, this._apiUrls = e2.apiUrls ? new ts(e2.apiUrls.realtimeWsApiUrl, e2.apiUrls.internalHttpApiUrl, e2.apiUrls.restApiHttpUrl) : fs, this._authProvider = new ds(this._apiUrls, t2, s2, n2, r2, i2), this._realtimeClient = new me(this._apiUrls.getRealtimeWsUrl(t2, s2, "1.0.1", e2.clientBuild), s2, this._authProvider), this.currentUser = new we(this._realtimeClient.userId, this._realtimeClient), this._terminationReason = o(), this._terminationReason.promise.then((e3) => {
3135
3144
  console.error(`[TalkSession] ${e3}`);
3136
3145
  }), function(e3, t3, s3) {
3137
3146
  return __async(this, null, function* () {
@@ -3162,7 +3171,7 @@ class bs {
3162
3171
  return new Kt(e2, this._realtimeClient);
3163
3172
  }
3164
3173
  terminate(e2) {
3165
- gs.deregister(this._appId, this.currentUser.id), this._terminationReason.resolve(e2), this._realtimeClient.destroy();
3174
+ ms.deregister(this._appId, this.currentUser.id), this._terminationReason.resolve(e2), this._realtimeClient.destroy();
3166
3175
  }
3167
3176
  _isConnected() {
3168
3177
  return this._realtimeClient.isConnected();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talkjs/core",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Lets you connect to your TalkJS chat as a user and read, subscribe to, and update your chat data.",
5
5
  "bugs": {
6
6
  "url": "https://talkjs.com/?chat"
@@ -69,4 +69,4 @@
69
69
  "notification",
70
70
  "notifications"
71
71
  ]
72
- }
72
+ }