PageSourceSearch

https://www.numerama.com/wp-content/mu-plugins/optimus/build/js/chunks/index-srqb0Rfi.js

js numerama.com collected 2026-09-24 08:38:42 UTC 150,939 bytes, 22 lines download raw bytes

1var xs=Object.defineProperty;var Ns=(e,t,n)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var I=(e,t,n)=>Ns(e,typeof t!="symbol"?t+"":t,n);import{c as ni}from"./react-i3XfpDzi.js";var Rs=Object.defineProperty,Ps=Object.defineProperties,Us=Object.getOwnPropertyDescriptors,tn=Object.getOwnPropertySymbols,Oi=Object.prototype.hasOwnProperty,xi=Object.prototype.propertyIsEnumerable,Ni=e=>{throw TypeError(e)},ii=(e,t,n)=>t in e?Rs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))Oi.call(t,n)&&ii(e,n,t[n]);if(tn)for(var n of tn(t))xi.call(t,n)&&ii(e,n,t[n]);return e},y=(e,t)=>Ps(e,Us(t)),Bn=(e,t)=>{var n={};for(var i in e)Oi.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(e!=null&&tn)for(var i of tn(e))t.indexOf(i)<0&&xi.call(e,i)&&(n[i]=e[i]);return n},Dn=(e,t,n)=>t.has(e)||Ni("Cannot "+n),o=(e,t,n)=>(Dn(e,t,"read from private field"),n?n.call(e):t.get(e)),p=(e,t,n)=>t.has(e)?Ni("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,i)=>(Dn(e,t,"write to private field"),t.set(e,n),n),S=(e,t,n)=>(Dn(e,t,"access private method"),n),Ri=(e,t,n,i)=>({set _(s){v(e,t,s)},get _(){return o(e,t,i)}}),l=(e,t,n)=>new Promise((i,s)=>{var r=h=>{try{c(n.next(h))}catch(u){s(u)}},a=h=>{try{c(n.throw(h))}catch(u){s(u)}},c=h=>h.done?i(h.value):Promise.resolve(h.value).then(r,a);c((n=n.apply(e,t)).next())});function si(e){if(!e)return"";const t=[];for(const[n,i]of Object.entries(e))if(i){const s=typeof i=="string"?i:i.id;t.push(`${n}:${s}`)}return t.sort().join(",")}function Ls({subscriberId:e,subscriber:t}){return t?typeof t=="string"?{subscriberId:t}:t:e?{subscriberId:e}:{subscriberId:""}}function Ms({topicKey:e,subscriberId:t,contextKey:n}){const i=`tk_${e}:si_${t}`;return n&&n.length>0?`${i}:ctx_${n}`:i}var Ws=(e=>(e.READ="read",e.SEEN="seen",e.SNOOZED="snoozed",e.UNREAD="unread",e.UNSEEN="unseen",e.UNSNOOZED="unsnoozed",e))(Ws||{}),Fs=(e=>(e.GLOBAL="global",e.TEMPLATE="template",e))(Fs||{}),$s=(e=>(e.IN_APP="in_app",e.EMAIL="email",e.SMS="sms",e.CHAT="chat",e.PUSH="push",e.TOOL="tool",e))($s||{}),Bs=(e=>(e.RECEIVED="notification_received",e.UNREAD="unread_count_changed",e.UNSEEN="unseen_count_changed",e))(Bs||{}),Ds=(e=>(e.HIGH="high",e.MEDIUM="medium",e.LOW="low",e.NONE="none",e))(Ds||{}),Ks=(e=>(e.CRITICAL="critical",e.NON_CRITICAL="nonCritical",e.ALL="all",e))(Ks||{}),w=class extends Error{constructor(e,t){super(e),this.originalError=t}},L,q,P=class{constructor(e,t,n){p(this,L),p(this,q),v(this,L,t),v(this,q,n),this.id=e.id,this.transactionId=e.transactionId,this.subject=e.subject,this.body=e.body,this.to=e.to,this.isRead=e.isRead,this.isSeen=e.isSeen,this.isArchived=e.isArchived,this.isSnoozed=e.isSnoozed,this.snoozedUntil=e.snoozedUntil,this.deliveredAt=e.deliveredAt,this.createdAt=e.createdAt,this.readAt=e.readAt,this.firstSeenAt=e.firstSeenAt,this.archivedAt=e.archivedAt,this.avatar=e.avatar,this.primaryAction=e.primaryAction,this.secondaryAction=e.secondaryAction,this.channelType=e.channelType,this.tags=e.tags,this.redirect=e.redirect,this.data=e.data,this.workflow=e.workflow,this.severity=e.severity}read(){return Pi({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}unread(){return Ui({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}seen(){return Li({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}archive(){return Mi({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}unarchive(){return Wi({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}delete(){return Bi({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}snooze(e){return Fi({emitter:o(this,L),apiService:o(this,q),args:{notification:this,snoozeUntil:e}})}unsnooze(){return $i({emitter:o(this,L),apiService:o(this,q),args:{notification:this}})}completePrimary(){if(!this.primaryAction)throw new Error("Primary action is not available");return nn({emitter:o(this,L),apiService:o(this,q),args:{notification:this},actionType:"primary"})}completeSecondary(){if(!this.primaryAction)throw new Error("Secondary action is not available");return nn({emitter:o(this,L),apiService:o(this,q),args:{notification:this},actionType:"secondary"})}revertPrimary(){if(!this.primaryAction)throw new Error("Primary action is not available");return sn({emitter:o(this,L),apiService:o(this,q),args:{notification:this},actionType:"primary"})}revertSecondary(){if(!this.primaryAction)throw new Error("Secondary action is not available");return sn({emitter:o(this,L),apiService:o(this,q),args:{notification:this},actionType:"secondary"})}on(e,t){const n=o(this,L).on(e,t);return()=>{n()}}off(e,t){o(this,L).off(e,t)}};L=new WeakMap;q=new WeakMap;function qs({notification:e,emitter:t,inboxService:n}){return e instanceof P||typeof e.read=="function"?e:new P(e,t,n)}var Pi=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isRead:!0,readAt:new Date().toISOString(),isArchived:!1,archivedAt:void 0},{emitter:t,apiService:n});try{t.emit("notification.read.pending",{args:i,data:r});const a=yield n.read(s),c=new P(a,t,n);return t.emit("notification.read.resolved",{args:i,data:c}),{data:c}}catch(a){return t.emit("notification.read.resolved",{args:i,error:a}),{error:new w("Failed to read notification",a)}}}),Ui=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isRead:!1,readAt:null,isArchived:!1,archivedAt:void 0},{emitter:t,apiService:n});try{t.emit("notification.unread.pending",{args:i,data:r});const a=yield n.unread(s),c=new P(a,t,n);return t.emit("notification.unread.resolved",{args:i,data:c}),{data:c}}catch(a){return t.emit("notification.unread.resolved",{args:i,error:a}),{error:new w("Failed to unread notification",a)}}}),Li=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isSeen:!0},{emitter:t,apiService:n});try{if(t.emit("notification.seen.pending",{args:i,data:r}),yield n.seen(s),!r)throw new Error("Failed to create optimistic value for notification");const a=new P(r,t,n);return t.emit("notification.seen.resolved",{args:i,data:a}),{data:a}}catch(a){return t.emit("notification.seen.resolved",{args:i,error:a}),{error:new w("Failed to mark notification as seen",a)}}}),Mi=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isArchived:!0,archivedAt:new Date().toISOString(),isRead:!0,readAt:new Date().toISOString()},{emitter:t,apiService:n});try{t.emit("notification.archive.pending",{args:i,data:r});const a=yield n.archive(s),c=new P(a,t,n);return t.emit("notification.archive.resolved",{args:i,data:c}),{data:c}}catch(a){return t.emit("notification.archive.resolved",{args:i,error:a}),{error:new w("Failed to archive notification",a)}}}),Wi=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isArchived:!1,archivedAt:null,isRead:!0,readAt:new Date().toISOString()},{emitter:t,apiService:n});try{t.emit("notification.unarchive.pending",{args:i,data:r});const a=yield n.unarchive(s),c=new P(a,t,n);return t.emit("notification.unarchive.resolved",{args:i,data:c}),{data:c}}catch(a){return t.emit("notification.unarchive.resolved",{args:i,error:a}),{error:new w("Failed to unarchive notification",a)}}}),Fi=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isSnoozed:!0,snoozedUntil:i.snoozeUntil},{emitter:t,apiService:n});try{t.emit("notification.snooze.pending",{args:i,data:r});const a=yield n.snooze(s,i.snoozeUntil),c=new P(a,t,n);return t.emit("notification.snooze.resolved",{args:i,data:c}),{data:c}}catch(a){return t.emit("notification.snooze.resolved",{args:i,error:a}),{error:new w("Failed to snooze notification",a)}}}),$i=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s,optimisticValue:r}=re(i,{isSnoozed:!1,snoozedUntil:null},{emitter:t,apiService:n});try{t.emit("notification.unsnooze.pending",{args:i,data:r});const a=yield n.unsnooze(s),c=new P(a,t,n);return t.emit("notification.unsnooze.resolved",{args:i,data:c}),{data:c}}catch(a){return t.emit("notification.unsnooze.resolved",{args:i,error:a}),{error:new w("Failed to unsnooze notification",a)}}}),nn=e=>l(null,[e],function*({emitter:t,apiService:n,args:i,actionType:s}){const r=s==="primary"?{primaryAction:y(d({},"notification"in i?i.notification.primaryAction:{}),{isCompleted:!0})}:{secondaryAction:y(d({},"notification"in i?i.notification.secondaryAction:{}),{isCompleted:!0})},{notificationId:a,optimisticValue:c}=re(i,r,{emitter:t,apiService:n});try{t.emit("notification.complete_action.pending",{args:i,data:c});const h=yield n.completeAction({actionType:s,notificationId:a}),u=new P(h,t,n);return t.emit("notification.complete_action.resolved",{args:i,data:u}),{data:u}}catch(h){return t.emit("notification.complete_action.resolved",{args:i,error:h}),{error:new w(`Failed to complete ${s} action on the notification`,h)}}}),sn=e=>l(null,[e],function*({emitter:t,apiService:n,args:i,actionType:s}){const r=s==="primary"?{primaryAction:y(d({},"notification"in i?i.notification.primaryAction:{}),{isCompleted:!1})}:{secondaryAction:y(d({},"notification"in i?i.notification.secondaryAction:{}),{isCompleted:!1})},{notificationId:a,optimisticValue:c}=re(i,r,{emitter:t,apiService:n});try{t.emit("notification.revert_action.pending",{args:i,data:c});const h=yield n.revertAction({actionType:s,notificationId:a}),u=new P(h,t,n);return t.emit("notification.revert_action.resolved",{args:i,data:u}),{data:u}}catch(h){return t.emit("notification.revert_action.resolved",{args:i,error:h}),{error:new w("Failed to fetch notifications",h)}}}
1),re=(e,t,n)=>"notification"in e?{notificationId:e.notification.id,optimisticValue:new P(d(d({},e.notification),t),n.emitter,n.apiService)}:{notificationId:e.notificationId},zs=e=>l(null,[e],function*({emitter:t,inboxService:n,notificationsCache:i,tags:s,data:r}){try{const c=i.getUniqueNotifications({tags:s,data:r}).map(h=>new P(y(d({},h),{isRead:!0,readAt:new Date().toISOString(),isArchived:!1,archivedAt:void 0}),t,n));return t.emit("notifications.read_all.pending",{args:{tags:s,data:r},data:c}),yield n.readAll({tags:s,data:r}),t.emit("notifications.read_all.resolved",{args:{tags:s,data:r},data:c}),{}}catch(a){return t.emit("notifications.read_all.resolved",{args:{tags:s,data:r},error:a}),{error:new w("Failed to read all notifications",a)}}}),ri=e=>l(null,[e],function*({emitter:t,inboxService:n,notificationsCache:i,notificationIds:s,tags:r,data:a}){try{const c=i.getUniqueNotifications({tags:r,data:a}),u=(s&&s.length>0?c.filter(f=>s.includes(f.id)):c).map(f=>new P(y(d({},f),{isSeen:!0,firstSeenAt:f.firstSeenAt||new Date().toISOString()}),t,n));return t.emit("notifications.seen_all.pending",{args:{notificationIds:s,tags:r,data:a},data:u}),yield n.markAsSeen({notificationIds:s,tags:r,data:a}),t.emit("notifications.seen_all.resolved",{args:{notificationIds:s,tags:r,data:a},data:u}),{}}catch(c){return t.emit("notifications.seen_all.resolved",{args:{notificationIds:s,tags:r,data:a},error:c}),{error:new w("Failed to mark all notifications as seen",c)}}}),Vs=e=>l(null,[e],function*({emitter:t,inboxService:n,notificationsCache:i,tags:s,data:r}){try{const c=i.getUniqueNotifications({tags:s,data:r}).map(h=>new P(y(d({},h),{isRead:!0,readAt:new Date().toISOString(),isArchived:!0,archivedAt:new Date().toISOString()}),t,n));return t.emit("notifications.archive_all.pending",{args:{tags:s,data:r},data:c}),yield n.archiveAll({tags:s,data:r}),t.emit("notifications.archive_all.resolved",{args:{tags:s,data:r},data:c}),{}}catch(a){return t.emit("notifications.archive_all.resolved",{args:{tags:s,data:r},error:a}),{error:new w("Failed to archive all notifications",a)}}}),Hs=e=>l(null,[e],function*({emitter:t,inboxService:n,notificationsCache:i,tags:s,data:r}){try{const c=i.getUniqueNotifications({tags:s,data:r,read:!0}).map(h=>new P(y(d({},h),{isArchived:!0,archivedAt:new Date().toISOString()}),t,n));return t.emit("notifications.archive_all_read.pending",{args:{tags:s,data:r},data:c}),yield n.archiveAllRead({tags:s,data:r}),t.emit("notifications.archive_all_read.resolved",{args:{tags:s,data:r},data:c}),{}}catch(a){return t.emit("notifications.archive_all_read.resolved",{args:{tags:s,data:r},error:a}),{error:new w("Failed to archive all read notifications",a)}}}),Bi=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const{notificationId:s}=re(i,{},{emitter:t,apiService:n});try{return t.emit("notification.delete.pending",{args:i}),yield n.delete(s),t.emit("notification.delete.resolved",{args:i}),{}}catch(r){return t.emit("notification.delete.resolved",{args:i,error:r}),{error:new w("Failed to delete notification",r)}}}),Gs=e=>l(null,[e],function*({emitter:t,inboxService:n,notificationsCache:i,tags:s,data:r}){try{const a=i.getUniqueNotifications({tags:s,data:r});return t.emit("notifications.delete_all.pending",{args:{tags:s,data:r},data:a}),yield n.deleteAll({tags:s,data:r}),t.emit("notifications.delete_all.resolved",{args:{tags:s,data:r}}),{}}catch(a){return t.emit("notifications.delete_all.resolved",{args:{tags:s,data:r},error:a}),{error:new w("Failed to delete all notifications",a)}}});function js(e){return{all:e=e||new Map,on:function(t,n){var i=e.get(t);i?i.push(n):e.set(t,[n])},off:function(t,n){var i=e.get(t);i&&(n?i.splice(i.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var i=e.get(t);i&&i.slice().map(function(s){s(n)}),(i=e.get("*"))&&i.slice().map(function(s){s(t,n)})}}}const un=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof ni<"u"&&ni,Js=function(){try{new un.Event("")}catch{return!0}return!1}(),Ys=function(){try{new un.EventTarget}catch{return!0}return!1}();Js&&(un.Event=function(){function e(t,n){this.bubbles=!!n&&!!n.bubbles,this.cancelable=!!n&&!!n.cancelable,this.composed=!!n&&!!n.composed,this.type=t}return e}());Ys&&(un.EventTarget=function(){function e(){this.__listeners=new Map}return e.prototype=Object.create(Object.prototype),e.prototype.addEventListener=function(t,n,i){if(arguments.length<2)throw new TypeError("TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only "+arguments.length+" present.");
1const s=this.__listeners,r=t.toString();s.has(r)||s.set(r,new Map);const a=s.get(r);a.has(n)||a.set(n,i)},e.prototype.removeEventListener=function(t,n,i){if(arguments.length<2)throw new TypeError("TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only "+arguments.length+" present.");const s=this.__listeners,r=t.toString();if(s.has(r)){const a=s.get(r);a.has(n)&&a.delete(n)}},e.prototype.dispatchEvent=function(t){if(!(t instanceof Event))throw new TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.");const n=t.type,s=this.__listeners.get(n);if(s)for(var r of s.entries()){const a=r[0],c=r[1];try{typeof a=="function"?a.call(this,t):a&&typeof a.handleEvent=="function"&&a.handleEvent(t)}catch(h){setTimeout(()=>{throw h})}c&&c.once&&s.delete(a)}return!0},e}());(!globalThis.EventTarget||!globalThis.Event)&&console.error(`
2  PartySocket requires a global 'EventTarget' class to be available!
3  You can polyfill this global by adding this to your code before any partysocket imports: 
4  
5  \`\`\`
6  import 'partysocket/event-target-polyfill';
7  \`\`\`
8  Please file an issue at https://github.com/partykit/partykit if you're still having trouble.
9`);var Di=class extends Event{constructor(t,n){super("error",n);I(this,"message");I(this,"error");this.message=t.message,this.error=t}},Ki=class extends Event{constructor(t=1e3,n="",i){super("close",i);I(this,"code");I(this,"reason");I(this,"wasClean",!0);this.code=t,this.reason=n}};const gn={Event,ErrorEvent:Di,CloseEvent:Ki};function Qs(e,t){if(!e)throw new Error(t)}function Xs(e){return new e.constructor(e.type,e)}function Zs(e){return"data"in e?new MessageEvent(e.type,e):"code"in e||"reason"in e?new Ki(e.code||1999,e.reason||"unknown reason",e):"error"in e?new Di(e.error,e):new Event(e.type,e)}var Ti;const er=typeof process<"u"&&typeof((Ti=process.versions)==null?void 0:Ti.node)<"u",tr=typeof navigator<"u"&&navigator.product==="ReactNative",St=er||tr?Zs:Xs,we={maxReconnectionDelay:1e4,minReconnectionDelay:3e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:Number.POSITIVE_INFINITY,maxEnqueuedMessages:Number.POSITIVE_INFINITY};let oi=!1;function nr(){}var qi=class fe extends EventTarget{constructor(n,i,s={}){super();I(this,"_ws");I(this,"_retryCount",-1);I(this,"_uptimeTimeout");I(this,"_connectTimeout");I(this,"_shouldReconnect",!0);I(this,"_connectLock",!1);I(this,"_binaryType","blob");I(this,"_closeCalled",!1);I(this,"_didWarnAboutClosedSend",!1);I(this,"_messageQueue",[]);I(this,"_debugLogger",console.log.bind(console));I(this,"_url");I(this,"_protocols");I(this,"_options");I(this,"onclose",null);I(this,"onerror",null);I(this,"onmessage",null);I(this,"onopen",null);I(this,"_handleOpen",n=>{this._debug("open event");const{minUptime:i=we.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),Qs(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(s=>{var r;(r=this._ws)==null||r.send(s)}),this._messageQueue=[],this.onopen&&this.onopen(n),this.dispatchEvent(St(n))});I(this,"_handleMessage",n=>{this._debug("message event"),this.onmessage&&this.onmessage(n),this.dispatchEvent(St(n))});I(this,"_handleError",n=>{this._debug("error event",n.message),this._disconnect(void 0,n.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(n),this._debug("exec error listeners"),this.dispatchEvent(St(n)),this._connect()});I(this,"_handleClose",n=>{this._debug("close event"),this._clearTimeouts(),this._options.shouldReconnectOnClose&&!this._options.shouldReconnectOnClose(n)&&(this._shouldReconnect=!1),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(n),this.dispatchEvent(St(n))});this._url=n,this._protocols=i,this._options=s,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return fe.CONNECTING}get OPEN(){return fe.OPEN}get CLOSING(){return fe.CLOSING}get CLOSED(){return fe.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(n){this._binaryType=n,this._ws&&(this._ws.binaryType=n)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((n,i)=>(typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._closeCalled?fe.CLOSED:this._ws?this._ws.readyState:this._options.startClosed?fe.CLOSED:fe.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}close(n=1e3,i){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING){this._debug("close: already closing or closed");return}this._disconnect(n,i)}reconnect(n,i){this._shouldReconnect=!0,this._closeCalled=!1,this._didWarnAboutClosedSend=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING?this._connect():(this._disconnect(n,i),this._connect())}send(n){if(this._ws&&this._ws.readyState===this.OPEN)return this._debug("send",n),this._ws.send(n),!0;this._closeCalled&&!this._didWarnAboutClosedSend&&(this._didWarnAboutClosedSend=!0,console.warn("ReconnectingWebSocket: send() was called after close(). The message has been buffered, but it will only be delivered if reconnect() is called on this socket. If this socket has been discarded, the message is lost — this usually means a 
9stale socket reference is being used."));const{maxEnqueuedMessages:i=we.maxEnqueuedMessages}=this._options;return this._messageQueue.length<i&&(this._debug("enqueue",n),this._messageQueue.push(n)),!1}drainQueuedMessages(){const n=this._messageQueue;return this._messageQueue=[],n}_debug(...n){this._options.debug&&this._debugLogger("RWS>",...n)}_getNextDelay(){const{reconnectionDelayGrowFactor:n=we.reconnectionDelayGrowFactor,minReconnectionDelay:i=we.minReconnectionDelay,maxReconnectionDelay:s=we.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=i*n**(this._retryCount-1),r>s&&(r=s)),this._debug("next delay",r),r}_wait(){return new Promise(n=>{setTimeout(n,this._getNextDelay())})}_getNextProtocols(n){if(!n)return Promise.resolve(null);if(typeof n=="string"||Array.isArray(n))return Promise.resolve(n);if(typeof n=="function"){const i=n();if(!i)return Promise.resolve(null);if(typeof i=="string"||Array.isArray(i))return Promise.resolve(i);if(i.then)return i}throw Error("Invalid protocols")}_getNextUrl(n){if(typeof n=="string")return Promise.resolve(n);if(typeof n=="function"){const i=n();if(typeof i=="string")return Promise.resolve(i);if(i.then)return i}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;
9const{maxRetries:n=we.maxRetries,connectionTimeout:i=we.connectionTimeout}=this._options;if(this._retryCount>=n){this._debug("max retries reached",this._retryCount,">=",n),this._connectLock=!1;return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>Promise.all([this._getNextUrl(this._url),this._getNextProtocols(this._protocols||null)])).then(([s,r])=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!oi&&(console.error(`‼️ No WebSocket implementation available. You should define options.WebSocket. 
10
11For example, if you're using node.js, run \`npm install ws\`, and then in your code:
12
13import PartySocket from 'partysocket';
14import WS from 'ws';
15
16const partysocket = new PartySocket({
17  host: "127.0.0.1:1999",
18  room: "test-room",
19  WebSocket: WS
20});
21
22`),oi=!0);const a=this._options.WebSocket||WebSocket;this._debug("connect",{url:s,protocols:r}),this._ws=r?new a(s,r):new a(s),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),i)}).catch(s=>{this._connectLock=!1,this._handleError(new gn.ErrorEvent(Error(s.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new gn.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(n=1e3,i){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(n,i),this._handleClose(new gn.CloseEvent(n,i,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError),this._ws.addEventListener("error",nr))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};const se=Object.create(null);se.open="0";se.close="1";se.ping="2";se.pong="3";se.message="4";se.upgrade="5";se.noop="6";const Ct=Object.create(null);Object.keys(se).forEach(e=>{Ct[se[e]]=e});const An={type:"error",data:"parser error"},zi=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Vi=typeof ArrayBuffer=="function",Hi=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Kn=({type:e,data:t},n,i)=>zi&&t instanceof Blob?n?i(t):ai(t,i):Vi&&(t instanceof ArrayBuffer||Hi(t))?n?i(t):ai(new Blob([t]),i):i(se[e]+(t||"")),ai=(e,t)=>{const n=new FileReader;return n.onload=function(){const i=n.result.split(",")[1];t("b"+(i||""))},n.readAsDataURL(e)};function ci(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let wn;function ir(e,t){if(zi&&e.data instanceof Blob)return e.data.arrayBuffer().then(ci).then(t);if(Vi&&(e.data instanceof ArrayBuffer||Hi(e.data)))return t(ci(e.data));Kn(e,!1,n=>{wn||(wn=new TextEncoder),t(wn.encode(n))})}const hi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",st=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<hi.length;e++)st[hi.charCodeAt(e)]=e;const sr=e=>{let t=e.length*.75,n=e.length,i,s=0,r,a,c,h;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),f=new Uint8Array(u);for(i=0;i<n;i+=4)r=st[e.charCodeAt(i)],a=st[e.charCodeAt(i+1)],c=st[e.charCodeAt(i+2)],h=st[e.charCodeAt(i+3)],f[s++]=r<<2|a>>4,f[s++]=(a&15)<<4|c>>2,f[s++]=(c&3)<<6|h&63;return u},rr=typeof ArrayBuffer=="function",qn=(e,t)=>{if(typeof e!="string")return{type:"message",data:Gi(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:or(e.substring(1),t)}:Ct[n]?e.length>1?{type:Ct[n],data:e.substring(1)}:{type:Ct[n]}:An},or=(e,t)=>
22{if(rr){const n=sr(e);return Gi(n,t)}else return{base64:!0,data:e}},Gi=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},ji="�",ar=(e,t)=>{const n=e.length,i=new Array(n);let s=0;e.forEach((r,a)=>{Kn(r,!1,c=>{i[a]=c,++s===n&&t(i.join(ji))})})},cr=(e,t)=>{const n=e.split(ji),i=[];for(let s=0;s<n.length;s++){const r=qn(n[s],t);if(i.push(r),r.type==="error")break}return i};function hr(){return new TransformStream({transform(e,t){ir(e,n=>{const i=n.length;let s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);const r=new DataView(s.buffer);r.setUint8(0,126),r.setUint16(1,i)}else{s=new Uint8Array(9);const r=new DataView(s.buffer);r.setUint8(0,127),r.setBigUint64(1,BigInt(i))}e.data&&typeof e.data!="string"&&(s[0]|=128),t.enqueue(s),t.enqueue(n)})}})}let bn;function kt(e){return e.reduce((t,n)=>t+n.length,0)}function Et(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let i=0;for(let s=0;s<t;s++)n[s]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),n}function lr(e,t){bn||(bn=new TextDecoder);const n=[];let i=0,s=-1,r=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(i===0){if(kt(n)<1)break;const h=Et(n,1);r=(h[0]&128)===128,s=h[0]&127,s<126?i=3:s===126?i=1:i=2}else if(i===1){if(kt(n)<2)break;const h=Et(n,2);s=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),i=3}else if(i===2){if(kt(n)<8)break;const h=Et(n,8),u=new DataView(h.buffer,h.byteOffset,h.length),f=u.getUint32(0);if(f>Math.pow(2,21)-1){c.enqueue(An);break}s=f*Math.pow(2,32)+u.getUint32(4),i=3}else{if(kt(n)<s)break;const h=Et(n,s);c.enqueue(qn(r?h:bn.decode(h),t)),i=0}if(s===0||s>e){c.enqueue(An);break}}}})}const Ji=4;function x(e){if(e)return ur(e)}function ur(e){for(var t in x.prototype)e[t]=x.prototype[t];return e}x.prototype.on=x.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};x.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};x.prototype.off=x.prototype.removeListener=x.prototype.removeAllListeners=x.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var i,s=0;s<n.length;s++)if(i=n[s],i===t||i.fn===t){n.splice(s,1);break}return n.length===0&&delete this._callbacks["$"+e],this};x.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(n){n=n.slice(0);for(var i=0,s=n.length;i<s;++i)n[i].apply(this,t)}return this};x.prototype.emitReserved=x.prototype.emit;x.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};x.prototype.hasListeners=function(e){return!!this.listeners(e).length};const dn=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),G=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),dr="arraybuffer";function Yi(e,...t){return t.reduce((n,i)=>(e.hasOwnProperty(i)&&(n[i]=e[i]),n),{})}const fr=G.setTimeout,pr=G.clearTimeout;function fn(e,t){t.useNativeTimers?(e.setTimeoutFn=fr.bind(G),e.clearTimeoutFn=pr.bind(G)):(e.setTimeoutFn=G.setTimeout.bind(G),e.clearTimeoutFn=G.clearTimeout.bind(G))}const vr=1.33;function yr(e){return typeof e=="string"?_r(e):Math.ceil((e.byteLength||e.size)*vr)}function _r(e){let t=0,n=0;for(let i=0,s=e.length;i<s;i++)t=e.charCodeAt(i),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(i++,n+=4);return n}function Qi(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function mr(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function gr(e){let t={},n=e.split("&");for(let i=0,s=n.length;i<s;i++){let r=n[i].split("=");
22t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}class wr extends Error{constructor(t,n,i){super(t),this.description=n,this.context=i,this.type="TransportError"}}class zn extends x{constructor(t){super(),this.writable=!1,fn(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,i){return super.emitReserved("error",new wr(t,n,i)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=qn(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const n=mr(t);return n.length?"?"+n:""}}class br extends zn{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let i=0;this._polling&&(i++,this.once("pollComplete",function(){--i||n()})),this.writable||(i++,this.once("drain",function(){--i||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=i=>{if(this.readyState==="opening"&&i.type==="open"&&this.onOpen(),i.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(i)};cr(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,ar(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=Qi()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let Xi=!1;try{Xi=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Sr=Xi;function kr(){}class Er extends br{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let i=location.port;i||(i=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||i!==t.port}}doWrite(t,n){const i=this.request({method:"POST",data:t});i.on("success",n),i.on("error",(s,r)=>{this.onError("xhr post error",s,r)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,i)=>{this.onError("xhr poll error",n,i)}),this.pollXhr=t}}class ie extends x{constructor(t,n,i){super(),this.createRequest=t,fn(this,i),this._opts=i,this._method=i.method||"GET",this._uri=n,this._data=i.data!==void 0?i.data:null,this._create()}_create(){var t;const n=Yi(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(n);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&i.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{i.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var s;i.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(i.getResponseHeader("set-cookie"))),i.readyState===4&&(i.status===200||i.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof i.status=="number"?i.status:0)},0))},i.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=ie.requestsCount++,ie.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=kr,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ie.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}ie.requestsCount=0;ie.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",li);else if(typeof addEventListener=="function"){const e="onpagehide"in G?"pagehide":"unload";addEventListener(e,li,!1)}}function li(){for(let e in ie.requests)ie.requests.hasOwnProperty(e)&&ie.requests[e].abort()}const Ar=function(){const e=Zi({xdomain:!1});return e&&e.responseType!==null}();
22class Ir extends Er{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=Ar&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ie(Zi,this.uri(),t)}}function Zi(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Sr))return new XMLHttpRequest}catch{}if(!t)try{return new G[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const es=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Cr extends zn{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,i=es?{}:Yi(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,i)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const i=t[n],s=n===t.length-1;Kn(i,this.supportsBinary,r=>{try{this.doWrite(i,r)}catch{}s&&dn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=Qi()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Sn=G.WebSocket||G.MozWebSocket;class Tr extends Cr{createSocket(t,n,i){return es?new Sn(t,n,i):n?new Sn(t,n):new Sn(t)}doWrite(t,n){this.ws.send(n)}}class Or extends zn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=lr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(n).getReader(),s=hr();s.readable.pipeTo(t.writable),this._writer=s.writable.getWriter();const r=()=>{i.read().then(({done:c,value:h})=>{c||(this.onPacket(h),r())}).catch(c=>{})};r();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const i=t[n],s=n===t.length-1;this._writer.write(i).then(()=>{s&&dn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const xr={websocket:Tr,webtransport:Or,polling:Ir},Nr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Rr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function In(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),i=e.indexOf("]");n!=-1&&i!=-1&&(e=e.substring(0,n)+e.substring(n,i).replace(/:/g,";")+e.substring(i,e.length));let s=Nr.exec(e||""),r={},a=14;for(;a--;)r[Rr[a]]=s[a]||"";return n!=-1&&i!=-1&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=Pr(r,r.path),r.queryKey=Ur(r,r.query),r}function Pr(e,t){const n=/\/{2,9}/g,i=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&i.splice(0,1),t.slice(-1)=="/"&&i.splice(i.length-1,1),i}function Ur(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(i,s,r){s&&(n[s]=r)}),n}const Cn=typeof addEventListener=="function"&&typeof removeEventListener=="function",Tt=[];Cn&&addEventListener("offline",()=>
22{Tt.forEach(e=>e())},!1);class me extends x{constructor(t,n){if(super(),this.binaryType=dr,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const i=In(t);n.hostname=i.host,n.secure=i.protocol==="https"||i.protocol==="wss",n.port=i.port,i.query&&(n.query=i.query)}else n.host&&(n.hostname=In(n.host).host);fn(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(i=>{const s=i.prototype.name;this.transports.push(s),this._transportsByName[s]=i}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=gr(this.opts.query)),Cn&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Tt.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=Ji,n.transport=t,this.id&&(n.sid=this.id);const i=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](i)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&me.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",me.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let i=0;i<this.writeBuffer.length;i++){const s=this.writeBuffer[i].data;if(s&&(n+=yr(s)),i>0&&n>this._maxPayload)return this.writeBuffer.slice(0,i);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,dn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,i){return this._sendPacket("message",t,n,i),this}send(t,n,i){return this._sendPacket("message",t,n,i),this}_sendPacket(t,n,i,s){if(typeof n=="function"&&(s=n,n=void 0),typeof i=="function"&&(s=i,i=null),this.readyState==="closing"||this.readyState==="closed")return;i=i||{},i.compress=i.compress!==!1;const r={type:t,data:n,options:i};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},i=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?i():t()}):this.upgrading?i():t()),this}_onError(t){if(me.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Cn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const i=Tt.indexOf(this._offlineEventListener);i!==-1&&Tt.splice(i,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}me.protocol=Ji;class Lr extends me{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),i=!1;me.priorWebsocketSuccess=!1;const s=()=>{i||(n.send([{type:"ping",data:"probe"}]),n.once("packet",g=>{if(!i)if(g.type==="pong"&&g.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;me.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{i||this.readyState!=="closed"&&(f(),this.setTransport(n),n.send([{type:"upgrade"}
22]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function r(){i||(i=!0,f(),n.close(),n=null)}const a=g=>{const m=new Error("probe error: "+g);m.transport=n.name,r(),this.emitReserved("upgradeError",m)};function c(){a("transport closed")}function h(){a("socket closed")}function u(g){n&&g.name!==n.name&&r()}const f=()=>{n.removeListener("open",s),n.removeListener("error",a),n.removeListener("close",c),this.off("close",h),this.off("upgrading",u)};n.once("open",s),n.once("error",a),n.once("close",c),this.once("close",h),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{i||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let i=0;i<t.length;i++)~this.transports.indexOf(t[i])&&n.push(t[i]);return n}}let Mr=class extends Lr{constructor(t,n={}){const i=typeof t=="object",s=i?{...t}:{...n};(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>xr[r]).filter(r=>!!r)),super(i?s:t,s)}};function Wr(e,t="",n){let i=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),i=In(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const r=i.host.indexOf(":")!==-1?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+r+":"+i.port+t,i.href=i.protocol+"://"+r+(n&&n.port===i.port?"":":"+i.port),i}const Fr=typeof ArrayBuffer=="function",$r=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,ts=Object.prototype.toString,Br=typeof Blob=="function"||typeof Blob<"u"&&ts.call(Blob)==="[object BlobConstructor]",Dr=typeof File=="function"||typeof File<"u"&&ts.call(File)==="[object FileConstructor]";function Vn(e){return Fr&&(e instanceof ArrayBuffer||$r(e))||Br&&e instanceof Blob||Dr&&e instanceof File}function Ot(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,i=e.length;n<i;n++)if(Ot(e[n]))return!0;return!1}if(Vn(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Ot(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Ot(e[n]))return!0;return!1}function Kr(e){const t=[],n=e.data,i=e;return i.data=xt(n,t),i.attachments=t.length,{packet:i,buffers:t}}function xt(e,t,n){if(!e)return e;if(Vn(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}else if(Array.isArray(e)){const i=new Array(e.length);for(let s=0;s<e.length;s++)i[s]=xt(e[s],t);return i}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return xt(e.toJSON(),t,!0);const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=xt(e[s],t));return i}return e}function qr(e,t){return e.data=Tn(e.data,t),delete e.attachments,e}function Tn(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=Tn(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=Tn(e[n],t));return e}const zr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var k;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(k||(k={}));class Vr{constructor(t){this.replacer=t}encode(t){return(t.type===k.EVENT||t.type===k.ACK)&&Ot(t)?this.encodeAsBinary({type:t.type===k.EVENT?k.BINARY_EVENT:k.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===k.BINARY_EVENT||t.type===k.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=Kr(t),i=this.encodeAsString(n.packet),s=n.buffers;return s.unshift(i),s}}class Hn extends x{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const i=n.type===k.BINARY_EVENT;i||n.type===k.BINARY_ACK?(n.type=i?k.EVENT:k.ACK,this.reconstructor=new Hr(n)):super.emitReserved("decoded",n)}else if(Vn(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const i={type:Number(t.charAt(0))};if(k[i.type]===void 0)throw new Error("unknown packet type "+i.type);if(i.type===k.BINARY_EVENT||i.type===k.BINARY_ACK){const r=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const a=t.substring(r,n);if(a!=Number(a)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const c=Number(a);if(!Gr(c)||c<1)throw new Error("Illegal attachments");if(c>this.opts.maxAttachments)throw new Error("too many attachments");i.attachments=c}if(t.charAt(n+1)==="/"){const r=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););i.nsp=t.substring(r,n)}else i.nsp="/";const s=t.charAt(n+1);if(s!==""&&Number(s)==s){const r=n+1;for(;++n;){const a=t.charAt(n);if(a==null||Number(a)!=a){--n;break}if(n===t.length)break}i.id=Number(t.substring(r,n+1))}
22if(t.charAt(++n)){const r=this.tryParse(t.substr(n));if(Hn.isPayloadValid(i.type,r))i.data=r;else throw new Error("invalid payload")}return i}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case k.CONNECT:return ui(n);case k.DISCONNECT:return n===void 0;case k.CONNECT_ERROR:return typeof n=="string"||ui(n);case k.EVENT:case k.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&zr.indexOf(n[0])===-1);case k.ACK:case k.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Hr{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=qr(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Gr=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function ui(e){return Object.prototype.toString.call(e)==="[object Object]"}const jr=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Hn,Encoder:Vr,get PacketType(){return k}},Symbol.toStringTag,{value:"Module"}));function J(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const Jr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});let ns=class extends x{constructor(t,n,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=n,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[J(t,"open",this.onopen.bind(this)),J(t,"packet",this.onpacket.bind(this)),J(t,"error",this.onerror.bind(this)),J(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var i,s,r;if(Jr.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const a={type:k.EVENT,data:n};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const f=this.ids++,g=n.pop();this._registerAckCallback(f,g),a.id=f}const c=(s=(i=this.io.engine)===null||i===void 0?void 0:i.transport)===null||s===void 0?void 0:s.writable,h=this.connected&&!(!((r=this.io.engine)===null||r===void 0)&&r._hasPingExpired());return this.flags.volatile&&!c||(h?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(t,n){var i;const s=(i=this.flags.timeout)!==null&&i!==void 0?i:this._opts.ackTimeout;if(s===void 0){this.acks[t]=n;return}const r=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===t&&this.sendBuffer.splice(c,1);n.call(this,new Error("operation has timed out"))},s),a=(...c)=>{this.io.clearTimeoutFn(r),n.apply(this,c)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...n){return new Promise((i,s)=>{const r=(a,c)=>a?s(a):i(c);r.withError=!0,n.push(r),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((s,...r)=>(this._queue[0],s!==null?i.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(s)):(this._queue.shift(),n&&n(null,...r)),i.pending=!1,this._drainQueue())),this._queue.push(i),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:k.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}
22_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(i=>String(i.id)===t)){const i=this.acks[t];delete this.acks[t],i.withError&&i.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case k.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case k.EVENT:case k.BINARY_EVENT:this.onevent(t);break;case k.ACK:case k.BINARY_ACK:this.onack(t);break;case k.DISCONNECT:this.ondisconnect();break;case k.CONNECT_ERROR:this.destroy();const i=new Error(t.data.message);i.data=t.data.data,this.emitReserved("connect_error",i);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const i of n)i.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let i=!1;return function(...s){i||(i=!0,n.packet({type:k.ACK,id:t,data:s}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:k.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let i=0;i<n.length;i++)if(t===n[i])return n.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let i=0;i<n.length;i++)if(t===n[i])return n.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const i of n)i.apply(this,t.data)}}};function ze(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ze.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};ze.prototype.reset=function(){this.attempts=0};ze.prototype.setMin=function(e){this.ms=e};ze.prototype.setMax=function(e){this.max=e};ze.prototype.setJitter=function(e){this.jitter=e};class On extends x{constructor(t,n){var i;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,fn(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((i=n.randomizationFactor)!==null&&i!==void 0?i:.5),this.backoff=new ze({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const s=n.parser||jr;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Mr(this.uri,this.opts);const n=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const s=J(n,"open",function(){i.onopen(),t&&t()}),r=c=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",c),t?t(c):this.maybeReconnectOnOpen()},a=J(n,"error",r);if(this._timeout!==!1){const c=this._timeout,h=this.setTimeoutFn(()=>{s(),r(new Error("timeout")),n.close()},c);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(s),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(J(t,"ping",this.onping.bind(this)),J(t,"data",this.ondata.bind(this)),J(t,"error",this.onerror.bind(this)),J(t,"close",this.onclose.bind(this)),J(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){dn(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let i=this.nsps[t];return i?this._autoConnect&&!i.active&&i.connect():(i=new ns(this,t,n),this.nsps[t]=i),i}_destroy(t){const n=Object.keys(this.nsps);for(const i of n)if(this.nsps[i].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let i=0;i<n.length;i++)this.engine.write(n[i],t.options)}
22cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var i;this.cleanup(),(i=this.engine)===null||i===void 0||i.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const i=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(s=>{s?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",s)):t.onreconnect()}))},n);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const nt={};function Nt(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=Wr(e,t.path||"/socket.io"),i=n.source,s=n.id,r=n.path,a=nt[s]&&r in nt[s].nsps,c=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let h;return c?h=new On(i,t):(nt[s]||(nt[s]=new On(i,t)),h=nt[s]),n.query&&!t.query&&(t.query=n.queryKey),h.socket(n.path,t)}Object.assign(Nt,{Manager:On,Socket:ns,io:Nt,connect:Nt});var Ka=["notification.read.resolved","notification.unread.resolved","notification.seen.resolved","notification.archive.resolved","notification.unarchive.resolved","notification.snooze.resolved","notification.unsnooze.resolved","notification.delete.resolved","notifications.read_all.resolved","notifications.seen_all.resolved","notifications.archive_all.resolved","notifications.archive_all_read.resolved","notifications.delete_all.resolved"],Yr=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,i)=>n===t[i]),di=30,rn=100,fi=200,R=class extends Error{constructor(e){super(e),this.name="TagsFilterValidationError"}};function pi(e,t){if(e.length>t)throw new R(`At most ${t} tags are allowed in a single OR-group`);for(const n of e)if(typeof n!="string")throw new R("Tags must be strings");return e}function Qr(e){const t=Object.keys(e),n=Object.prototype.hasOwnProperty.call(e,"or"),i=Object.prototype.hasOwnProperty.call(e,"and");if(n&&i)throw new R('Tags filter cannot have both "or" and "and"');if(n){if(t.length!==1)throw new R("Invalid tags filter object");const s=e.or;if(!Array.isArray(s))throw new R('"or" must be an array of strings');return s.length===0?[]:[pi(s,rn)]}if(i){if(t.length!==1)throw new R("Invalid tags filter object");const s=e.and;if(!Array.isArray(s))throw new R('"and" must be an array');if(s.length===0)return[];if(s.length>di)throw new R(`At most ${di} tag groups are allowed`);const r=[];let a=0;for(const c of s){if(typeof c!="object"||c===null||Array.isArray(c))throw new R('Each "and" entry must be an object { or: string[] }');if(Object.keys(c).length!==1||!Object.prototype.hasOwnProperty.call(c,"or"))throw new R('Each "and" entry must be { or: string[] }');const u=c.or;if(!Array.isArray(u))throw new R('"or" must be an array of strings');if(u.length===0)throw new R("Each tag group must be a non-empty array of strings");const f=pi(u,rn);a+=f.length,r.push(f)}if(a>fi)throw new R(`At most ${fi} total tag values are allowed`);return r}throw new R('Tags filter object must have "or" or "and"')}function is(e){if(e===void 0)return[];if(e===null)throw new R("Tags must be an array or object");if(typeof e=="object"&&!Array.isArray(e))return Qr(e);if(!Array.isArray(e))throw new R("Tags must be an array or object");if(e.length===0)return[];if(Array.isArray(e[0]))throw new R("Nested tag arrays are not supported; use { and: [{ or: string[] }, ...] } for multiple OR-groups");const t=e;if(t.length>rn)throw new R(`At most ${rn} tags are allowed in a single OR-group`);for(const n of t)if(typeof n!="string")throw new R("Tags must be strings");return[t]}function vi(e){if(e===void 0)return"";const t=is(e);if(t.length===0)return"";const n=Array.from(new Map(t.map(i=>{const s=Array.from(new Set(i)).sort((r,a)=>r.localeCompare(a));return[JSON.stringify(s),s]})).values()).sort((i,s)=>JSON.stringify(i).localeCompare(JSON.stringify(s)));return JSON.stringify(n)}var ss=(e,t)=>{try{return vi(e)===vi(t)}catch{return!1}},Xr=(e,t)=>
22{const n=Array.isArray(e)?e:e?[e]:[],i=Array.isArray(t)?t:t?[t]:[];return Yr(n,i)},rs=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}},yi=(e,t)=>rs(e.data,t.data)&&ss(e.tags,t.tags)&&e.read===t.read&&e.archived===t.archived&&e.snoozed===t.snoozed&&e.seen===t.seen&&Xr(e.severity,t.severity)&&e.createdGte===t.createdGte&&e.createdLte===t.createdLte;function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zr(e){return Object.prototype.hasOwnProperty.call(e,"or")||Object.prototype.hasOwnProperty.call(e,"and")}function At(e){return e===null||typeof e=="boolean"||typeof e=="string"?!0:typeof e=="number"?Number.isFinite(e):!1}function eo(e){if(e===void 0)return[];if(Array.isArray(e))return e.length===0?[]:e.every(At)?[e]:null;if(xn(e)){const t=Object.prototype.hasOwnProperty.call(e,"or"),n=Object.prototype.hasOwnProperty.call(e,"and");if(t&&n)return null;const i=Object.keys(e);if(t){if(i.length!==1)return null;const s=e.or;return Array.isArray(s)?s.length===0?[]:s.every(At)?[s]:null:null}if(n){if(i.length!==1)return null;const s=e.and;if(!Array.isArray(s))return null;const r=[];for(const a of s){if(!xn(a)||Object.keys(a).length!==1||!("or"in a))return null;const h=a.or;if(!Array.isArray(h)||h.length===0||!h.every(At))return null;r.push(h)}return r}return null}return At(e)?[[e]]:null}function to(e,t){let n=e;for(const i of t){if(n==null||typeof n!="object"||Array.isArray(n))return;n=n[i]}return n}function no(e,t){return Array.isArray(t)?t.some(n=>e.some(i=>i===n)):e.some(n=>n===t)}function os(e,t,n,i){if(i>2)return!1;for(const[s,r]of Object.entries(t)){if(s.startsWith("$")||s.startsWith(".")||s==="__proto__"||s==="constructor"||s==="prototype")return!1;const a=[...n,s];if(xn(r)&&!Zr(r)){if(!os(e,r,a,i+1))return!1;continue}const c=eo(r);if(c===null)return!1;if(c.length===0)continue;const h=e?to(e,a):void 0;if(h===void 0||!c.every(u=>no(u,h)))return!1}return!0}function io(e,t){return!t||Object.keys(t).length===0?!0:e?os(e,t,[],1):!1}function as(e,t){let n;try{n=is(t)}catch{return!1}return n.length===0?!0:!e||e.length===0?!1:n.every(i=>i.some(s=>e.includes(s)))}function cs(e,t){return!(t.read!==void 0&&e.isRead!==t.read||t.seen!==void 0&&e.isSeen!==t.seen||t.archived!==void 0&&e.isArchived!==t.archived||t.snoozed!==void 0&&e.isSnoozed!==t.snoozed)}function so(e,t,n){if(!t&&!n)return!0;const i=new Date(e).getTime();return!(t&&i<t||n&&i>n)}function qa(e,t){return cs(e,t)&&as(e.tags,t.tags)&&io(e.data,t.data)&&so(e.createdAt,t.createdGte,t.createdLte)}var pe,ve,Se,ke,rt,bt=class{constructor(e,t,n,i,s){p(this,pe),p(this,ve),p(this,Se),p(this,ke),p(this,rt,!1);var r;v(this,pe,t),v(this,ve,n),v(this,Se,i),v(this,ke,s),this.id=e.id,this.identifier=e.identifier,this.topicKey=e.topicKey,this.preferences=(r=e.preferences)==null?void 0:r.map(a=>new vt(d({},a),o(this,pe),o(this,ve),o(this,Se),o(this,ke)))}update(e){return l(this,null,function*(){return hs({emitter:o(this,pe),apiService:o(this,ve),cache:o(this,Se),useCache:o(this,ke),args:y(d({},e),{subscription:this})})})}updatePreference(e){return l(this,null,function*(){return o(this,rt)?{error:new w("Cannot update a deleted subscription",new Error("Subscription is stale"))}:ls({emitter:o(this,pe),apiService:o(this,ve),cache:o(this,Se),useCache:o(this,ke),args:y(d({},e),{subscriptionId:this.identifier})})})}bulkUpdatePreferences(e){return l(this,null,function*(){return o(this,rt)?{error:new w("Cannot bulk update a deleted subscription",new Error("Subscription is stale"))}:co({emitter:o(this,pe),apiService:o(this,ve),cache:o(this,Se),useCache:o(this,ke),args:e.map(t=>y(d({},t),{subscriptionId:this.identifier}))})})}delete(){return l(this,null,function*(){return o(this,rt)?{error:new w("Cannot delete an already deleted subscription",new Error("Subscription is stale"))}:us({emitter:o(this,pe),apiService:o(this,ve),args:{subscription:this}})})}};pe=new WeakMap;ve=new WeakMap;Se=new WeakMap;ke=new WeakMap;rt=new WeakMap;var ro=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,options:s,args:r}){try{const{useCache:a,refetch:c}=s;let h=a&&!c?i.getAll(r):void 0;return t.emit("subscriptions.list.pending",{args:r,data:h}
22),(!h||c)&&(h=(yield n.fetchSubscriptions(r.topicKey)).map(f=>new bt(y(d({},f),{topicKey:r.topicKey}),t,n,i,a)),a&&(i.set(r,h),h=i.getAll(r))),t.emit("subscriptions.list.resolved",{args:r,data:h}),{data:h}}catch(a){return t.emit("subscriptions.list.resolved",{args:r,error:a}),{error:new w("Failed to fetch subscriptions",a)}}}),oo=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,options:s,args:r}){try{const{useCache:a,refetch:c}=s;let h=a&&!c?i.get(r):void 0;if(t.emit("subscription.get.pending",{args:r,data:h}),!h||c){const u=yield n.getSubscription(r.topicKey,r.identifier,r.workflowIds,r.tags);if(!u)return t.emit("subscription.get.resolved",{args:r,data:null}),{data:null};h=new bt(y(d({},u),{topicKey:r.topicKey}),t,n,i,a),a&&(i.setOne(r,h),h=i.get(r))}return t.emit("subscription.get.resolved",{args:r,data:h}),{data:h}}catch(a){return t.emit("subscription.get.resolved",{args:r,error:a}),{error:new w("Failed to fetch subscription",a)}}}),ao=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,useCache:s,args:r}){var a;try{t.emit("subscription.create.pending",{args:r});const c=yield n.createSubscription({identifier:(a=r.identifier)!=null?a:"",name:r.name,topicKey:r.topicKey,topicName:r.topicName,preferences:r.preferences}),h=new bt(y(d({},c),{topicKey:r.topicKey}),t,n,i,s);return t.emit("subscription.create.resolved",{args:r,data:h}),{data:h}}catch(c){return t.emit("subscription.create.resolved",{args:r,error:c}),{error:new w("Failed to create subscription",c)}}}),hs=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,useCache:s,args:r}){const a="identifier"in r?r.identifier:r.subscription.identifier,c="topicKey"in r?r.topicKey:r.subscription.topicKey;try{t.emit("subscription.update.pending",{args:r});const h=yield n.updateSubscription({topicKey:c,identifier:a,name:r.name,preferences:r.preferences}),u=new bt(y(d({},h),{topicKey:c}),t,n,i,s);return t.emit("subscription.update.resolved",{args:r,data:u}),{data:u}}catch(h){return t.emit("subscription.update.resolved",{args:r,error:h}),{error:new w("Failed to update subscription",h)}}}),ls=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,useCache:s,args:r}){var a,c;const h="workflowId"in r?r.workflowId:(c=(a=r.preference)==null?void 0:a.workflow)==null?void 0:c.id;try{t.emit("subscription.preference.update.pending",{args:r,data:"preference"in r?new vt(d(d({},r.preference),typeof r.value=="boolean"?{enabled:r.value}:{condition:r.value}),t,n,i,s):void 0});const u=yield n.updateSubscriptionPreference(d({subscriptionIdentifier:r.subscriptionId,workflowId:h},typeof r.value=="boolean"?{enabled:r.value,email:r.value,sms:r.value,in_app:r.value,chat:r.value,push:r.value}:{condition:r.value})),f=new vt(d({},u),t,n,i,s);return t.emit("subscription.preference.update.resolved",{args:r,data:f}),{data:f}}catch(u){return t.emit("subscription.preference.update.resolved",{args:r,error:u}),{error:new w("Failed to update subscription",u)}}}),co=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,useCache:s,args:r}){try{const a=r.map(f=>"preference"in f?new vt(d(d({},f.preference),typeof f.value=="boolean"?{enabled:f.value}:{condition:f.value}),t,n,i,s):void 0).filter(f=>f!==void 0);t.emit("subscription.preferences.bulk_update.pending",{args:r,data:a});const c=r.map(f=>{var g,m,_,U,N,A;return d({subscriptionIdentifier:f.subscriptionId,workflowId:"workflowId"in f?f.workflowId:(A=(N=(m=(g=f.preference)==null?void 0:g.workflow)==null?void 0:m.id)!=null?N:(U=(_=f.preference)==null?void 0:_.workflow)==null?void 0:U.identifier)!=null?A:""},typeof f.value=="boolean"?{enabled:f.value,email:f.value,sms:f.value,in_app:f.value,chat:f.value,push:f.value}:{condition:f.value})}),u=(yield n.bulkUpdateSubscriptionPreferences(c)).map(f=>new vt(f,t,n,i,s));return t.emit("subscription.preferences.bulk_update.resolved",{args:r,data:u}),{data:u}}catch(a){return t.emit("subscription.preferences.bulk_update.resolved",{args:r,error:a}),{error:new w("Failed to bulk update subscription preferences",a)}}}),us=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){const s="identifier"in i?i.identifier:i.subscription.identifier,r="topicKey"in i?i.topicKey:i.subscription.topicKey;try{return t.emit("subscription.delete.pending",{args:i}),yield n.deleteSubscription({topicKey:r,identifier:s}),t.emit("subscription.delete.resolved",{args:i}),{data:void 0}}catch(a){return t.emit("subscription.delete.resolved",{args:i,error:a}),{error:new w("Failed to delete subscription",a)}}}),Rt,Pt,Ut,Lt,vt=class{constructor(e,t,n,i,s){p(this,Rt),p(this,Pt),p(this,Ut),p(this,Lt);var r;v(this,Rt,t),v(this,Pt,n),v(this,Ut,i),v(this,Lt,s),this.enabled=e.enabled,this.condition=(r=e.condition)!=null?r:void 0,this.workflow=e.workflow,this.subscriptionId=e.subscriptionId}update(e){return l(this,null,function*(){var t;return ls({emitter:o(this,Rt),apiService:o(this,Pt),cache:o(this,Ut),useCache:o(this,Lt),args:{subscriptionId:this.subscriptionId,workflowId:(t=this.workflow)==null?void 0:t.id,value:e.value,preference:this}})})}};Rt=new WeakMap;Pt=new WeakMap;Ut=new WeakMap;Lt=new WeakMap;var Ee,ot,he=class{constructor({inboxServiceInstance:e,eventEmitterInstance:t}){p(this,Ee,[]),p(this,ot),this._emitter=t,this._inboxService=e,this._emitter.on("session.initialize.resolved",({error:n,data:i})=>{i?(this.onSessionSuccess(i),o(this,Ee).forEach(s=>l(this,[s],function*({fn:r,resolve:a}){a(yield r())})),v(this,Ee,[])):n&&(this.onSessionError(n),v(this,ot,n),o(this,Ee).forEach(({resolve:s})=>{s({error:new w("Failed to initialize session, please contact the support",n)})}),v(this,Ee,[]))})}onSessionSuccess(e){}onSessionError(e){}callWithSession(e){return l(this,null,function*(){return this._inboxService.isSessionInitialized?e():o(this,ot)?Promise.resolve({error:new w("Failed to initialize session, please contact the support",o(this,ot))}):new Promise((t,n)=>{o(this,Ee).push({fn:e,resolve:t,reject:n})})})}};Ee=new WeakMap;ot=new WeakMap;var Z,yt=class{constructor(){p(this,Z),v(this,Z,new Map)}get(e){return o(this,Z).get(e)}getValues(){return Array.from(o(this,Z).values())}entries(){return Array.from(o(this,Z).entries())}keys(){return Array.from(o(this,Z).keys())}set(e,t){o(this,Z).set(e,t)}remove(e){o(this,Z).delete(e)}clear(){o(this,Z).clear()}};Z=new WeakMap;var be=e=>`list:${e.topicKey}`,_i=e=>e.split(":")[1],le=e=>`item:${e.topicKey}:${e.identifier}`,D,C,Mt,O,Wt,ho=class{constructor({emitterInstance:e,inboxServiceInstance:t,useCache:n}){p(this,D),p(this,C),p(this,Mt),p(this,O),p(this,Wt),this.handleCreate=i=>{const s=be({topicKey:i.topicKey}),r=o(this,C).get(s);if(r){const a=[...r,i];o(this,C).set(s,a),o(this,D).emit("subscriptions.list.updated",{data:{topicKey:i.topicKey,subscriptions:a}})}o(this,O).set(le({topicKey:i.topicKey,identifier:i.identifier}),i)},this.handleUpdate=i=>{const s=be({topicKey:i.topicKey}),r=o(this,C).get(s);if(r){const a=r.map(c=>c.id===i.id?i:c);o(this,C).set(s,a),o(this,D).emit("subscriptions.list.updated",{data:{topicKey:i.topicKey,subscriptions:a}})}o(this,O).set(le({topicKey:i.topicKey,identifier:i.identifier}),i)},this.handlePreferenceUpdate=i=>{this.updateSubscriptionPreferences([i])},this.handleBulkPreferenceUpdate=i=>{this.updateSubscriptionPreferences(i)},this.updateSubscriptionPreferences=i=>{var s;const r=new Map;for(const h of i){const u=(s=r.get(h.subscriptionId))!=null?s:[];u.push(h),r.set(h.subscriptionId,u)}const a=o(this,C).keys();for(const h of a){const u=o(this,C).get(h);if(!u)continue;let f=!1;const g=u.map(m=>{const _=r.get(m.identifier);return _?(f=!0,this.createUpdatedSubscription(m,_)):m});f&&(o(this,C).set(h,g),o(this,D).emit("subscriptions.list.updated",{data:{topicKey:_i(h),subscriptions:g}}))}const c=o(this,O).keys();
22for(const h of c){const u=o(this,O).get(h);if(!u)continue;const f=r.get(u.identifier);if(f){const g=this.createUpdatedSubscription(u,f);o(this,O).set(h,g),o(this,D).emit("subscription.update.resolved",{args:{subscription:u},data:g})}}},this.createUpdatedSubscription=(i,s)=>{var r;const a=(r=i.preferences)==null?void 0:r.map(c=>{const h=s.find(u=>u.workflow.id===c.workflow.id);return h||c});return new bt({id:i.id,identifier:i.identifier,topicKey:i.topicKey,preferences:a},o(this,D),o(this,Wt),this,o(this,Mt))},this.handleDelete=i=>{const s=be({topicKey:i.topicKey}),r=o(this,C).get(s);if(r){const a=r.filter(c=>c.id!==i.id);o(this,C).set(s,a),o(this,D).emit("subscriptions.list.updated",{data:{topicKey:i.topicKey,subscriptions:a}})}o(this,O).remove(le({topicKey:i.topicKey,identifier:i.identifier}))},this.handleDeleteByIdentifier=i=>{const s=o(this,C).keys();for(const a of s){const c=o(this,C).get(a);if(c){const h=c.find(u=>u.identifier===i);if(h){const u=c.filter(f=>f.identifier!==i);o(this,C).set(a,u),o(this,D).emit("subscriptions.list.updated",{data:{topicKey:_i(a),subscriptions:u}}),o(this,O).remove(le({topicKey:h.topicKey,identifier:h.identifier}));return}}}const r=o(this,O).keys();for(const a of r){const c=o(this,O).get(a);if(c&&c.identifier===i){o(this,O).remove(a);return}}},v(this,D,e),v(this,C,new yt),v(this,O,new yt),v(this,Wt,t),v(this,Mt,n),o(this,D).on("subscription.create.resolved",({data:i})=>{i&&this.handleCreate(i)}),o(this,D).on("subscription.update.resolved",({data:i})=>{i&&this.handleUpdate(i)}),o(this,D).on("subscription.delete.resolved",({args:i})=>{"subscription"in i?this.handleDelete(i.subscription):"identifier"in i&&this.handleDeleteByIdentifier(i.identifier)}),o(this,D).on("subscription.preference.update.pending",({data:i})=>{i&&this.handlePreferenceUpdate(i)}),o(this,D).on("subscription.preference.update.resolved",({data:i})=>{i&&this.handlePreferenceUpdate(i)}),o(this,D).on("subscription.preferences.bulk_update.resolved",({data:i})=>{i&&i.length>0&&this.handleBulkPreferenceUpdate(i)})}has(e){return o(this,C).get(be(e))!==void 0}set(e,t){o(this,C).set(be(e),t);for(const n of t)o(this,O).set(le({topicKey:e.topicKey,identifier:n.identifier}),n)}setOne(e,t){o(this,O).set(le(e),t)}getAll(e){return o(this,C).get(be(e))}get(e){return o(this,O).get(le(e))}invalidate(e){const t=be({topicKey:e.topicKey}),n=o(this,C).get(t);if(n)for(const s of n)o(this,O).remove(le({topicKey:e.topicKey,identifier:s.identifier}));o(this,C).remove(t);const i=o(this,O).keys();for(const s of i)s.startsWith(`item:${e.topicKey}:`)&&o(this,O).remove(s)}clearAll(){o(this,C).clear(),o(this,O).clear()}};D=new WeakMap;C=new WeakMap;Mt=new WeakMap;O=new WeakMap;Wt=new WeakMap;var Ae,Ft,$t,lo=class extends he{constructor({useCache:e,inboxServiceInstance:t,eventEmitterInstance:n,subscriber:i,contextKey:s}){super({eventEmitterInstance:n,inboxServiceInstance:t}),p(this,Ae),p(this,Ft),p(this,$t),this.cache=new ho({emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,useCache:e}),v(this,Ae,e),v(this,Ft,i),v(this,$t,s)}list(e,t){return l(this,null,function*(){return this.callWithSession(()=>{var n;return ro({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:y(d({},t),{useCache:(n=t==null?void 0:t.useCache)!=null?n:o(this,Ae)}),args:e})})})}get(e,t){return l(this,null,function*(){return this.callWithSession(()=>{var n,i;return oo({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:y(d({},t),{useCache:(n=t==null?void 0:t.useCache)!=null?n:o(this,Ae)}),args:y(d({},e),{identifier:(i=e.identifier)!=null?i:Ms({topicKey:e.topicKey,subscriberId:o(this,Ft).subscriberId,contextKey:o(this,$t)})})})})})}create(e){return l(this,null,function*(){return this.callWithSession(()=>ao({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:o(this,Ae),args:e}))})}update(e){return l(this,null,function*(){return this.callWithSession(()=>hs({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:o(this,Ae),args:e}))})}delete(e){return l(this,null,function*(){return this.callWithSession(()=>us({emitter:this._emitter,apiService:this._inboxService,args:e}))})}};Ae=new WeakMap;Ft=new WeakMap;$t=new WeakMap;function Nn(){return{messages:[],isRunning:!1,status:"active",lastSequence:0}}function uo(e=Nn(),t){return t.reduce((n,i)=>fo(n,i),e)}function fo(e,t){const n=y(d({},e),{lastSequence:Math.max(e.lastSequence,t.sequence)});return po(n,t)}function po(e,t){const{event:n}=t;switch(n.type){case"run-start":return y(d({},e),{isRunning:!0});case"run-finish":return mi(y(d({},e),{isRunning:!1,activeAssistantMessageId:void 0}));case"run-error":return mi(y(d({},e),{isRunning:!1,activeAssistantMessageId:void 0,error:{message:n.message,code:n.code}}));case"resolve":return y(d({},e),{status:"resolved"});case"message-start":return It(e,t,n.messageId,i=>y(d({},i),{parts:[...i.parts,ds("")]}));case"message-delta":return It(e,t,n.messageId,i=>y(d({},i),{parts:mo(i.parts,n.delta)}));case"message-end":return It(e,t,n.messageId,i=>y(d({},i),{parts:go(i.parts,n.content,n.files)}));case"message":return Gn(e,t,n.messageId,n.role,i=>y(d({},i),{parts:Jn(i.parts,n.content,n.files),status:"sent"}));case"thinking-start":return ue(e,t,i=>y(d({},i),{parts:[...i.parts,yo(n.thinkingId)]}));case"thinking-delta":return ue(e,t,i=>y(d({},i),{parts:wo(i.parts,n.thinkingId,n.delta)}));case"thinking-end":return ue(e,t,i=>y(d({},i),{parts:bo(i.parts,n.thinkingId)}));case"tool-use-start":return ue(e,t,i=>y(d({},i),{parts:[...i.parts,_o(n.toolUseId,n.toolName,n.source)]}));case"tool-use-delta":return ue(e,t,i=>y(d({},i),{parts:ko(i.parts,n.toolUseId,n.delta)}));case"tool-use-done":return ue(e,t,i=>y(d({},i),{parts:Eo(i.parts,n.toolUseId,n.toolName,n.input,n.source)}));case"tool-use-result":return ue(e,t,i=>y(d({},i),{parts:Ao(i.parts,n.toolUseId,n.content,n.isError)}));case"tool-approval-request":return ue(e,t,i=>y(d({},i),{parts:[...i.parts,{type:"approval",approvalId:n.approvalId,toolUseId:n.toolUseId,toolName:n.toolName,input:n.input,source:n.source,state:"pending"}]}));case"tool-approval-response":return Io(e,n.approvalId,n.decision);case"source":return It(e,t,n.messageId,i=>y(d({},i),{parts:[...i.parts,{type:"source",sourceType:n.sourceType,url:n.url,title:n.title,filename:n.filename}]}));case"channel.edit":return Co(e,t.timestamp,n.messageId,n.content,n.files);case"channel.delete":return y(d({},e),{messages:e.messages.filter(i=>i.id!==n.messageId)});case"step-start":case"step-end":case"channel.typing":case"channel.reaction":case"connection.error":case"signal":case"custom"
22:return e;default:return e}}function Gn(e,t,n,i,s){const{messages:r,index:a}=vo(e,t,n,i),c=r[a];if(!c)return e;const h=r.slice();return h[a]=s(c),d(y(d({},e),{messages:h}),i==="assistant"?{activeAssistantMessageId:n}:{})}function It(e,t,n,i){return Gn(e,t,n,"assistant",i)}function ue(e,t,n){var i;const s=(i=e.activeAssistantMessageId)!=null?i:t.runId;return Gn(e,t,s,"assistant",n)}function vo(e,t,n,i){const s=e.messages.findIndex(a=>a.id===n&&a.role===i);if(s>=0)return{messages:e.messages,index:s};const r={id:n,role:i,parts:[],createdAt:t.timestamp,status:"sent"};return{messages:[...e.messages,r],index:e.messages.length}}function ds(e){return{type:"text",text:e,state:"streaming"}}function yo(e){return{type:"thinking",thinkingId:e,text:"",state:"streaming"}}function _o(e,t,n){return{type:"tool",toolUseId:e,toolName:t,source:n,state:"input-streaming"}}function jn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if((n==null?void 0:n.type)==="text"&&n.state==="streaming")return t}return-1}function mo(e,t){const n=jn(e);if(n<0)return[...e,ds(t)];const i=e.slice(),s=i[n];return i[n]=y(d({},s),{text:s.text+t}),i}function Jn(e,t,n){let i=e.slice();const s=jn(i);return"markdown"in t&&(s>=0?i[s]={type:"text",text:t.markdown,state:"done"}:i=[...i,{type:"text",text:t.markdown,state:"done"}]),"card"in t&&(i=[...i,{type:"card",card:t.card}]),fs(i,n)}function go(e,t,n){let i=e.slice();const s=jn(i);if(t)return i=Jn(i,t,n),i;if(s>=0){const r=i[s];i[s]=y(d({},r),{state:"done"})}return fs(i,n)}function fs(e,t){return t!=null&&t.length?[...e,...t.map(n=>({type:"file",fileId:n.fileId,name:n.name,mediaType:n.mediaType}))]:e}function ps(e,t){return e.findIndex(n=>n.type==="thinking"&&n.thinkingId===t)}function wo(e,t,n){const i=ps(e,t);if(i<0)return[...e,{type:"thinking",thinkingId:t,text:n,state:"streaming"}];const s=e.slice(),r=s[i];return s[i]=y(d({},r),{text:r.text+n}),s}function bo(e,t){const n=ps(e,t);if(n<0)return e;const i=e.slice(),s=i[n];return i[n]=y(d({},s),{state:"done"}),i}function Yn(e,t){return e.findIndex(n=>n.type==="tool"&&n.toolUseId===t)}function So(e){if(typeof e!="object"||e===null)return"";const t=e.__stream;return typeof t=="string"?t:JSON.stringify(e)}function ko(e,t,n){const i=Yn(e,t);if(i<0)return e;const s=e.slice(),r=s[i],c=`${So(r.input)}${n}`;let h;try{h=JSON.parse(c)}catch{h={__stream:c}}return s[i]=y(d({},r),{input:h}),s}function Eo(e,t,n,i,s){const r=Yn(e,t),a={type:"tool",toolUseId:t,toolName:n,source:s,input:i,state:"input-available"};if(r<0)return[...e,a];const c=e.slice(),h=c[r];return c[r]=d(d({},h),a),c}function Ao(e,t,n,i){const s=Yn(e,t);if(s<0)return e;const r=e.slice(),a=r[s];return r[s]=y(d({},a),{output:n,state:i?"output-error":"output-available"}),r}function Io(e,t,n){const i=n==="approved"?"approved":"denied";return y(d({},e),{messages:e.messages.map(s=>y(d({},s),{parts:s.parts.map(r=>r.type==="approval"&&r.approvalId===t?y(d({},r),{state:i}):r)}))})}function Co(e,t,n,i,s){const r=e.messages.findIndex(u=>u.id===n);if(r<0)return e;const a=e.messages[r];if(!a)return e;const c=y(d({},a),{createdAt:t,parts:Jn([],i,s)}),h=e.messages.slice();return h[r]=c,y(d({},e),{messages:h})}function mi(e){return y(d({},e),{messages:e.messages.map(t=>y(d({},t),{parts:t.parts.map(n=>n.type==="text"&&n.state==="streaming"?y(d({},n),{state:"done"}):n.type==="thinking"&&n.state==="streaming"?y(d({},n),{state:"done"}):n)}))})}function To(e,t){var n;const i=(n=t.role)!=null?n:"user";return y(d({},e),{messages:[...e.messages,{id:t.id,role:i,parts:t.parts,createdAt:t.createdAt,status:t.status}]})}function vs(e){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return`${e}_${crypto.randomUUID().replace(/-/g,"").slice(0,12)}`;if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const t=new Uint8Array(6);return crypto.getRandomValues(t),`${e}_${Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}`}return`${e}_${Date.now().toString(36)}`}function ys(){return vs("local")}function Oo(){return vs("opt")}function gi(e,t){e.messages=t.messages,e.isRunning=t.isRunning,e.status=t.status,e.lastSequence=t.lastSequence,e.error=t.error,e.activeAssistantMessageId=t.activeAssistantMessageId}var Ie,Ce,xo=class{constructor(e){p(this,Ie,new Map),p(this,Ce),v(this,Ce,e)}clear(){o(this,Ie).clear()}get(e){return o(this,Ie).get(e)}getByConversationId(e,t){for(const n of o(this,Ie).values())if(n.agentId===e&&n.conversationId===t)return n}getOrCreate(e){const t=o(this,Ie).get(e.key);if(t)return t;const n=y(d({},Nn()),{agentId:e.agentId,conversationId:e.conversationId,key:e.key});return o(this,Ie).set(e.key,n),n}appendSending(e,t){const n=Oo();return gi(e,To(e,{id:n,createdAt:new Date().toISOString(),status:"sending",parts:[{type:"text",text:t,state:"done"}]})),o(this,Ce).call(this,e),n}markSent(e,t){return e.messages=e.messages.map(n=>n.id===t.optimisticMessageId?y(d({},n),{id:t.serverMessageId,status:"sent"}):n),e.conversationId||(e.conversationId=t.conversationId),o(this,Ce).call(this,e),e}markFailed(e,t){return e.messages=e.messages.map(n=>n.id===t?y(d({},n),{status:"failed"}):n),o(this,Ce).call(this,e),e}absorbHistoryPage(e,t){const n=uo(Nn(),t),i=new Set(n.messages.map(r=>r.id)),s=e.messages.filter(r=>!i.has(r.id));return gi(e,y(d({},n),{messages:[...n.messages,...s]})),o(this,Ce).call(this,e),e}withCreateClaim(e,t,n){var i;const s=t??e.conversationId;if(s)return n(s);const r=()=>l(null,null,function*(){return e.conversationId?n(e.conversationId):n(void 0)}),c=((i=e.pendingCreate)!=null?i:Promise.resolve()).then(r,r);return e.pendingCreate=c.then(()=>{},()=>{}),c}};Ie=new WeakMap;Ce=new WeakMap;var at,$,on,_s,ms,No=class extends he{constructor({inboxServiceInstance:e,eventEmitterInstance:t,agentChatService:n}){super({inboxServiceInstance:e,eventEmitterInstance:t}),p(this,on),p(this,at),p(this,$),v(this,at,n),v(this,$,new xo(i=>{this._emitter.emit("agent_chat.messages.updated",{data:{agentId:i.agentId,conversationId:i.conversationId,key:i.key,messages:i.messages}})}))}
22clearCache(){o(this,$).clear()}getConversation({agentId:e,conversationId:t,key:n}){var i;const s=n?o(this,$).get(n):t?(i=o(this,$).get(t))!=null?i:o(this,$).getByConversationId(e,t):void 0;if(!(!s||s.agentId!==e))return{conversationId:s.conversationId,messages:s.messages,key:s.key}}loadConversation(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){try{const t=yield o(this,at).getEvents({conversationId:e.conversationId}),n=o(this,$).getOrCreate({agentId:e.agentId,key:e.conversationId,conversationId:e.conversationId}),i=o(this,$).absorbHistoryPage(n,t.events);return{data:{conversationId:e.conversationId,messages:i.messages}}}catch(t){return{error:new w("Failed to load agent chat conversation",t)}}}))})}sendMessage(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){var t,n;const i=(n=(t=e.key)!=null?t:e.conversationId)!=null?n:ys(),s=S(this,on,_s).call(this,e,i),r=o(this,$).appendSending(s,e.text);return o(this,$).withCreateClaim(s,e.conversationId,a=>l(this,null,function*(){try{const c=yield o(this,at).sendMessage({agentId:e.agentId,text:e.text,conversationId:a});return o(this,$).markSent(s,{optimisticMessageId:r,serverMessageId:c.messageId,conversationId:c.identifier}),{data:{conversationId:c.identifier,messageId:c.messageId}}}catch(c){return o(this,$).markFailed(s,r),{error:new w("Failed to send agent chat message",c)}}}))}))})}};at=new WeakMap;$=new WeakMap;on=new WeakSet;_s=function(e,t){var n;const i=o(this,$).get(t);if(i&&S(this,on,ms).call(this,i,e))return i;if(e.conversationId)return(n=o(this,$).getByConversationId(e.agentId,e.conversationId))!=null?n:o(this,$).getOrCreate({agentId:e.agentId,key:e.conversationId,conversationId:e.conversationId});const s=i?ys():t;return o(this,$).getOrCreate({agentId:e.agentId,key:s})};ms=function(e,t){return!(e.agentId!==t.agentId||t.conversationId!==void 0&&e.conversationId!==void 0&&e.conversationId!==t.conversationId)};var wi="/web-chat/conversations",ct,Ro=class{constructor({httpClient:e}){p(this,ct),v(this,ct,e)}sendMessage(e){return l(this,null,function*(){return o(this,ct).post(wi,d({agentId:e.agentId,text:e.text},e.conversationId?{conversationIdentifier:e.conversationId}:{}))})}getEvents(e){return l(this,null,function*(){return o(this,ct).get(`${wi}/${encodeURIComponent(e.conversationId)}/events`)})}};ct=new WeakMap;var Po="v1",Uo="@novu/[email protected]",gs=class{constructor(e={}){this.DEFAULT_BACKEND_URL=typeof window<"u"&&window.NOVU_LOCAL_BACKEND_URL||"https://api.novu.co";const{apiVersion:t=Po,apiUrl:n=this.DEFAULT_BACKEND_URL,headers:i={}}=e||{};this.apiVersion=t,this.apiUrl=`${n}/${t}`,this.headers=d({"Novu-API-Version":"2024-06-26","Novu-Client-Version":Uo,"Content-Type":"application/json"},i)}setAuthorizationToken(e){this.headers.Authorization=`Bearer ${e}`}setKeylessHeader(e){var t;const n=e||typeof window<"u"&&((t=window.localStorage)==null?void 0:t.getItem("novu_keyless_application_identifier"));!n||!n.startsWith("pk_keyless_")||(this.headers["Novu-Application-Identifier"]=n)}setHeaders(e){this.headers=d(d({},this.headers),e)}get(e,t,n=!0){return l(this,null,function*(){return this.doFetch({path:e,searchParams:t,options:{method:"GET"},unwrapEnvelope:n})})}post(e,t,n){return l(this,null,function*(){return this.doFetch({path:e,options:{method:"POST",body:t,headers:n==null?void 0:n.headers}})})}patch(e,t){return l(this,null,function*(){return this.doFetch({path:e,options:{method:"PATCH",body:t}})})}delete(e,t){return l(this,null,function*(){return this.doFetch({path:e,options:{method:"DELETE",body:t}})})}doFetch(e){return l(this,arguments,function*({path:t,searchParams:n,options:i,unwrapEnvelope:s=!0}){const r=Lo(this.apiUrl,t,n?`?${n.toString()}`:""),a={method:(i==null?void 0:i.method)||"GET",headers:d(d({},this.headers),(i==null?void 0:i.headers)||{}),body:i!=null&&i.body?JSON.stringify(i.body):void 0},c=yield fetch(r,a);if(!c.ok){const u=yield c.json();throw new Error(`${this.headers["Novu-Client-Version"]} error. Status: ${c.status}, Message: ${u.message}`)}if(c.status===204)return;const h=yield c.json();return s?h.data:h})}};function Lo(...e){return e.reduce((t,n)=>(n&&t.push(n.replace(new RegExp("(?<!https?:)\\/+","g"),"/").replace(/^\/+|\/+$/g,"")),t),[]).join("/").replace(/\/\?/,"?")}var F="/inbox",B=`${F}/notifications`,Mo=`${F}/chat/oauth`,ht=`${F}/channel-connections`,Wo=`${ht}/oauth`,Me=`${F}/channel-endpoints`,Fo=`${Me}/oauth`;function bi(e){const t=new URLSearchParams;if(e.subscriberId&&t.append("subscriberId",e.subscriberId),e.integrationIdentifier&&t.append("integrationIdentifier",e.integrationIdentifier),e.connectionIdentifier&&t.append("connectionIdentifier",e.connectionIdentifier),e.channel&&t.append("channel",e.channel),e.providerId&&t.append("providerId",e.providerId),e.connectionMode&&t.append("connectionMode",e.connectionMode),e.contextKeys!==void 0)if(e.contextKeys.length===0)t.append("contextKeys","");else for(const n of e.contextKeys)t.append("contextKeys",n);return e.limit&&t.append("limit",String(e.limit)),e.after&&t.append("after",e.after),e.before&&t.append("before",e.before),t.size?`?${t.toString()}`:""}function $o(e,t){if(t!==void 0){if(Array.isArray(t)){if(t.length===0)return;for(const n of t)e.append("tags[]",n);return}if("or"in t){if(t.or.length===0)return;for(const n of t.or)e.append("tags[]",n);return}if("and"in t){if(t.and.length===0)return;
22t.and.forEach((n,i)=>{for(const s of n.or)e.append(`tags[${i}][]`,s)})}}}var b,Bo=class{constructor(e={}){this.isSessionInitialized=!1,p(this,b);const t=e,{httpClient:n}=t,i=Bn(t,["httpClient"]);v(this,b,n??new gs(i))}initializeSession(e){return l(this,arguments,function*({applicationIdentifier:t,subscriberHash:n,contextHash:i,subscriber:s,defaultSchedule:r,context:a}){const c=yield o(this,b).post(`${F}/session`,{applicationIdentifier:t,subscriberHash:n,contextHash:i,subscriber:s,defaultSchedule:r,context:a});return o(this,b).setAuthorizationToken(c.token),o(this,b).setKeylessHeader(c.applicationIdentifier),this.isSessionInitialized=!0,c})}fetchNotifications({after:e,archived:t,limit:n=10,offset:i,read:s,tags:r,snoozed:a,seen:c,data:h,severity:u,createdGte:f,createdLte:g}){const m=new URLSearchParams(`limit=${n}`);if(e&&m.append("after",e),i&&m.append("offset",`${i}`),$o(m,r),s!==void 0&&m.append("read",`${s}`),t!==void 0&&m.append("archived",`${t}`),a!==void 0&&m.append("snoozed",`${a}`),c!==void 0&&m.append("seen",`${c}`),h!==void 0&&m.append("data",JSON.stringify(h)),u&&Array.isArray(u))for(const _ of u)m.append("severity[]",_);else u&&m.append("severity",u);return f&&m.append("createdGte",`${f}`),g&&m.append("createdLte",`${g}`),o(this,b).get(B,m,!1)}count({filters:e}){return o(this,b).get(`${B}/count`,new URLSearchParams({filters:JSON.stringify(e)}),!1)}read(e){return o(this,b).patch(`${B}/${e}/read`)}unread(e){return o(this,b).patch(`${B}/${e}/unread`)}archive(e){return o(this,b).patch(`${B}/${e}/archive`)}unarchive(e){return o(this,b).patch(`${B}/${e}/unarchive`)}snooze(e,t){return o(this,b).patch(`${B}/${e}/snooze`,{snoozeUntil:t})}unsnooze(e){return o(this,b).patch(`${B}/${e}/unsnooze`)}readAll({tags:e,data:t}){return o(this,b).post(`${B}/read`,{tags:e,data:t?JSON.stringify(t):void 0})}archiveAll({tags:e,data:t}){return o(this,b).post(`${B}/archive`,{tags:e,data:t?JSON.stringify(t):void 0})}archiveAllRead({tags:e,data:t}){return o(this,b).post(`${B}/read-archive`,{tags:e,data:t?JSON.stringify(t):void 0})}delete(e){return o(this,b).delete(`${B}/${e}/delete`)}deleteAll({tags:e,data:t}){return o(this,b).post(`${B}/delete`,{tags:e,data:t?JSON.stringify(t):void 0})}markAsSeen({notificationIds:e,tags:t,data:n}){return o(this,b).post(`${B}/seen`,{notificationIds:e,tags:t,data:n?JSON.stringify(n):void 0})}seen(e){return this.markAsSeen({notificationIds:[e]})}completeAction({actionType:e,notificationId:t}){return o(this,b).patch(`${B}/${t}/complete`,{actionType:e})}revertAction({actionType:e,notificationId:t}){return o(this,b).patch(`${B}/${t}/revert`,{actionType:e})}fetchPreferences({tags:e,severity:t,criticality:n}){const i=new URLSearchParams;if(e)for(const r of e)i.append("tags[]",r);if(t&&Array.isArray(t))for(const r of t)i.append("severity[]",r);else t&&i.append("severity",t);n&&i.append("criticality",n);const s=i.size?`?${i.toString()}`:"";return o(this,b).get(`${F}/preferences${s}`)}bulkUpdatePreferences(e){return o(this,b).patch(`${F}/preferences/bulk`,{preferences:e})}updateGlobalPreferences(e){return o(this,b).patch(`${F}/preferences`,e)}updateWorkflowPreferences({workflowId:e,channels:t}){return o(this,b).patch(`${F}/preferences/${e}`,t)}fetchGlobalPreferences(){return o(this,b).get(`${F}/preferences/global`)}triggerHelloWorldEvent(){const e={name:"hello-world",to:{subscriberId:"keyless-subscriber-id"},payload:{subject:"Novu Keyless Environment",body:"You're using a keyless demo environment. For full access to Novu features and cloud integration, obtain your API key.",primaryActionText:"Obtain API Key",primaryActionUrl:"https://go.novu.co/keyless",secondaryActionText:"Explore Documentation",secondaryActionUrl:"https://go.novu.co/keyless-docs"}};return o(this,b).post("/inbox/events",e)}fetchSubscriptions(e){return o(this,b).get(`${F}/topics/${e}/subscriptions`)}getSubscription(e,t,n,i){const s=new URLSearchParams;if(n!=null&&n.length)for(const a of n)s.append("workflowIds",a);if(i!=null&&i.length)for(const a of i)s.append("tags",a);const r=s.size?`?${s.toString()}`:"";return o(this,b).get(`${F}/topics/${e}/subscriptions/${t}${r}`)}createSubscription({identifier:e,name:t,topicKey:n,topicName:i,preferences:s}){return o(this,b).post(`${F}/topics/${n}/subscriptions`,d(d({identifier:e,name:t},i&&{topic:{name:i}}),s!==void 0&&{preferences:s}))}updateSubscription({topicKey:e,identifier:t,name:n,preferences:i}){return o(this,b).patch(`${F}/topics/${e}/subscriptions/${t}
22`,d({name:n},i!==void 0&&{preferences:i}))}updateSubscriptionPreference({subscriptionIdentifier:e,workflowId:t,enabled:n,condition:i,email:s,sms:r,in_app:a,chat:c,push:h}){return o(this,b).patch(`${F}/subscriptions/${e}/preferences/${t}`,{enabled:n,condition:i,email:s,sms:r,in_app:a,chat:c,push:h})}bulkUpdateSubscriptionPreferences(e){return o(this,b).patch(`${F}/preferences/bulk`,{preferences:e})}deleteSubscription({topicKey:e,identifier:t}){return o(this,b).delete(`${F}/topics/${e}/subscriptions/${t}`)}generateChatOAuthUrl({integrationIdentifier:e,connectionIdentifier:t,subscriberId:n,context:i,scope:s,userScope:r,mode:a,connectionMode:c,autoLinkUser:h}){return o(this,b).post(Mo,{integrationIdentifier:e,connectionIdentifier:t,subscriberId:n,context:i,scope:s,userScope:r,mode:a,connectionMode:c,autoLinkUser:h})}generateConnectOAuthUrl({integrationIdentifier:e,connectionIdentifier:t,subscriberId:n,context:i,contextHash:s,scope:r,connectionMode:a,autoLinkUser:c}){return o(this,b).post(Wo,{integrationIdentifier:e,connectionIdentifier:t,subscriberId:n,context:i,contextHash:s,scope:r,connectionMode:a,autoLinkUser:c})}generateLinkUserOAuthUrl({integrationIdentifier:e,connectionIdentifier:t,subscriberId:n,context:i,contextHash:s,userScope:r}){return o(this,b).post(Fo,{integrationIdentifier:e,connectionIdentifier:t,subscriberId:n,context:i,contextHash:s,userScope:r})}listChannelConnections(e={}){const t=bi(e);return o(this,b).get(`${ht}${t}`,void 0,!1)}getChannelConnection({identifier:e,connectionMode:t}){const n=new URLSearchParams;return t&&n.append("connectionMode",t),o(this,b).get(`${ht}/${e}`,n,!1)}createChannelConnection({identifier:e,integrationIdentifier:t,subscriberId:n,context:i,workspace:s,auth:r}){return o(this,b).post(ht,{identifier:e,integrationIdentifier:t,subscriberId:n,context:i,workspace:s,auth:r})}deleteChannelConnection(e){return o(this,b).delete(`${ht}/${e}`)}listChannelEndpoints(e={}){const t=bi(e);return o(this,b).get(`${Me}${t}`,void 0,!1)}getChannelEndpoint(e){return o(this,b).get(`${Me}/${e}`)}createChannelEndpoint({identifier:e,integrationIdentifier:t,connectionIdentifier:n,subscriberId:i,context:s,type:r,endpoint:a}){return o(this,b).post(Me,{identifier:e,integrationIdentifier:t,connectionIdentifier:n,subscriberId:i,context:s,type:r,endpoint:a})}deleteChannelEndpoint(e){return o(this,b).delete(`${Me}/${e}`)}linkChannelEndpoint({integrationIdentifier:e,context:t,contextHash:n}){return o(this,b).post(`${Me}/link`,{integrationIdentifier:e,context:t,contextHash:n})}};b=new WeakMap;var Do=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-connection.oauth-url.pending",{args:i});const s=yield n.generateChatOAuthUrl(i);return t.emit("channel-connection.oauth-url.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-connection.oauth-url.resolved",{args:i,error:s}),{error:new w("Failed to generate chat OAuth URL",s)}}}),Ko=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-connection.oauth-url.pending",{args:i});const s=yield n.generateConnectOAuthUrl(i);return t.emit("channel-connection.oauth-url.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-connection.oauth-url.resolved",{args:i,error:s}),{error:new w("Failed to generate connect OAuth URL",s)}}}),qo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-connections.list.pending",{args:i});const r=(yield n.listChannelConnections(i)).data;return t.emit("channel-connections.list.resolved",{args:i,data:r}),{data:r}}catch(s){return t.emit("channel-connections.list.resolved",{args:i,error:s}),{error:new w("Failed to list channel connections",s)}}}),zo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-connection.get.pending",{args:i});const s=yield n.getChannelConnection(i);return t.emit("channel-connection.get.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-connection.get.resolved",{args:i,error:s}),{error:new w("Failed to get channel connection",s)}}}),Vo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{return t.emit("channel-connection.delete.pending",{args:i}),yield n.deleteChannelConnection(i.identifier),t.emit("channel-connection.delete.resolved",{args:i}),{data:void 0}}catch(s){return t.emit("channel-connection.delete.resolved",{args:i,error:s}),{error:new w("Failed to delete channel connection",s)}}}),Ho=class extends he{constructor({inboxServiceInstance:e,eventEmitterInstance:t}){super({inboxServiceInstance:e,eventEmitterInstance:t})}generateOAuthUrl(e){return l(this,null,function*(){return this.callWithSession(()=>Do({emitter:this._emitter,apiService:this._inboxService,args:e}))})}generateConnectOAuthUrl(e){return l(this,null,function*(){return this.callWithSession(()=>Ko({emitter:this._emitter,apiService:this._inboxService,args:e}))})}list(){return l(this,arguments,function*(e={}){return this.callWithSession(()=>qo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}get(e){return l(this,null,function*(){return this.callWithSession(()=>zo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}delete(e){return l(this,null,function*(){return this.callWithSession(()=>Vo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}},Go=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-endpoint.oauth-url.pending",{args:i});const s=yield n.generateLinkUserOAuthUrl(i);return t.emit("channel-endpoint.oauth-url.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-endpoint.oauth-url.resolved",{args:i,error:s}),{error:new w("Failed to generate link user OAuth URL",s)}}}),jo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-endpoints.list.pending",{args:i});const r=(yield n.listChannelEndpoints(i)).data;return t.emit("channel-endpoints.list.resolved",{args:i,data:r}),{data:r}}catch(s){return t.emit("channel-endpoints.list.resolved",{args:i,error:s}),{error:new w("Failed to list channel endpoints",s)}}}),Jo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-endpoint.get.pending",{args:i});const s=yield n.getChannelEndpoint(i.identifier);return t.emit("channel-endpoint.get.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-endpoint.get.resolved",{args:i,error:s}),{error:new w("Failed to get channel endpoint",s)}}}),Yo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-endpoint.create.pending",{args:i});const s=yield n.createChannelEndpoint(i);return t.emit("channel-endpoint.create.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-endpoint.create.resolved",{args:i,error:s}),{error:new w("Failed to create channel endpoint",s)}}}),Qo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{return t.emit("channel-endpoint.delete.pending",{args:i}),yield n.deleteChannelEndpoint(i.identifier),t.emit("channel-endpoint.delete.resolved",{args:i}),{data:void 0}}catch(s){return t.emit("channel-endpoint.delete.resolved",{args:i,error:s}),{error:new w("Failed to delete channel endpoint",s)}}}),Xo=e=>l(null,[e],function*({emitter:t,apiService:n,args:i}){try{t.emit("channel-endpoint.link.pending",{args:i});const s=yield n.linkChannelEndpoint(i);return t.emit("channel-endpoint.link.resolved",{args:i,data:s}),{data:s}}catch(s){return t.emit("channel-endpoint.link.resolved",{args:i,error:s}),{error:new w("Failed to link channel endpoint",s)}}}),Zo=class extends he{constructor({inboxServiceInstance:e,eventEmitterInstance:t}){super({inboxServiceInstance:e,eventEmitterInstance:t})}generateLinkUserOAuthUrl(e){return l(this,null,function*(){return this.callWithSession(()=>Go({emitter:this._emitter,apiService:this._inboxService,args:e}))})}list(){return l(this,arguments,function*(e={}){return this.callWithSession(()=>jo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}get(e){return l(this,null,function*(){return this.callWithSession(()=>Jo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}create(e){return l(this,null,function*(){return this.callWithSession(()=>Yo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}delete(e){return l(this,null,function*(){return this.callWithSession(()=>Qo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}link(e){return l(this,null,function*(){return this.callWithSession(()=>Xo({emitter:this._emitter,apiService:this._inboxService,args:e}))})}},We,ea=class{constructor(){p(this,We),v(this,We,js())}on(e,t){return o(this,We).on(e,t),()=>{this.off(e,t)}}off(e,t){o(this,We).off(e,t)}emit(e,t){o(this,We).emit(e,t)}};
22We=new WeakMap;var ws=({tags:e,data:t,read:n,archived:i,snoozed:s,seen:r,severity:a,limit:c,offset:h,after:u,createdGte:f,createdLte:g})=>Object.entries({tags:e,data:t,read:n,archived:i,snoozed:s,seen:r,severity:a,limit:c,offset:h,after:u,createdGte:f,createdLte:g}).filter(([m,_])=>_!=null&&!(Array.isArray(_)&&_.length===0)).reduce((m,[_,U])=>(m[_]=U,m),{}),it=({tags:e,data:t,read:n,archived:i,snoozed:s,seen:r,severity:a,limit:c,offset:h,after:u,createdGte:f,createdLte:g})=>JSON.stringify(ws({tags:e,data:t,read:n,archived:i,snoozed:s,seen:r,severity:a,limit:c,offset:h,after:u,createdGte:f,createdLte:g})),ta=({tags:e,data:t,read:n,archived:i,snoozed:s,seen:r,severity:a,createdGte:c,createdLte:h})=>JSON.stringify(ws({tags:e,data:t,read:n,archived:i,snoozed:s,seen:r,severity:a,createdGte:c,createdLte:h})),de=e=>JSON.parse(e),na=["notification.read.pending","notification.read.resolved","notification.unread.pending","notification.unread.resolved","notification.seen.pending","notification.seen.resolved","notification.complete_action.pending","notification.complete_action.resolved","notification.revert_action.pending","notification.revert_action.resolved","notifications.read_all.pending","notifications.read_all.resolved","notifications.seen_all.pending","notifications.seen_all.resolved"],ia=["notification.archive.pending","notification.unarchive.pending","notification.snooze.pending","notification.unsnooze.pending","notification.delete.pending","notifications.archive_all.pending","notifications.archive_all_read.pending","notifications.delete_all.pending"],ye,Bt,T,Te,Dt,sa=class{constructor({emitter:e,inboxService:t}){p(this,ye),p(this,Bt),p(this,T),p(this,Te,n=>qs({notification:n,emitter:o(this,ye),inboxService:o(this,Bt)})),p(this,Dt,n=>n.map(i=>o(this,Te).call(this,i))),this.syncNotificationInBucket=(n,i)=>{const s=o(this,Te).call(this,i),r=o(this,T).get(n);if(!r)return!1;const a=de(n),c=cs(s,a)&&as(s.tags,a.tags),h=r.notifications.findIndex(f=>f.id===s.id),u=h!==-1;if(c&&u){const f=[...r.notifications];return f[h]=s,o(this,T).set(n,y(d({},r),{notifications:f})),!0}return!c&&u?this.removeNotification(n,s):!1},this.removeNotification=(n,i)=>{const s=o(this,T).get(n);if(!s)return!1;const r=s.notifications.findIndex(c=>c.id===i.id);if(r===-1)return!1;const a=[...s.notifications];return a.splice(r,1),o(this,T).set(n,y(d({},s),{notifications:a})),!0},this.handleNotificationEvent=({remove:n}={remove:!1})=>i=>{const{data:s,args:r}=i;let a=[];if(s!=null)Array.isArray(s)&&s.every(h=>typeof h=="object"&&"id"in h)?a=o(this,Dt).call(this,s):typeof s=="object"&&"id"in s&&(a=[o(this,Te).call(this,s)]);else if(n&&r){if("notification"in r&&r.notification)a=[o(this,Te).call(this,r.notification)];else if("notificationId"in r&&r.notificationId){const h=[];o(this,T).keys().forEach(u=>{const f=o(this,T).get(u);if(f){const g=f.notifications.find(m=>m.id===r.notificationId);g&&h.push(g)}}),a=h}}if(a.length===0)return;const c=new Set;o(this,T).keys().forEach(h=>{a.forEach(u=>{let f=!1;n?f=this.removeNotification(h,u):f=this.syncNotificationInBucket(h,u),f&&c.add(ta(de(h)))})}),c.forEach(h=>{const u=this.getAggregated(de(h));o(this,ye).emit("notifications.list.updated",{data:u})})},v(this,ye,e),v(this,Bt,t),na.forEach(n=>{o(this,ye).on(n,this.handleNotificationEvent())}),ia.forEach(n=>{o(this,ye).on(n,this.handleNotificationEvent({remove:!0}))}),v(this,T,new yt)}getAggregated(e){const t=o(this,T).keys().filter(s=>{const r=de(s);return yi(r,e)}),n=new Map;let i=!1;for(const s of t){const r=o(this,T).get(s);if(r){i=r.hasMore;
22for(const a of r.notifications)n.set(a.id,a)}}return{hasMore:i,filter:e,notifications:Array.from(n.values())}}get(e){return o(this,T).get(it(e))}has(e){return o(this,T).get(it(e))!==void 0}set(e,t){o(this,T).set(it(e),y(d({},t),{notifications:o(this,Dt).call(this,t.notifications)}))}unshift(e,t){const n=it(e),i=o(this,T).get(n)||{hasMore:!1,filter:de(n),notifications:[]},s=o(this,Te).call(this,d({},t)),r=i.notifications.filter(a=>a.id!==t.id);this.update(e,y(d({},i),{notifications:[s,...r]}))}update(e,t){this.set(e,t);const n=this.getAggregated(de(it(e)));o(this,ye).emit("notifications.list.updated",{data:n})}getAll(e){if(this.has(e))return this.getAggregated({tags:e.tags,data:e.data,read:e.read,snoozed:e.snoozed,archived:e.archived,seen:e.seen,severity:e.severity,createdGte:e.createdGte,createdLte:e.createdLte})}getUniqueNotifications({tags:e,read:t,data:n}){const i=o(this,T).keys(),s=new Map;return i.forEach(r=>{const a=de(r);if(ss(e,a.tags)&&rs(n,a.data)){const c=o(this,T).get(r);if(!c)return;c.notifications.filter(h=>typeof t>"u"||t===h.isRead).forEach(h=>{s.set(h.id,h)})}}),Array.from(s.values())}clear(e){o(this,T).keys().forEach(n=>{yi(de(n),e)&&o(this,T).remove(n)})}clearAll(){o(this,T).clear()}};ye=new WeakMap;Bt=new WeakMap;T=new WeakMap;Te=new WeakMap;Dt=new WeakMap;var Kt,ra=class extends he{constructor({useCache:e,inboxServiceInstance:t,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:t}),p(this,Kt),this.cache=new sa({emitter:n,inboxService:t}),v(this,Kt,e)}list(){return l(this,arguments,function*(e={}){var t=e,{limit:n=10}=t,i=Bn(t,["limit"]);return this.callWithSession(()=>l(this,null,function*(){const s=d({limit:n},i);try{const r="useCache"in s?s.useCache:o(this,Kt);let a=r?this.cache.getAll(s):void 0;if(this._emitter.emit("notifications.list.pending",{args:s,data:a}),!a){const c=yield this._inboxService.fetchNotifications(d({limit:n},i));a={hasMore:c.hasMore,filter:c.filter,notifications:c.data.map(h=>new P(h,this._emitter,this._inboxService))},r&&(this.cache.set(s,a),a=this.cache.getAll(s))}return this._emitter.emit("notifications.list.resolved",{args:s,data:a}),{data:a}}catch(r){return this._emitter.emit("notifications.list.resolved",{args:s,error:r}),{error:new w("Failed to fetch notifications",r)}}}))})}count(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){const t=e&&"filters"in e?e.filters:[d({},e)];try{this._emitter.emit("notifications.count.pending",{args:e});const n=yield this._inboxService.count({filters:t}),i=e&&"filters"in e?{counts:n.data}:n.data[0];return this._emitter.emit("notifications.count.resolved",{args:e,data:i}),{data:i}}catch(n){return this._emitter.emit("notifications.count.resolved",{args:e,error:n}),{error:new w("Failed to count notifications",n)}}}))})}read(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Pi({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}unread(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Ui({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}seen(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Li({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}archive(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Mi({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}unarchive(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Wi({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}delete(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Bi({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}snooze(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Fi({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}unsnooze(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return $i({emitter:this._emitter,apiService:this._inboxService,args:e})}))})}completePrimary(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return nn({emitter:this._emitter,apiService:this._inboxService,args:e,actionType:"primary"})}))})}completeSecondary(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return nn({emitter:this._emitter,apiService:this._inboxService,args:e,actionType:"secondary"})}))})}revertPrimary(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return sn({emitter:this._emitter,apiService:this._inboxService,args:e,actionType:"primary"})}))})}revertSecondary(e){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return sn({emitter:this._emitter,apiService:this._inboxService,args:e,actionType:"secondary"})}))})}readAll(){return l(this,arguments,function*({tags:e,data:t}={}){return this.callWithSession(()=>l(this,null,function*(){return zs({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:e,data:t})}))})}
22seenAll(){return l(this,arguments,function*(e={}){return this.callWithSession(()=>l(this,null,function*(){return"notificationIds"in e?ri({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,notificationIds:e.notificationIds}):ri({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:"tags"in e?e.tags:void 0,data:"data"in e?e.data:void 0})}))})}archiveAll(){return l(this,arguments,function*({tags:e,data:t}={}){return this.callWithSession(()=>l(this,null,function*(){return Vs({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:e,data:t})}))})}archiveAllRead(){return l(this,arguments,function*({tags:e,data:t}={}){return this.callWithSession(()=>l(this,null,function*(){return Hs({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:e,data:t})}))})}deleteAll(){return l(this,arguments,function*({tags:e,data:t}={}){return this.callWithSession(()=>l(this,null,function*(){return Gs({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:e,data:t})}))})}clearCache({filter:e}={}){if(e){this.cache.clear(e??{});return}this.cache.clearAll()}triggerHelloWorldEvent(){return l(this,null,function*(){return this._inboxService.triggerHelloWorldEvent()})}};Kt=new WeakMap;var qt,zt,Vt,Ht,an=class{constructor(e,{emitterInstance:t,inboxServiceInstance:n,cache:i,useCache:s}){p(this,qt),p(this,zt),p(this,Vt),p(this,Ht),v(this,qt,t),v(this,zt,n),v(this,Vt,i),v(this,Ht,s),this.isEnabled=e.isEnabled,this.weeklySchedule=e.weeklySchedule}update(e){return l(this,null,function*(){var t;const n=!!e.weeklySchedule||!!this.weeklySchedule;return Ss({emitter:o(this,qt),apiService:o(this,zt),cache:o(this,Vt),useCache:o(this,Ht),args:d({isEnabled:(t=e.isEnabled)!=null?t:this.isEnabled},n&&{weeklySchedule:d(d({},this.weeklySchedule),e.weeklySchedule)})})})}};qt=new WeakMap;zt=new WeakMap;Vt=new WeakMap;Ht=new WeakMap;var Gt,jt,Jt,Yt,Qt,qe=class{constructor(e,{emitterInstance:t,inboxServiceInstance:n,cache:i,scheduleCache:s,useCache:r}){p(this,Gt),p(this,jt),p(this,Jt),p(this,Yt),p(this,Qt),v(this,Gt,t),v(this,jt,n),v(this,Jt,i),v(this,Yt,s),v(this,Qt,r),this.level=e.level,this.enabled=e.enabled,this.channels=e.channels,this.workflow=e.workflow,this.schedule=new an(d({},e.schedule),{emitterInstance:t,inboxServiceInstance:n,cache:s,useCache:r})}update({channels:e,channelPreferences:t}){var n;return bs({emitter:o(this,Gt),apiService:o(this,jt),cache:o(this,Jt),scheduleCache:o(this,Yt),useCache:o(this,Qt),args:{workflowId:(n=this.workflow)==null?void 0:n.id,channels:e||t,preference:this}})}};Gt=new WeakMap;jt=new WeakMap;Jt=new WeakMap;Yt=new WeakMap;Qt=new WeakMap;var bs=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,scheduleCache:s,useCache:r,args:a}){var c;const{channels:h}=a,u="workflowId"in a?a.workflowId:(c=a.preference.workflow)==null?void 0:c.id;try{t.emit("preference.update.pending",{args:a,data:"preference"in a?new qe(y(d({},a.preference),{channels:d(d({},a.preference.channels),h)}),{emitterInstance:t,inboxServiceInstance:n,cache:i,scheduleCache:s,useCache:r}):void 0});let f;u?f=yield n.updateWorkflowPreferences({workflowId:u,channels:h}):(aa({emitter:t,apiService:n,cache:i,scheduleCache:s,useCache:r,args:a}),f=yield n.updateGlobalPreferences(h));const g=new qe(f,{emitterInstance:t,inboxServiceInstance:n,cache:i,scheduleCache:s,useCache:r});return t.emit("preference.update.resolved",{args:a,data:g}),{data:g}}catch(f){return t.emit("preference.update.resolved",{args:a,error:f}),{error:new w("Failed to update preference",f)}}}),oa=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,scheduleCache:s,useCache:r,args:a}){if(a.find(h=>"preference"in h&&h.preference.level==="global"))return{error:new w("Global preference is not supported in bulk update","")};try{const h=a.map(m=>"preference"in m?new qe(y(d({},m.preference),{channels:d(d({},m.preference.channels),m.channels)}),{emitterInstance:t,inboxServiceInstance:n,cache:i,scheduleCache:s,useCache:r}):void 0).filter(m=>m!==void 0);t.emit("preferences.bulk_update.pending",{args:a,data:h});const u=a.map(m=>{var _,U,N,A;return d({workflowId:"workflowId"in m?m.workflowId:(A=(N=(_=m.preference.workflow)==null?void 0:_.id)!=null?N:(U=m.preference.workflow)==null?void 0:U.identifier)!=null?A:""},m.channels)}),g=(yield n.bulkUpdatePreferences(u)).map(m=>new qe(m,{emitterInstance:t,inboxServiceInstance:n,cache:i,scheduleCache:s,useCache:r}));return t.emit("preferences.bulk_update.resolved",{args:a,data:g}),{data:g}}catch(h){return t.emit("preferences.bulk_update.resolved",{args:a,error:h}),{error:new w("Failed to bulk update preferences",h)}}}),aa=({emitter:e,apiService:t,cache:n,scheduleCache:i,useCache:s,args:r})=>{const a=s?n==null?void 0:n.getAll({}):void 0;a==null||a.forEach(c=>{var h,u;if(c.level==="template"){const f=y(d({},c),{channels:Object.entries(c.channels).reduce((m,[_,U])=>{var N;const A=_;return m[A]=(N=r.channels[A])!=null?N:U,m},{})}),g="preference"in r?new qe(f,{emitterInstance:e,inboxServiceInstance:t,cache:n,scheduleCache:i,useCache:s}):void 0;g&&e.emit("preference.update.pending",{args:{workflowId:(u=(h=c.workflow)==null?void 0:h.id)!=null?u:"",channels:g.channels},data:g})}})},Ss=e=>l(null,[e],function*({emitter:t,apiService:n,cache:i,useCache:s,args:r}){var a,c;try{const{isEnabled:h,weeklySchedule:u}=r,f=new an({isEnabled:h,weeklySchedule:u},{emitterInstance:t,inboxServiceInstance:n,cache:i,useCache:s});t.emit("preference.schedule.update.pending",{args:r,data:f});const g=yield n.updateGlobalPreferences({schedule:{isEnabled:h,weeklySchedule:u}}),m=new an({isEnabled:(a=g.schedule)==null?void 0:a.isEnabled,weeklySchedule:(c=g.schedule)==null?void 0:c.weeklySchedule},{emitterInstance:t,inboxServiceInstance:n,cache:i,useCache:s});return t.emit("preference.schedule.update.resolved",{args:r,data:m}),{data:m}}catch(h){return t.emit("preference.schedule.update.resolved",{args:r,error:h}),{error:new w("Failed to update preference",h)}}}),Oe,ca=class extends he{constructor({cache:e,useCache:t,inboxServiceInstance:n,eventEmitterInstance:i}){super({eventEmitterInstance:i,inboxServiceInstance:n}),p(this,Oe),this.cache=e,v(this,Oe,t)}get(){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){var e,t;try{let n=o(this,Oe)?this.cache.getAll():void 0;if(this._emitter.emit("preference.schedule.get.pending",{args:void 0,data:n}),!n){const i=yield this._inboxService.fetchGlobalPreferences();n=new an({isEnabled:(e=i==null?void 0:i.schedule)==null?void 0:e.isEnabled,weeklySchedule:(t=i==null?void 0:i.schedule)==null?void 0:t.weeklySchedule},{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,useCache:o(this,Oe)}),o(this,Oe)&&(this.cache.set(n),n=this.cache.getAll())}return this._emitter.emit("preference.schedule.get.resolved",{args:void 0,data:n}),{data:n}}catch(n){throw this._emitter.emit("preference.schedule.get.resolved",{args:void 0,error:n}),n}}))})}update(e){return l(this,null,function*(){return this.callWithSession(()=>Ss({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:o(this,Oe),args:e}))})}};Oe=new WeakMap;var ha=["preference.update.pending","preference.update.resolved","preferences.bulk_update.pending","preferences.bulk_update.resolved"],la=["preference.schedule.update.pending","preference.schedule.update.resolved"],ua=({tags:e,severity:t})=>Object.entries({tags:e,severity:t}).reduce((n,[i,s])=>(s==null||Array.isArray(s)&&s.length===0||(n[i]=s),n),{}),kn=({tags:e,severity:t})=>JSON.stringify(ua({tags:e,severity:t})),xe,M,da=class{constructor({emitterInstance:e}){p(this,xe),p(this,M),this.updatePreference=(t,n)=>{const i=o(this,M).get(t);if(!i)return!1;const s=i.findIndex(a=>{var c,h;return((c=a.workflow)==null?void 0:c.id)===((h=n.workflow)==null?void 0:h.id)||a.level===n.level&&n.level==="global"});if(s===-1)return!1;const r=[...i];return r[s]=n,o(this,M).set(t,r),!0},this.updatePreferenceSchedule=(t,n)=>{const i=o(this,M).get(t);if(!i)return!1;const s=i.findIndex(a=>a.level==="global");if(s===-1)return!1;const r=[...i];return r[s].schedule=n,o(this,M).set(t,r),!0},this.handleScheduleEvent=({data:t})=>{var n;if(!t)return;const i=o(this,M).keys(),s=new Set;for(const r of i){const a=this.updatePreferenceSchedule(r,t),c=o(this,M).get(r);!a||!c||s.add(r)}
22for(const r of s)o(this,xe).emit("preferences.list.updated",{data:(n=o(this,M).get(r))!=null?n:[]})},this.handlePreferenceEvent=({data:t})=>{if(!t)return;const n=Array.isArray(t)?t:[t],i=new Set;o(this,M).keys().forEach(s=>{n.forEach(r=>{const a=this.updatePreference(s,r),c=o(this,M).get(s);!a||!c||i.add(s)})}),i.forEach(s=>{var r;o(this,xe).emit("preferences.list.updated",{data:(r=o(this,M).get(s))!=null?r:[]})})},v(this,xe,e);for(const t of ha)o(this,xe).on(t,this.handlePreferenceEvent);for(const t of la)o(this,xe).on(t,this.handleScheduleEvent);v(this,M,new yt)}has(e){return o(this,M).get(kn(e))!==void 0}set(e,t){o(this,M).set(kn(e),t)}getAll(e){if(this.has(e))return o(this,M).get(kn(e))}clearAll(){o(this,M).clear()}};xe=new WeakMap;M=new WeakMap;var fa=["preference.schedule.update.pending","preference.schedule.update.resolved"],En=()=>"schedule",lt,V,pa=class{constructor({emitterInstance:e}){p(this,lt),p(this,V),this.updateScheduleInCache=(t,n)=>o(this,V).get(t)?(o(this,V).set(t,n),!0):!1,this.handleScheduleEvent=({data:t})=>{if(!t)return;const n=new Set,i=o(this,V).keys();for(const s of i){const r=this.updateScheduleInCache(s,t),a=o(this,V).get(s);!r||!a||n.add(s)}for(const s of n)o(this,lt).emit("preference.schedule.get.updated",{data:o(this,V).get(s)})},v(this,lt,e);for(const t of fa)o(this,lt).on(t,this.handleScheduleEvent);v(this,V,new yt)}has(){return o(this,V).get(En())!==void 0}set(e){o(this,V).set(En(),e)}getAll(){if(this.has())return o(this,V).get(En())}clearAll(){o(this,V).clear()}};lt=new WeakMap;V=new WeakMap;var _e,va=class extends he{constructor({useCache:e,inboxServiceInstance:t,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:t}),p(this,_e),this.cache=new da({emitterInstance:this._emitter}),this.scheduleCache=new pa({emitterInstance:this._emitter}),v(this,_e,e),this.schedule=new ca({cache:this.scheduleCache,useCache:e,inboxServiceInstance:t,eventEmitterInstance:n})}list(){return l(this,arguments,function*(e={}){return this.callWithSession(()=>l(this,null,function*(){var t;try{let n=o(this,_e)?this.cache.getAll(e):void 0;return this._emitter.emit("preferences.list.pending",{args:e,data:n}),n||(n=(yield this._inboxService.fetchPreferences({tags:e.tags,severity:e.severity,criticality:(t=e.criticality)!=null?t:"nonCritical"})).map(s=>new qe(s,{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:o(this,_e)})),o(this,_e)&&(this.cache.set(e,n),n=this.cache.getAll(e))),this._emitter.emit("preferences.list.resolved",{args:e,data:n}),{data:n}}catch(n){throw this._emitter.emit("preferences.list.resolved",{args:e,error:n}),n}}))})}update(e){return l(this,null,function*(){return this.callWithSession(()=>bs({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:o(this,_e),args:e}))})}bulkUpdate(e){return l(this,null,function*(){return this.callWithSession(()=>oa({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:o(this,_e),args:e}))})}};_e=new WeakMap;function ya(){return typeof window<"u"}var Fe,Xt,K,_a=class{constructor(e,t,n){p(this,Fe),p(this,Xt),p(this,K),v(this,Fe,n),v(this,Xt,t),v(this,K,e)}get applicationIdentifier(){return o(this,K).applicationIdentifier}get subscriberId(){var e;return(e=o(this,K).subscriber)==null?void 0:e.subscriberId}get context(){return o(this,K).context}get subscriberHash(){return o(this,K).subscriberHash}get contextHash(){return o(this,K).contextHash}get subscriber(){return o(this,K).subscriber}handleApplicationIdentifier(e,t){if(typeof window>"u"||!window.localStorage)return null;const n="novu_keyless_application_identifier";switch(e){case"get":return window.localStorage.getItem(n);case"store":return t&&window.localStorage.setItem(n,t),null;case"delete":return window.localStorage.removeItem(n),null;default:return null}}initialize(e){return l(this,null,function*(){var t,n,i,s,r,a;const c=((t=o(this,K).subscriber)==null?void 0:t.subscriberId)===((n=e==null?void 0:e.subscriber)==null?void 0:n.subscriberId),h=JSON.stringify(o(this,K).context)===JSON.stringify(e==null?void 0:e.context);if(!(c&&h))try{e&&v(this,K,e);const{subscriber:u,subscriberHash:f,contextHash:g,applicationIdentifier:m,defaultSchedule:_,context:U}=o(this,K);let N;ya()&&(N=Intl.DateTimeFormat().resolvedOptions().timeZone);let A=m;if(A)this.handleApplicationIdentifier("delete");else{const Le=this.handleApplicationIdentifier("get");Le&&(A=Le)}
22o(this,Fe).emit("session.initialize.pending",{args:o(this,K)});const X=yield o(this,Xt).initializeSession({applicationIdentifier:A,subscriberHash:f,contextHash:g,subscriber:y(d({},u),{subscriberId:(i=u==null?void 0:u.subscriberId)!=null?i:"",timezone:(s=u==null?void 0:u.timezone)!=null?s:N}),defaultSchedule:_,context:U});(r=X==null?void 0:X.applicationIdentifier)!=null&&r.startsWith("pk_keyless_")&&this.handleApplicationIdentifier("store",X.applicationIdentifier),(a=X==null?void 0:X.applicationIdentifier)!=null&&a.startsWith("pk_keyless_")||this.handleApplicationIdentifier("delete"),o(this,Fe).emit("session.initialize.resolved",{args:o(this,K),data:X})}catch(u){o(this,Fe).emit("session.initialize.resolved",{args:o(this,K),error:u})}})}};Fe=new WeakMap;Xt=new WeakMap;K=new WeakMap;var ma=/^(?:\{\{[^}]*\}\}.*|(?!mailto:)(?:https?:\/\/[^\s/$.?#][^\s{}]*(?:\{\{[^}]*\}\}[^\s{}]*)*)|\/(?!\/)[^\s{}]*(?:\{\{[^}]*\}\}[^\s{}]*)*)$/,ga=["_self","_blank","_parent","_top","_unfencedTop"];function wa(e){return ma.test(e)}function ba(e){return typeof e=="string"&&ga.includes(e)}function Be(e,t){if(!(!e||!wa(e)))return d({url:e},ba(t)?{target:t}:{})}var pn="wss://socket.novu.co",Sa=25e3,ks="ping",Si="notifications.notification_received",ki="notifications.unseen_count_changed",Ei="notifications.unread_count_changed",ka=({_id:e,transactionId:t,content:n,read:i,seen:s,archived:r,snoozedUntil:a,deliveredAt:c,createdAt:h,lastReadDate:u,firstSeenDate:f,archivedAt:g,channel:m,subscriber:_,subject:U,avatar:N,cta:A,tags:X,data:Le,workflow:yn,severity:_n})=>{var Ve,He,Ge,je,Je,Ye,Qe,Xe,Ze;const mn={id:_==null?void 0:_._id,subscriberId:_==null?void 0:_.subscriberId,firstName:_==null?void 0:_.firstName,lastName:_==null?void 0:_.lastName,avatar:_==null?void 0:_.avatar,locale:_==null?void 0:_.locale,data:_==null?void 0:_.data,timezone:_==null?void 0:_.timezone,email:_==null?void 0:_.email,phone:_==null?void 0:_.phone},oe=(He=(Ve=A.action)==null?void 0:Ve.buttons)==null?void 0:He.find(ge=>ge.type==="primary"),ae=(je=(Ge=A.action)==null?void 0:Ge.buttons)==null?void 0:je.find(ge=>ge.type==="secondary"),et=(Ye=(Je=A.action)==null?void 0:Je.result)==null?void 0:Ye.type,tt=(Qe=A.action)==null?void 0:Qe.status;return y(d(d({id:e,transactionId:t,subject:U,body:n,to:mn,isRead:i,isSeen:s,isArchived:r,isSnoozed:!!a},c&&{deliveredAt:c}),a&&{snoozedUntil:a}),{createdAt:h,readAt:u,firstSeenAt:f,archivedAt:g,avatar:N,primaryAction:oe&&{label:oe.content,isCompleted:et==="primary"&&tt==="done",redirect:Be(oe.url,oe.target)},secondaryAction:ae&&{label:ae.content,isCompleted:et==="secondary"&&tt==="done",redirect:Be(ae.url,ae.target)},channelType:m,tags:X,redirect:Be((Xe=A.data)==null?void 0:Xe.url,(Ze=A.data)==null?void 0:Ze.target),data:Le,workflow:yn,severity:_n})},dt,ee,Y,_t,cn,De,Rn,Pn,Un,Qn,Q,vn,Es,As,Ln,Mn,Ea=class extends he{constructor({socketUrl:e,socketOptions:t,inboxServiceInstance:n,eventEmitterInstance:i}){super({eventEmitterInstance:i,inboxServiceInstance:n}),p(this,Q),p(this,dt),p(this,ee),p(this,Y),p(this,_t),p(this,cn),p(this,De),p(this,Rn,s=>{try{const r=JSON.parse(s.data);r.event==="notification_received"&&o(this,ee).emit(Si,{result:new P(ka(r.data.message),o(this,ee),this._inboxService)})}catch(r){console.log("error",r)}}),p(this,Pn,s=>{try{const r=JSON.parse(s.data);r.event==="unseen_count_changed"&&o(this,ee).emit(ki,{result:r.data.unseenCount})}catch{}}),p(this,Un,s=>{try{const r=JSON.parse(s.data);r.event==="unread_count_changed"&&o(this,ee).emit(Ei,{result:r.data.counts})}catch{}}),p(this,Qn,s=>{if(!(s.data===ks||s.data==="pong"))try{switch(JSON.parse(s.data).event){case"notification_received":o(this,Rn).call(this,s);break;case"unseen_count_changed":o(this,Pn).call(this,s);break;case"unread_count_changed":o(this,Un).call(this,s);break;default:}}catch{}}),v(this,ee,i),v(this,_t,e??pn),v(this,cn,t)}onSessionSuccess({token:e}){v(this,dt,e)}isSocketEvent(e){return e===Si||e===ki||e===Ei}connect(){return l(this,null,function*(){return o(this,dt)?S(this,Q,Ln).call(this):this.callWithSession(S(this,Q,Ln).bind(this))})}disconnect(){return l(this,null,function*(){return o(this,Y)?S(this,Q,Mn).call(this):this.callWithSession(S(this,Q,Mn).bind(this))})}};dt=new WeakMap;ee=new WeakMap;Y=new WeakMap;_t=new WeakMap;cn=new WeakMap;De=new WeakMap;Rn=new WeakMap;Pn=new WeakMap;Un=new WeakMap;Qn=new WeakMap;Q=new WeakSet;vn=function(){o(this,De)!==void 0&&(clearInterval(o(this,De)),v(this,De,void 0))};Es=function(){S(this,Q,vn).call(this),v(this,De,setInterval(()=>{const e=o(this,Y);if(!(!e||e.readyState!==qi.OPEN))try{e.send(ks)}catch{}},Sa))};As=function(){return l(this,null,function*(){if(o(this,Y))return;const e={socketUrl:o(this,_t)};o(this,ee).emit("socket.connect.pending",{args:e});const t=new URL(o(this,_t));t.searchParams.set("token",o(this,dt)),v(this,Y,new qi(t.toString(),void 0,o(this,cn)));const n=o(this,Y);n.addEventListener("open",()=>{S(this,Q,Es).call(this),o(this,ee).emit("socket.connect.resolved",{args:e})}),n.addEventListener("error",i=>{o(this,ee).emit("socket.connect.resolved",{args:e,error:i})}),n.addEventListener("close",()=>{n===o(this,Y)&&(S(this,Q,vn).call(this),v(this,Y,void 0))}),n.addEventListener("message",o(this,Qn))})};Ln=function(){return l(this,null,function*(){try{return yield S(this,Q,As).call(this),{}}catch(e){return{error:new w("Failed to initialize the PartySocket",e)}}})};Mn=function(){return l(this,null,function*(){var e;try{return S(this,Q,vn).call(this),(e=o(this,Y))==null||e.close(),v(this,Y,void 0),{}}catch(t){return{error:new w("Failed to disconnect from the PartySocket",t)}}})};var Aa="https://ws.novu.co",Ai="notifications.notification_received",Ii="notifications.unseen_count_changed",Ci="notifications.unread_count_changed",Ia=({_id:e,transactionId:t,content:n,read:i,seen:s,archived:r,snoozedUntil:a,deliveredAt:c,createdAt:h,lastReadDate:u,firstSeenDate:f,archivedAt:g,channel:m,subscriber:_,subject:U,avatar:N,cta:A,tags:X,data:Le,w
22orkflow:yn,severity:_n})=>{var Ve,He,Ge,je,Je,Ye,Qe,Xe,Ze;const mn={id:_==null?void 0:_._id,subscriberId:_==null?void 0:_.subscriberId,firstName:_==null?void 0:_.firstName,lastName:_==null?void 0:_.lastName,avatar:_==null?void 0:_.avatar,locale:_==null?void 0:_.locale,data:_==null?void 0:_.data,timezone:_==null?void 0:_.timezone,email:_==null?void 0:_.email,phone:_==null?void 0:_.phone},oe=(He=(Ve=A.action)==null?void 0:Ve.buttons)==null?void 0:He.find(ge=>ge.type==="primary"),ae=(je=(Ge=A.action)==null?void 0:Ge.buttons)==null?void 0:je.find(ge=>ge.type==="secondary"),et=(Ye=(Je=A.action)==null?void 0:Je.result)==null?void 0:Ye.type,tt=(Qe=A.action)==null?void 0:Qe.status;return y(d(d({id:e,transactionId:t,subject:U,body:n,to:mn,isRead:i,isSeen:s,isArchived:r,isSnoozed:!!a},c&&{deliveredAt:c}),a&&{snoozedUntil:a}),{createdAt:h,readAt:u,firstSeenAt:f,archivedAt:g,avatar:N,primaryAction:oe&&{label:oe.content,isCompleted:et==="primary"&&tt==="done",redirect:Be(oe.url,oe.target)},secondaryAction:ae&&{label:ae.content,isCompleted:et==="secondary"&&tt==="done",redirect:Be(ae.url,ae.target)},channelType:m,tags:X,redirect:Be((Xe=A.data)==null?void 0:Xe.url,(Ze=A.data)==null?void 0:Ze.target),data:Le,workflow:yn,severity:_n})},ft,te,H,mt,hn,Xn,Zn,ei,Ne,Is,Wn,Fn,Ca=class extends he{constructor({socketUrl:e,socketOptions:t,inboxServiceInstance:n,eventEmitterInstance:i}){super({eventEmitterInstance:i,inboxServiceInstance:n}),p(this,Ne),p(this,ft),p(this,te),p(this,H),p(this,mt),p(this,hn),p(this,Xn,({message:s})=>{o(this,te).emit(Ai,{result:new P(Ia(s),o(this,te),this._inboxService)})}),p(this,Zn,({unseenCount:s})=>{o(this,te).emit(Ii,{result:s})}),p(this,ei,({counts:s})=>{o(this,te).emit(Ci,{result:s})}),v(this,te,i),v(this,mt,e??Aa),v(this,hn,t)}onSessionSuccess({token:e}){v(this,ft,e)}isSocketEvent(e){return e===Ai||e===Ii||e===Ci}connect(){return l(this,null,function*(){return o(this,ft)?S(this,Ne,Wn).call(this):this.callWithSession(S(this,Ne,Wn).bind(this))})}disconnect(){return l(this,null,function*(){return o(this,H)?S(this,Ne,Fn).call(this):this.callWithSession(S(this,Ne,Fn).bind(this))})}};ft=new WeakMap;te=new WeakMap;H=new WeakMap;mt=new WeakMap;hn=new WeakMap;Xn=new WeakMap;Zn=new WeakMap;ei=new WeakMap;Ne=new WeakSet;Is=function(){return l(this,null,function*(){var e,t,n,i;if(o(this,H))return;const s={socketUrl:o(this,mt)};o(this,te).emit("socket.connect.pending",{args:s}),v(this,H,Nt(o(this,mt),d({reconnectionDelayMax:1e4,transports:["websocket"],query:{token:`${o(this,ft)}`}},(e=o(this,hn))!=null?e:{}))),o(this,H).on("connect",()=>{o(this,te).emit("socket.connect.resolved",{args:s})}),o(this,H).on("connect_error",r=>{o(this,te).emit("socket.connect.resolved",{args:s,error:r})}),(t=o(this,H))==null||t.on("notification_received",o(this,Xn)),(n=o(this,H))==null||n.on("unseen_count_changed",o(this,Zn)),(i=o(this,H))==null||i.on("unread_count_changed",o(this,ei))})};Wn=function(){return l(this,null,function*(){try{return yield S(this,Ne,Is).call(this),{}}catch(e){return{error:new w("Failed to initialize the socket",e)}}})};Fn=function(){return l(this,null,function*(){var e;try{return(e=o(this,H))==null||e.disconnect(),v(this,H,void 0),{}}catch(t){return{error:new w("Failed to disconnect from the socket",t)}}})};var Ta=["wss://eu.socket.novu.co",pn,"wss://socket.novu-staging.co","wss://socket-worker-local.cli-shortener.workers.dev"],Oa={"https://eu.ws.novu.co":"wss://eu.socket.novu.co","https://ws.novu.co":pn,"https://dev.ws.novu.co":"wss://socket.novu-staging.co"},xa={cloud:"partysocket","self-hosted":"socket.io"};function Na(e){return e?Oa[e]||e:pn}function Ra(e){return!e||Ta.includes(e)}function Pa(e,t){return t?xa[t]:Ra(e)?"partysocket":"socket.io"}function Ua({socketUrl:e,socketOptions:t,inboxServiceInstance:n,eventEmitterInstance:i}){const s=Na(e),r=t||{},{socketType:a}=r,c=Bn(r,["socketType"]);switch(Pa(s,a)){case"partysocket":return new Ea({socketUrl:s,socketOptions:c,inboxServiceInstance:n,eventEmitterInstance:i});case"socket.io":default:return new Ca({socketUrl:s,socketOptions:c,inboxServiceInstance:n,eventEmitterInstance:i})}}var z,W,ut,j,Zt,en,za=class{constructor(e){p(this,z),p(this,W),p(this,ut),p(this,j),p(this,Zt),p(this,en);var t,n,i;v(this,en,e),v(this,ut,new gs({apiUrl:e.apiUrl||e.backendUrl})),v(this,j,new Bo({httpClient:o(this,ut)})),v(this,Zt,new Ro({httpClient:o(this,ut)})),v(this,z,new ea);const s=Ls({subscriberId:e.subscriberId,subscriber:e.subscriber}),r=si(e.context);v(this,W,new _a({applicationIdentifier:e.applicationIdentifier||"",subscriberHash:e.subscriberHash,subscriber:s,defaultSchedule:e.defaultSchedule,context:e.context,contextHash:e.contextHash},o(this,j),o(this,z))),o(this,W).initialize(),this.notifications=new ra({useCache:(t=e.useCache)!=null?t:!0,inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,z)}),this.preferences=new va({useCache:(n=e.useCache)!=null?n:!0,inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,z)}),this.subscriptions=new lo({subscriber:s,contextKey:r,useCache:(i=e.useCache)!=null?i:!0,inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,z)}),this.channelConnections=new Ho({inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,z)}),this.channelEndpoints=new Zo({inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,z)}),this.agentChat=new No({inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,z),agentChatService:o(this,Zt)}),this.socket=Ua({socketUrl:e.socketUrl,socketOptions:e.socketOptions,eventEmitterInstance:o(this,z),inboxServiceInstance:o(this,j)}),this.on=(a,c)=>{this.socket.isSocketEvent(a)&&this.socket.connect();const h=o(this,z).on(a,c);return()=>{h()}},this.off=(a,c)=>{o(this,z).off(a,c)}}get applicationIdentifier(){return o(this,W).applicationIdentifier}get subscriberId(){return o(this,W).subscriberId}get context(){return o(this,W).context}get contextHash(){return o(this,W).contextHash}get options(){return o(this,en)}get contextKey(){return si(o(this,W).context)}clearCache(){this.notifications.cache.clearAll(),this.preferences.cache.clearAll(),this.preferences.scheduleCache.clearAll(),this.subscriptions.cache.clearAll(),this.agentChat.clearCache()}changeSubscriber(e){return l(this,null,function*(){yield o(this,W).initialize({applicationIdentifier:o(this,W).applicationIdentifier||"",subscriberHash:e.subscriberHash,subscriber:e.subscriber,context:o(this,W).context,contextHash:o(this,W).contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}changeContext(e){return l(this,null,function*(){const t=o(this,W).subscriber;if(!t)throw new Error("Cannot change context without an active subscriber");yield o(this,W).initialize({applicationIdentifier:o(this,W).applicationIdentifier||"",subscriberHash:o(this,W).subscriberHash,subscriber:t,context:e.context,contextHash:e.contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}};z=new WeakMap;W=new WeakMap;ut=new WeakMap;j=new WeakMap;Zt=new WeakMap;en=new WeakMap;var La="https://api.novu.co",Ma=2e3,Wa="telegram",Pe,ce,pt,Re,Ke,$e,gt,E,ln,ne,Cs,Ts,$n,Os,ti,Ue,wt,Va=class{constructor(e){p(this,E),p(this,Pe),p(this,ce,{status:"loading",deepLinkUrl:null,botUsername:null,expiresAt:null,error:null}),p(this,pt,new Set),p(this,Re,null),p(this,Ke,null),p(this,$e,!1),p(this,gt,0);var t,n,i;v(this,Pe,{apiUrl:(t=e.apiUrl)!=null?t:La,secretKey:e.secretKey,integrationIdentifier:e.integrationIdentifier,subscriberId:e.subscriberId,pollIntervalMs:(n=e.pollIntervalMs)!=null?n:Ma,c
22ontext:e.context,fetchFn:(i=e.fetchFn)!=null?i:fetch})}get state(){return o(this,ce)}onStateChange(e){return o(this,pt).add(e),()=>{o(this,pt).delete(e)}}start(){return l(this,null,function*(){v(this,$e,!1);const e=++Ri(this,gt)._;try{const t=yield S(this,E,ti).call(this);if(S(this,E,ne).call(this,e))return;if(t){S(this,E,Ue).call(this,y(d({},o(this,ce)),{status:"connected",error:null}));return}}catch{}S(this,E,ne).call(this,e)||(yield S(this,E,ln).call(this))})}refresh(){return l(this,null,function*(){S(this,E,wt).call(this),v(this,$e,!1),yield S(this,E,ln).call(this)})}stop(){v(this,$e,!0),S(this,E,wt).call(this)}};Pe=new WeakMap;ce=new WeakMap;pt=new WeakMap;Re=new WeakMap;Ke=new WeakMap;$e=new WeakMap;gt=new WeakMap;E=new WeakSet;ln=function(){return l(this,null,function*(){const e=++Ri(this,gt)._;try{const t=yield S(this,E,Cs).call(this);if(S(this,E,ne).call(this,e))return;S(this,E,Ue).call(this,{status:"pending",deepLinkUrl:t.deepLinkUrl,botUsername:t.botUsername,expiresAt:t.expiresAt,error:null}),S(this,E,Ts).call(this,t.expiresAt,e),S(this,E,Os).call(this,e)}catch(t){if(S(this,E,ne).call(this,e))return;S(this,E,Ue).call(this,y(d({},o(this,ce)),{status:"pending",error:t instanceof Error?t:new Error(String(t))}))}})};ne=function(e){return o(this,$e)||e!==o(this,gt)};Cs=function(){return l(this,null,function*(){var e,t,n,i,s;const{apiUrl:r,integrationIdentifier:a,subscriberId:c,secretKey:h,context:u,fetchFn:f}=o(this,Pe),g=`${r}/v1/integrations/channel-endpoints/link`,m={"Content-Type":"application/json"};h&&(m.Authorization=`ApiKey ${h}`);const _=yield f(g,{method:"POST",headers:m,body:JSON.stringify({integrationIdentifier:a,subscriberId:c,context:u})});if(!_.ok){const A=yield _.text();throw new Error(`Failed to issue Telegram subscriber link (HTTP ${_.status}): ${A}`)}const U=yield _.json(),N=(e=U.data)!=null?e:U;return{deepLinkUrl:N.url,botUsername:(n=(t=N.providerMetadata)==null?void 0:t.botUsername)!=null?n:"",expiresAt:(s=(i=N.providerMetadata)==null?void 0:i.expiresAt)!=null?s:""}})};Ts=function(e,t){const n=new Date(e).getTime();if(!Number.isFinite(n)){S(this,E,Ue).call(this,y(d({},o(this,ce)),{error:new Error(`Invalid expiresAt received: ${e}`)}));return}const i=n-Date.now();if(i<=0){S(this,E,$n).call(this,t);return}v(this,Ke,setTimeout(()=>S(this,E,$n).call(this,t),i))};$n=function(e){S(this,E,ne).call(this,e)||(S(this,E,wt).call(this),S(this,E,Ue).call(this,y(d({},o(this,ce)),{status:"expired"})),S(this,E,ln).call(this))};Os=function(e){if(S(this,E,ne).call(this,e))return;const t=()=>l(this,null,function*(){if(!S(this,E,ne).call(this,e)){try{const n=yield S(this,E,ti).call(this);if(S(this,E,ne).call(this,e))return;if(n){S(this,E,wt).call(this),S(this,E,Ue).call(this,y(d({},o(this,ce)),{status:"connected",error:null}));return}}catch{}S(this,E,ne).call(this,e)||v(this,Re,setTimeout(t,o(this,Pe).pollIntervalMs))}});v(this,Re,setTimeout(t,o(this,Pe).pollIntervalMs))};ti=function(){return l(this,null,function*(){var e;const{apiUrl:t,integrationIdentifier:n,subscriberId:i,secretKey:s,fetchFn:r}=o(this,Pe),a=new URLSearchParams({subscriberId:i,integrationIdentifier:n,providerId:Wa,limit:"1"}),c=`${t}/v1/channel-endpoints?${a.toString()}`,h={};s&&(h.Authorization=`ApiKey ${s}`);const u=yield r(c,{method:"GET",headers:h});if(!u.ok)return!1;const f=yield u.json(),g=(e=f.data)!=null?e:f;return Array.isArray(g)&&g.length>0})};Ue=function(e){v(this,ce,e);for(const t of o(this,pt))t(e)};wt=function(){o(this,Re)&&(clearTimeout(o(this,Re)),v(this,Re,null)),o(this,Ke)&&(clearTimeout(o(this,Ke)),v(this,Ke,null))};export{$s as ChannelType,Ka as NOTIFICATION_COUNT_SYNC_EVENTS,Ws as NotificationStatus,za as Novu,w as NovuError,Fs as PreferenceLevel,Ds as SeverityLevelEnum,vt as SubscriptionPreference,Va as TelegramSubscriberLink,bt as TopicSubscription,Bs as WebSocketEvent,Ks as WorkflowCriticalityEnum,Xr as areSeveritiesEqual,ss as areTagsEqual,io as checkNotificationDataFilter,qa as checkNotificationMatchesFilter,yi as isSameFilter,is as normalizeTagGroups};

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