@gamention/pulse-core 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -19,11 +19,13 @@ export declare class Connection extends Emitter {
19
19
  private reconnectAttempt;
20
20
  private reconnectTimer;
21
21
  private _state;
22
+ private permanentlyClosed;
22
23
  get state(): ConnectionState;
23
24
  constructor(endpoint?: string);
24
25
  connect(): void;
25
26
  disconnect(): void;
26
27
  send(message: ClientMessage): void;
28
+ permanentDisconnect(): void;
27
29
  private scheduleReconnect;
28
30
  }
29
31
 
@@ -52,6 +54,7 @@ export declare class PulseClient extends Emitter {
52
54
  constructor(config: PulseConfig);
53
55
  connect(): void;
54
56
  disconnect(): void;
57
+ destroy(): void;
55
58
  private authenticate;
56
59
  send(message: ClientMessage): void;
57
60
  moveCursor(position: CursorPosition): void;
@@ -120,6 +123,8 @@ export declare class StateManager extends Emitter {
120
123
  markAllNotificationsRead(): void;
121
124
  get activityLogs(): ActivityLog[];
122
125
  getUser(userId: string): PulseUser | undefined;
126
+ /** Get all known users (from presence + comment authors). */
127
+ get users(): PulseUser[];
123
128
  getReactions(targetId: string): Reaction[];
124
129
  getTypingUsers(threadId: string): string[];
125
130
  get viewports(): Map<string, ViewportInfo>;
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var _=(o,n,t)=>n in o?f(o,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[n]=t;var i=(o,n,t)=>_(o,typeof n!="symbol"?n+"":n,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d={allowImages:!0,allowAudio:!0,allowVideo:!0,maxFileSizeMb:10,maxAttachmentsPerComment:5,allowReactions:!0,allowDrawing:!0,allowMentions:!0,showCursors:!0,showPresence:!0,showTypingIndicators:!0},m="ws://localhost:4567",l=50,w=3e4,v=1e3,y=3e4;class h{constructor(){i(this,"handlers",new Map)}on(n,t){this.handlers.has(n)||this.handlers.set(n,new Set);const e=this.handlers.get(n);return e.add(t),()=>e.delete(t)}off(n,t){var e;(e=this.handlers.get(n))==null||e.delete(t)}emit(n,t){var e;(e=this.handlers.get(n))==null||e.forEach(s=>s(t))}removeAll(){this.handlers.clear()}}class u extends h{constructor(t){super();i(this,"ws",null);i(this,"endpoint");i(this,"reconnectAttempt",0);i(this,"reconnectTimer",null);i(this,"_state","disconnected");this.endpoint=t??m}get state(){return this._state}connect(){this.ws||(this._state="connecting",this.emit("state",this._state),this.ws=new WebSocket(this.endpoint),this.ws.addEventListener("open",()=>{this._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)}),this.ws.addEventListener("message",t=>{const e=JSON.parse(t.data);this.emit("message",e)}),this.ws.addEventListener("close",()=>{this.ws=null,this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{var t;(t=this.ws)==null||t.close()}))}disconnect(){var t;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,(t=this.ws)==null||t.close(),this.ws=null,this._state="disconnected",this.emit("state",this._state)}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}scheduleReconnect(){const t=Math.min(v*2**this.reconnectAttempt,y);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}}class p extends h{constructor(){super(...arguments);i(this,"baseUrl","");i(this,"_user",null);i(this,"_config",{...d});i(this,"_users",new Map);i(this,"_presence",new Map);i(this,"_threads",new Map);i(this,"_reactions",new Map);i(this,"_notifications",[]);i(this,"_activityLogs",[]);i(this,"_typing",new Map);i(this,"_viewports",new Map);i(this,"_selections",new Map)}get user(){return this._user}get config(){return this._config}removeComment(t){for(const[e,s]of this._threads){const r=s.comments.findIndex(a=>a.id===t);if(r!==-1){s.comments.splice(r,1),s.comments.length===0&&this._threads.delete(e),this.emit("threads",this.threads);return}}}get presence(){return[...this._presence.values()]}get threads(){return[...this._threads.values()]}get notifications(){return this._notifications}get unreadCount(){return this._notifications.filter(t=>!t.read).length}markNotificationRead(t){const e=this._notifications.find(s=>s.id===t);e&&!e.read&&(e.read=!0,this.emit("notifications",this._notifications))}markAllNotificationsRead(){let t=!1;for(const e of this._notifications)e.read||(e.read=!0,t=!0);t&&this.emit("notifications",this._notifications)}get activityLogs(){return this._activityLogs}getUser(t){return this._users.get(t)}getReactions(t){return this._reactions.get(t)??[]}getTypingUsers(t){const e=this._typing.get(t);if(!e)return[];const s=Date.now(),r=[];for(const[a,c]of e)s-c<3e3&&r.push(a);return r}get viewports(){return this._viewports}getViewport(t){return this._viewports.get(t)}get selections(){return this._selections}resolveUrl(t){return!this.baseUrl||!t||t.startsWith("http://")||t.startsWith("https://")?t:`${this.baseUrl}${t}`}resolveAttachments(t){return t.map(e=>({...e,url:this.resolveUrl(e.url),thumbnailUrl:e.thumbnailUrl?this.resolveUrl(e.thumbnailUrl):void 0}))}resolveComment(t){return!t.attachments||t.attachments.length===0?t:{...t,attachments:this.resolveAttachments(t.attachments)}}resolveThread(t){return{...t,comments:t.comments.map(e=>this.resolveComment(e))}}handleMessage(t){switch(t.type){case"auth:ok":this._config=t.config??{...d},this._user=t.user,this._users.clear();for(const e of t.users)this._users.set(e.id,e);this._presence.clear();for(const e of t.presence)this._presence.set(e.user.id,e),this._users.set(e.user.id,e.user);this._users.set(t.user.id,t.user),this._threads.clear();for(const e of t.threads)this._threads.set(e.id,this.resolveThread(e));this._notifications=t.notifications,this._reactions.clear();for(const e of t.reactions){const s=this._reactions.get(e.targetId)??[];s.push(e),this._reactions.set(e.targetId,s)}this._activityLogs=[...t.activityLogs],this.emit("auth",t.user),this.emit("presence",this.presence),this.emit("threads",this.threads),this.emit("notifications",this._notifications),this.emit("reactions",null),this.emit("activity-logs",this._activityLogs);break;case"presence:join":this._presence.set(t.user.user.id,t.user),this._users.set(t.user.user.id,t.user.user),this.emit("presence",this.presence);break;case"presence:leave":this._presence.delete(t.userId),this._viewports.delete(t.userId),this._selections.delete(t.userId);for(const e of this._typing.values())e.delete(t.userId);this.emit("presence",this.presence);break;case"presence:update":{const e=this._presence.get(t.userId);e&&(e.status=t.status,this.emit("presence",this.presence));break}case"cursor:move":this.emit("cursor",{userId:t.userId,position:t.position});break;case"click:perform":this.emit("click",{userId:t.userId,position:t.position});break;case"thread:created":this._threads.set(t.thread.id,this.resolveThread(t.thread)),this.emit("threads",this.threads);break;case"comment:created":{const e=this._threads.get(t.threadId);e&&(e.comments.push(this.resolveComment(t.comment)),e.updatedAt=t.comment.createdAt,this.emit("threads",this.threads));break}case"comment:edited":{const e=this._threads.get(t.threadId);if(e){const s=e.comments.findIndex(r=>r.id===t.comment.id);s!==-1&&(e.comments[s]=this.resolveComment(t.comment)),this.emit("threads",this.threads)}break}case"comment:deleted":{const e=this._threads.get(t.threadId);e&&(e.comments=e.comments.filter(s=>s.id!==t.commentId),e.comments.length===0&&this._threads.delete(t.threadId),this.emit("threads",this.threads));break}case"thread:resolved":{const e=this._threads.get(t.threadId);e&&(e.resolved=t.resolved,this.emit("threads",this.threads));break}case"thread:deleted":this._threads.delete(t.threadId),this.emit("threads",this.threads);break;case"reaction:added":{const e=this._reactions.get(t.reaction.targetId)??[];e.push(t.reaction),this._reactions.set(t.reaction.targetId,e),this.emit("reactions",{targetId:t.reaction.targetId,reactions:e});break}case"reaction:removed":{const e=this._reactions.get(t.targetId);if(e){const s=e.filter(r=>r.id!==t.reactionId);this._reactions.set(t.targetId,s),this.emit("reactions",{targetId:t.targetId,reactions:s})}break}case"notification":this._notifications.unshift(t.notification),this.emit("notifications",this._notifications);break;case"typing:indicator":{this._typing.has(t.threadId)||this._typing.set(t.threadId,new Map),this._typing.get(t.threadId).set(t.userId,Date.now()),this.emit("typing",{threadId:t.threadId,userId:t.userId});break}case"viewport:update":{this._viewports.set(t.userId,{scrollX:t.scrollX,scrollY:t.scrollY,viewportWidth:t.viewportWidth,viewportHeight:t.viewportHeight,pageWidth:t.pageWidth,pageHeight:t.pageHeight}),this.emit("viewport",{userId:t.userId});break}case"selection:update":this._selections.set(t.userId,t.selection),this.emit("selection",{userId:t.userId,selection:t.selection});break;case"emoji:drop":this.emit("emoji-drop",{userId:t.userId,emoji:t.emoji,position:t.position});break;case"draw:stroke":this.emit("draw-stroke",{userId:t.userId,points:t.points,color:t.color,width:t.width});break;case"draw:clear":this.emit("draw-clear",{userId:t.userId});break;case"activity:logged":this._activityLogs.unshift(t.activityLog),this._activityLogs.length>100&&(this._activityLogs=this._activityLogs.slice(0,100)),this.emit("activity-logs",this._activityLogs);break;case"error":this.emit("error",t);break}}reset(){this._user=null,this._config={...d},this._users.clear(),this._presence.clear(),this._threads.clear(),this._reactions.clear(),this._notifications=[],this._activityLogs=[],this._typing.clear(),this._viewports.clear(),this._selections.clear()}}class I extends h{constructor(t){var s;super();i(this,"state");i(this,"connection");i(this,"config");i(this,"heartbeatTimer",null);i(this,"lastCursorSend",0);i(this,"pendingCursor",null);i(this,"cursorTimer",null);this.config=t,this.state=new p,this.state.baseUrl=(t.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const e=((s=t.endpoint)==null?void 0:s.replace(/^http/,"ws"))??void 0;this.connection=new u(e),this.connection.on("message",r=>{this.state.handleMessage(r),this.emit(r.type,r)}),this.connection.on("state",r=>{this.emit("connection",r),r==="connected"?(this.authenticate(),this.startHeartbeat()):r==="disconnected"&&this.stopHeartbeat()})}get connectionState(){return this.connection.state}connect(){this.connection.connect()}disconnect(){this.stopHeartbeat(),this.connection.disconnect(),this.state.reset()}authenticate(){this.send({type:"auth",apiKey:this.config.apiKey,token:this.config.token,room:this.config.room})}send(t){this.connection.send(t)}moveCursor(t){const e=Date.now();this.pendingCursor=t,e-this.lastCursorSend>=l?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},l))}flushCursor(){this.pendingCursor&&(this.send({type:"cursor:move",position:this.pendingCursor}),this.lastCursorSend=Date.now(),this.pendingCursor=null)}updatePresence(t){this.send({type:"presence:update",status:t})}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.send({type:"presence:update",status:"online"})},w)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}createThread(t,e={}){const s=crypto.randomUUID();return this.send({type:"thread:create",id:s,body:t,mentions:e.mentions??[],position:e.position??null,attachmentIds:e.attachmentIds}),s}reply(t,e,s=[],r){const a=crypto.randomUUID();return this.send({type:"comment:create",threadId:t,id:a,body:e,mentions:s,attachmentIds:r}),a}editComment(t,e,s=[]){this.send({type:"comment:edit",commentId:t,body:e,mentions:s})}deleteComment(t){this.state.removeComment(t),this.send({type:"comment:delete",commentId:t})}resolveThread(t,e=!0){this.send({type:"thread:resolve",threadId:t,resolved:e})}addReaction(t,e,s){this.send({type:"reaction:add",targetId:t,targetType:e,emoji:s})}removeReaction(t){this.send({type:"reaction:remove",reactionId:t})}markRead(t){this.state.markNotificationRead(t),this.send({type:"notification:read",notificationId:t})}markAllRead(){this.state.markAllNotificationsRead(),this.send({type:"notification:read-all"})}performClick(t){this.send({type:"click:perform",position:t})}sendTyping(t){this.send({type:"typing:start",threadId:t})}updateViewport(t){this.send({type:"viewport:update",...t})}updateSelection(t){this.send({type:"selection:update",selection:t})}dropEmoji(t,e){this.send({type:"emoji:drop",emoji:t,position:e})}drawStroke(t,e,s){this.send({type:"draw:stroke",points:t,color:e,width:s})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(t){const e=(this.config.endpoint??window.location.origin).replace(/^ws(s?):/,"http$1:"),s=new FormData;s.append("file",t);const r=await fetch(`${e}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:s});if(!r.ok){const c=await r.json().catch(()=>({error:"Upload failed"}));throw new Error(c.error??"Upload failed")}const a=await r.json();return a.url&&!a.url.startsWith("http")&&(a.url=`${e}${a.url}`),a.thumbnailUrl&&!a.thumbnailUrl.startsWith("http")&&(a.thumbnailUrl=`${e}${a.thumbnailUrl}`),a}setAppearOffline(t){t?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}}exports.Connection=u;exports.Emitter=h;exports.PulseClient=I;exports.StateManager=p;
1
+ "use strict";var f=Object.defineProperty;var _=(h,n,t)=>n in h?f(h,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[n]=t;var i=(h,n,t)=>_(h,typeof n!="symbol"?n+"":n,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@gamention/pulse-shared");class d{constructor(){i(this,"handlers",new Map)}on(n,t){this.handlers.has(n)||this.handlers.set(n,new Set);const e=this.handlers.get(n);return e.add(t),()=>e.delete(t)}off(n,t){var e;(e=this.handlers.get(n))==null||e.delete(t)}emit(n,t){var e;(e=this.handlers.get(n))==null||e.forEach(s=>s(t))}removeAll(){this.handlers.clear()}}class l extends d{constructor(t){super();i(this,"ws",null);i(this,"endpoint");i(this,"reconnectAttempt",0);i(this,"reconnectTimer",null);i(this,"_state","disconnected");i(this,"permanentlyClosed",!1);this.endpoint=t??c.DEFAULT_ENDPOINT}get state(){return this._state}connect(){this.ws||this.permanentlyClosed||(this._state="connecting",this.emit("state",this._state),this.ws=new WebSocket(this.endpoint),this.ws.addEventListener("open",()=>{this._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)}),this.ws.addEventListener("message",t=>{try{const e=JSON.parse(t.data);this.emit("message",e)}catch{}}),this.ws.addEventListener("close",()=>{this.ws=null,this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{var t;(t=this.ws)==null||t.close()}))}disconnect(){var t;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,(t=this.ws)==null||t.close(),this.ws=null,this._state="disconnected",this.emit("state",this._state)}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}permanentDisconnect(){this.permanentlyClosed=!0,this.disconnect()}scheduleReconnect(){if(this.permanentlyClosed)return;const t=Math.min(c.RECONNECT_BASE_DELAY_MS*2**this.reconnectAttempt,c.RECONNECT_MAX_DELAY_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}}class u extends d{constructor(){super(...arguments);i(this,"baseUrl","");i(this,"_user",null);i(this,"_config",{...c.DEFAULT_ENV_CONFIG});i(this,"_users",new Map);i(this,"_presence",new Map);i(this,"_threads",new Map);i(this,"_reactions",new Map);i(this,"_notifications",[]);i(this,"_activityLogs",[]);i(this,"_typing",new Map);i(this,"_viewports",new Map);i(this,"_selections",new Map)}get user(){return this._user}get config(){return this._config}removeComment(t){for(const[e,s]of this._threads){const r=s.comments.findIndex(o=>o.id===t);if(r!==-1){s.comments.splice(r,1),s.comments.length===0&&this._threads.delete(e),this.emit("threads",this.threads);return}}}get presence(){return[...this._presence.values()]}get threads(){return[...this._threads.values()]}get notifications(){return this._notifications}get unreadCount(){return this._notifications.filter(t=>!t.read).length}markNotificationRead(t){const e=this._notifications.find(s=>s.id===t);e&&!e.read&&(e.read=!0,this.emit("notifications",this._notifications))}markAllNotificationsRead(){let t=!1;for(const e of this._notifications)e.read||(e.read=!0,t=!0);t&&this.emit("notifications",this._notifications)}get activityLogs(){return this._activityLogs}getUser(t){return this._users.get(t)}get users(){return[...this._users.values()]}getReactions(t){return this._reactions.get(t)??[]}getTypingUsers(t){const e=this._typing.get(t);if(!e)return[];const s=Date.now(),r=[];for(const[o,a]of e)s-a<3e3&&r.push(o);return r}get viewports(){return this._viewports}getViewport(t){return this._viewports.get(t)}get selections(){return this._selections}resolveUrl(t){return!this.baseUrl||!t||t.startsWith("http://")||t.startsWith("https://")?t:`${this.baseUrl}${t}`}resolveAttachments(t){return t.map(e=>({...e,url:this.resolveUrl(e.url),thumbnailUrl:e.thumbnailUrl?this.resolveUrl(e.thumbnailUrl):void 0}))}resolveComment(t){return!t.attachments||t.attachments.length===0?t:{...t,attachments:this.resolveAttachments(t.attachments)}}resolveThread(t){return{...t,comments:t.comments.map(e=>this.resolveComment(e))}}handleMessage(t){switch(t.type){case"auth:ok":this._config=t.config??{...c.DEFAULT_ENV_CONFIG},this._user=t.user,this._users.clear();for(const e of t.users)this._users.set(e.id,e);this._presence.clear();for(const e of t.presence)this._presence.set(e.user.id,e),this._users.set(e.user.id,e.user);this._users.set(t.user.id,t.user),this._threads.clear();for(const e of t.threads)this._threads.set(e.id,this.resolveThread(e));this._notifications=t.notifications,this._reactions.clear();for(const e of t.reactions){const s=this._reactions.get(e.targetId)??[];s.push(e),this._reactions.set(e.targetId,s)}this._activityLogs=[...t.activityLogs],this.emit("auth",t.user),this.emit("presence",this.presence),this.emit("threads",this.threads),this.emit("notifications",this._notifications),this.emit("reactions",null),this.emit("activity-logs",this._activityLogs);break;case"presence:join":this._presence.set(t.user.user.id,t.user),this._users.set(t.user.user.id,t.user.user),this.emit("presence",this.presence);break;case"presence:leave":this._presence.delete(t.userId),this._viewports.delete(t.userId),this._selections.delete(t.userId);for(const e of this._typing.values())e.delete(t.userId);this.emit("presence",this.presence);break;case"presence:update":{const e=this._presence.get(t.userId);e&&(e.status=t.status,this.emit("presence",this.presence));break}case"cursor:move":this.emit("cursor",{userId:t.userId,position:t.position});break;case"click:perform":this.emit("click",{userId:t.userId,position:t.position});break;case"thread:created":this._threads.set(t.thread.id,this.resolveThread(t.thread)),this.emit("threads",this.threads);break;case"comment:created":{const e=this._threads.get(t.threadId);e&&(e.comments.push(this.resolveComment(t.comment)),e.updatedAt=t.comment.createdAt,this.emit("threads",this.threads));break}case"comment:edited":{const e=this._threads.get(t.threadId);if(e){const s=e.comments.findIndex(r=>r.id===t.comment.id);s!==-1&&(e.comments[s]=this.resolveComment(t.comment)),this.emit("threads",this.threads)}break}case"comment:deleted":{const e=this._threads.get(t.threadId);e&&(e.comments=e.comments.filter(s=>s.id!==t.commentId),e.comments.length===0&&this._threads.delete(t.threadId),this.emit("threads",this.threads));break}case"thread:resolved":{const e=this._threads.get(t.threadId);e&&(e.resolved=t.resolved,this.emit("threads",this.threads));break}case"thread:deleted":this._threads.delete(t.threadId),this.emit("threads",this.threads);break;case"reaction:added":{const e=this._reactions.get(t.reaction.targetId)??[];e.push(t.reaction),this._reactions.set(t.reaction.targetId,e),this.emit("reactions",{targetId:t.reaction.targetId,reactions:e});break}case"reaction:removed":{const e=this._reactions.get(t.targetId);if(e){const s=e.filter(r=>r.id!==t.reactionId);this._reactions.set(t.targetId,s),this.emit("reactions",{targetId:t.targetId,reactions:s})}break}case"notification":this._notifications.unshift(t.notification),this.emit("notifications",this._notifications);break;case"typing:indicator":{this._typing.has(t.threadId)||this._typing.set(t.threadId,new Map),this._typing.get(t.threadId).set(t.userId,Date.now()),this.emit("typing",{threadId:t.threadId,userId:t.userId});break}case"viewport:update":{this._viewports.set(t.userId,{scrollX:t.scrollX,scrollY:t.scrollY,viewportWidth:t.viewportWidth,viewportHeight:t.viewportHeight,pageWidth:t.pageWidth,pageHeight:t.pageHeight}),this.emit("viewport",{userId:t.userId});break}case"selection:update":this._selections.set(t.userId,t.selection),this.emit("selection",{userId:t.userId,selection:t.selection});break;case"emoji:drop":this.emit("emoji-drop",{userId:t.userId,emoji:t.emoji,position:t.position});break;case"draw:stroke":this.emit("draw-stroke",{userId:t.userId,points:t.points,color:t.color,width:t.width});break;case"draw:clear":this.emit("draw-clear",{userId:t.userId});break;case"activity:logged":this._activityLogs.unshift(t.activityLog),this._activityLogs.length>100&&(this._activityLogs=this._activityLogs.slice(0,100)),this.emit("activity-logs",this._activityLogs);break;case"auth:error":this.emit("auth:error",t);break;case"error":this.emit("error",t);break}}reset(){this._user=null,this._config={...c.DEFAULT_ENV_CONFIG},this._users.clear(),this._presence.clear(),this._threads.clear(),this._reactions.clear(),this._notifications=[],this._activityLogs=[],this._typing.clear(),this._viewports.clear(),this._selections.clear()}}class m extends d{constructor(t){var s;super();i(this,"state");i(this,"connection");i(this,"config");i(this,"heartbeatTimer",null);i(this,"lastCursorSend",0);i(this,"pendingCursor",null);i(this,"cursorTimer",null);this.config=t,this.state=new u,this.state.baseUrl=(t.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const e=((s=t.endpoint)==null?void 0:s.replace(/^http/,"ws"))??void 0;this.connection=new l(e),this.connection.on("message",r=>{this.state.handleMessage(r),this.emit(r.type,r),r.type==="auth:error"&&this.connection.permanentDisconnect()}),this.connection.on("state",r=>{this.emit("connection",r),r==="connected"?(this.authenticate(),this.startHeartbeat()):r==="disconnected"&&this.stopHeartbeat()})}get connectionState(){return this.connection.state}connect(){this.connection.connect()}disconnect(){this.stopHeartbeat(),this.cursorTimer&&(clearTimeout(this.cursorTimer),this.cursorTimer=null),this.connection.disconnect(),this.state.reset()}destroy(){this.disconnect(),this.removeAll(),this.state.removeAll(),this.connection.removeAll()}authenticate(){this.send({type:"auth",apiKey:this.config.apiKey,token:this.config.token,room:this.config.room})}send(t){this.connection.send(t)}moveCursor(t){const e=Date.now();this.pendingCursor=t,e-this.lastCursorSend>=c.CURSOR_THROTTLE_MS?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},c.CURSOR_THROTTLE_MS))}flushCursor(){this.pendingCursor&&(this.send({type:"cursor:move",position:this.pendingCursor}),this.lastCursorSend=Date.now(),this.pendingCursor=null)}updatePresence(t){this.send({type:"presence:update",status:t})}startHeartbeat(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this.send({type:"presence:update",status:"online"})},c.PRESENCE_HEARTBEAT_MS))}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}createThread(t,e={}){const s=crypto.randomUUID();return this.send({type:"thread:create",id:s,body:t,mentions:e.mentions??[],position:e.position??null,attachmentIds:e.attachmentIds}),s}reply(t,e,s=[],r){const o=crypto.randomUUID();return this.send({type:"comment:create",threadId:t,id:o,body:e,mentions:s,attachmentIds:r}),o}editComment(t,e,s=[]){this.send({type:"comment:edit",commentId:t,body:e,mentions:s})}deleteComment(t){this.state.removeComment(t),this.send({type:"comment:delete",commentId:t})}resolveThread(t,e=!0){this.send({type:"thread:resolve",threadId:t,resolved:e})}addReaction(t,e,s){this.send({type:"reaction:add",targetId:t,targetType:e,emoji:s})}removeReaction(t){this.send({type:"reaction:remove",reactionId:t})}markRead(t){this.state.markNotificationRead(t),this.send({type:"notification:read",notificationId:t})}markAllRead(){this.state.markAllNotificationsRead(),this.send({type:"notification:read-all"})}performClick(t){this.send({type:"click:perform",position:t})}sendTyping(t){this.send({type:"typing:start",threadId:t})}updateViewport(t){this.send({type:"viewport:update",...t})}updateSelection(t){this.send({type:"selection:update",selection:t})}dropEmoji(t,e){this.send({type:"emoji:drop",emoji:t,position:e})}drawStroke(t,e,s){this.send({type:"draw:stroke",points:t,color:e,width:s})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(t){const e=typeof window<"u"?window.location.origin:"",s=(this.config.endpoint??e).replace(/^ws(s?):/,"http$1:"),r=new FormData;r.append("file",t);const o=await fetch(`${s}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:r});if(!o.ok){const p=await o.json().catch(()=>({error:"Upload failed"}));throw new Error(p.error??"Upload failed")}const a=await o.json();return a.url&&!a.url.startsWith("http")&&(a.url=`${s}${a.url}`),a.thumbnailUrl&&!a.thumbnailUrl.startsWith("http")&&(a.thumbnailUrl=`${s}${a.thumbnailUrl}`),a}setAppearOffline(t){t?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}}exports.Connection=l;exports.Emitter=d;exports.PulseClient=m;exports.StateManager=u;
@@ -1,19 +1,7 @@
1
- var u = Object.defineProperty;
2
- var p = (o, n, t) => n in o ? u(o, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[n] = t;
3
- var i = (o, n, t) => p(o, typeof n != "symbol" ? n + "" : n, t);
4
- const c = {
5
- allowImages: !0,
6
- allowAudio: !0,
7
- allowVideo: !0,
8
- maxFileSizeMb: 10,
9
- maxAttachmentsPerComment: 5,
10
- allowReactions: !0,
11
- allowDrawing: !0,
12
- allowMentions: !0,
13
- showCursors: !0,
14
- showPresence: !0,
15
- showTypingIndicators: !0
16
- }, _ = "ws://localhost:4567", l = 50, f = 3e4, m = 1e3, w = 3e4;
1
+ var p = Object.defineProperty;
2
+ var f = (h, n, t) => n in h ? p(h, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : h[n] = t;
3
+ var i = (h, n, t) => f(h, typeof n != "symbol" ? n + "" : n, t);
4
+ import { DEFAULT_ENDPOINT as m, RECONNECT_BASE_DELAY_MS as _, RECONNECT_MAX_DELAY_MS as w, DEFAULT_ENV_CONFIG as c, CURSOR_THROTTLE_MS as l, PRESENCE_HEARTBEAT_MS as v } from "@gamention/pulse-shared";
17
5
  class d {
18
6
  constructor() {
19
7
  i(this, "handlers", /* @__PURE__ */ new Map());
@@ -35,7 +23,7 @@ class d {
35
23
  this.handlers.clear();
36
24
  }
37
25
  }
38
- class v extends d {
26
+ class y extends d {
39
27
  constructor(t) {
40
28
  super();
41
29
  i(this, "ws", null);
@@ -43,17 +31,21 @@ class v extends d {
43
31
  i(this, "reconnectAttempt", 0);
44
32
  i(this, "reconnectTimer", null);
45
33
  i(this, "_state", "disconnected");
46
- this.endpoint = t ?? _;
34
+ i(this, "permanentlyClosed", !1);
35
+ this.endpoint = t ?? m;
47
36
  }
48
37
  get state() {
49
38
  return this._state;
50
39
  }
51
40
  connect() {
52
- this.ws || (this._state = "connecting", this.emit("state", this._state), this.ws = new WebSocket(this.endpoint), this.ws.addEventListener("open", () => {
41
+ this.ws || this.permanentlyClosed || (this._state = "connecting", this.emit("state", this._state), this.ws = new WebSocket(this.endpoint), this.ws.addEventListener("open", () => {
53
42
  this._state = "connected", this.reconnectAttempt = 0, this.emit("state", this._state);
54
43
  }), this.ws.addEventListener("message", (t) => {
55
- const e = JSON.parse(t.data);
56
- this.emit("message", e);
44
+ try {
45
+ const e = JSON.parse(t.data);
46
+ this.emit("message", e);
47
+ } catch {
48
+ }
57
49
  }), this.ws.addEventListener("close", () => {
58
50
  this.ws = null, this._state = "disconnected", this.emit("state", this._state), this.scheduleReconnect();
59
51
  }), this.ws.addEventListener("error", () => {
@@ -69,9 +61,13 @@ class v extends d {
69
61
  var e;
70
62
  ((e = this.ws) == null ? void 0 : e.readyState) === WebSocket.OPEN && this.ws.send(JSON.stringify(t));
71
63
  }
64
+ permanentDisconnect() {
65
+ this.permanentlyClosed = !0, this.disconnect();
66
+ }
72
67
  scheduleReconnect() {
68
+ if (this.permanentlyClosed) return;
73
69
  const t = Math.min(
74
- m * 2 ** this.reconnectAttempt,
70
+ _ * 2 ** this.reconnectAttempt,
75
71
  w
76
72
  );
77
73
  this.reconnectAttempt++, this.reconnectTimer = setTimeout(() => {
@@ -79,7 +75,7 @@ class v extends d {
79
75
  }, t);
80
76
  }
81
77
  }
82
- class y extends d {
78
+ class I extends d {
83
79
  constructor() {
84
80
  super(...arguments);
85
81
  /** HTTP base URL for resolving relative attachment paths (e.g. "http://localhost:4000"). */
@@ -105,7 +101,7 @@ class y extends d {
105
101
  /** Optimistically remove a comment from local state (before server round-trip). */
106
102
  removeComment(t) {
107
103
  for (const [e, s] of this._threads) {
108
- const r = s.comments.findIndex((a) => a.id === t);
104
+ const r = s.comments.findIndex((o) => o.id === t);
109
105
  if (r !== -1) {
110
106
  s.comments.splice(r, 1), s.comments.length === 0 && this._threads.delete(e), this.emit("threads", this.threads);
111
107
  return;
@@ -142,6 +138,10 @@ class y extends d {
142
138
  getUser(t) {
143
139
  return this._users.get(t);
144
140
  }
141
+ /** Get all known users (from presence + comment authors). */
142
+ get users() {
143
+ return [...this._users.values()];
144
+ }
145
145
  getReactions(t) {
146
146
  return this._reactions.get(t) ?? [];
147
147
  }
@@ -149,8 +149,8 @@ class y extends d {
149
149
  const e = this._typing.get(t);
150
150
  if (!e) return [];
151
151
  const s = Date.now(), r = [];
152
- for (const [a, h] of e)
153
- s - h < 3e3 && r.push(a);
152
+ for (const [o, a] of e)
153
+ s - a < 3e3 && r.push(o);
154
154
  return r;
155
155
  }
156
156
  get viewports() {
@@ -309,6 +309,9 @@ class y extends d {
309
309
  case "activity:logged":
310
310
  this._activityLogs.unshift(t.activityLog), this._activityLogs.length > 100 && (this._activityLogs = this._activityLogs.slice(0, 100)), this.emit("activity-logs", this._activityLogs);
311
311
  break;
312
+ case "auth:error":
313
+ this.emit("auth:error", t);
314
+ break;
312
315
  case "error":
313
316
  this.emit("error", t);
314
317
  break;
@@ -318,7 +321,7 @@ class y extends d {
318
321
  this._user = null, this._config = { ...c }, this._users.clear(), this._presence.clear(), this._threads.clear(), this._reactions.clear(), this._notifications = [], this._activityLogs = [], this._typing.clear(), this._viewports.clear(), this._selections.clear();
319
322
  }
320
323
  }
321
- class b extends d {
324
+ class T extends d {
322
325
  constructor(t) {
323
326
  var s;
324
327
  super();
@@ -329,10 +332,10 @@ class b extends d {
329
332
  i(this, "lastCursorSend", 0);
330
333
  i(this, "pendingCursor", null);
331
334
  i(this, "cursorTimer", null);
332
- this.config = t, this.state = new y(), this.state.baseUrl = (t.endpoint ?? "").replace(/^ws(s?):/, "http$1:").replace(/\/$/, "");
335
+ this.config = t, this.state = new I(), this.state.baseUrl = (t.endpoint ?? "").replace(/^ws(s?):/, "http$1:").replace(/\/$/, "");
333
336
  const e = ((s = t.endpoint) == null ? void 0 : s.replace(/^http/, "ws")) ?? void 0;
334
- this.connection = new v(e), this.connection.on("message", (r) => {
335
- this.state.handleMessage(r), this.emit(r.type, r);
337
+ this.connection = new y(e), this.connection.on("message", (r) => {
338
+ this.state.handleMessage(r), this.emit(r.type, r), r.type === "auth:error" && this.connection.permanentDisconnect();
336
339
  }), this.connection.on("state", (r) => {
337
340
  this.emit("connection", r), r === "connected" ? (this.authenticate(), this.startHeartbeat()) : r === "disconnected" && this.stopHeartbeat();
338
341
  });
@@ -345,7 +348,10 @@ class b extends d {
345
348
  this.connection.connect();
346
349
  }
347
350
  disconnect() {
348
- this.stopHeartbeat(), this.connection.disconnect(), this.state.reset();
351
+ this.stopHeartbeat(), this.cursorTimer && (clearTimeout(this.cursorTimer), this.cursorTimer = null), this.connection.disconnect(), this.state.reset();
352
+ }
353
+ destroy() {
354
+ this.disconnect(), this.removeAll(), this.state.removeAll(), this.connection.removeAll();
349
355
  }
350
356
  authenticate() {
351
357
  this.send({
@@ -373,9 +379,9 @@ class b extends d {
373
379
  this.send({ type: "presence:update", status: t });
374
380
  }
375
381
  startHeartbeat() {
376
- this.heartbeatTimer = setInterval(() => {
382
+ this.heartbeatTimer || (this.heartbeatTimer = setInterval(() => {
377
383
  this.send({ type: "presence:update", status: "online" });
378
- }, f);
384
+ }, v));
379
385
  }
380
386
  stopHeartbeat() {
381
387
  this.heartbeatTimer && (clearInterval(this.heartbeatTimer), this.heartbeatTimer = null);
@@ -393,8 +399,8 @@ class b extends d {
393
399
  }), s;
394
400
  }
395
401
  reply(t, e, s = [], r) {
396
- const a = crypto.randomUUID();
397
- return this.send({ type: "comment:create", threadId: t, id: a, body: e, mentions: s, attachmentIds: r }), a;
402
+ const o = crypto.randomUUID();
403
+ return this.send({ type: "comment:create", threadId: t, id: o, body: e, mentions: s, attachmentIds: r }), o;
398
404
  }
399
405
  editComment(t, e, s = []) {
400
406
  this.send({ type: "comment:edit", commentId: t, body: e, mentions: s });
@@ -448,22 +454,22 @@ class b extends d {
448
454
  }
449
455
  // ── File Upload ──
450
456
  async uploadFile(t) {
451
- const e = (this.config.endpoint ?? window.location.origin).replace(/^ws(s?):/, "http$1:"), s = new FormData();
452
- s.append("file", t);
453
- const r = await fetch(`${e}/api/v1/upload`, {
457
+ const e = typeof window < "u" ? window.location.origin : "", s = (this.config.endpoint ?? e).replace(/^ws(s?):/, "http$1:"), r = new FormData();
458
+ r.append("file", t);
459
+ const o = await fetch(`${s}/api/v1/upload`, {
454
460
  method: "POST",
455
461
  headers: {
456
462
  "X-Pulse-Key": this.config.apiKey,
457
463
  "X-Pulse-Token": this.config.token
458
464
  },
459
- body: s
465
+ body: r
460
466
  });
461
- if (!r.ok) {
462
- const h = await r.json().catch(() => ({ error: "Upload failed" }));
463
- throw new Error(h.error ?? "Upload failed");
467
+ if (!o.ok) {
468
+ const u = await o.json().catch(() => ({ error: "Upload failed" }));
469
+ throw new Error(u.error ?? "Upload failed");
464
470
  }
465
- const a = await r.json();
466
- return a.url && !a.url.startsWith("http") && (a.url = `${e}${a.url}`), a.thumbnailUrl && !a.thumbnailUrl.startsWith("http") && (a.thumbnailUrl = `${e}${a.thumbnailUrl}`), a;
471
+ const a = await o.json();
472
+ return a.url && !a.url.startsWith("http") && (a.url = `${s}${a.url}`), a.thumbnailUrl && !a.thumbnailUrl.startsWith("http") && (a.thumbnailUrl = `${s}${a.thumbnailUrl}`), a;
467
473
  }
468
474
  // ── Presence control ──
469
475
  setAppearOffline(t) {
@@ -471,8 +477,8 @@ class b extends d {
471
477
  }
472
478
  }
473
479
  export {
474
- v as Connection,
480
+ y as Connection,
475
481
  d as Emitter,
476
- b as PulseClient,
477
- y as StateManager
482
+ T as PulseClient,
483
+ I as StateManager
478
484
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamention/pulse-core",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "description": "Core client SDK for Pulse — WebSocket connection, state management, and API for real-time collaboration",
5
5
  "type": "module",
6
6
  "main": "./dist/pulse-core.cjs",
@@ -35,9 +35,10 @@
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  },
38
- "dependencies": {
39
- "@gamention/pulse-shared": "0.1.10"
38
+ "peerDependencies": {
39
+ "@gamention/pulse-shared": "0.1.11"
40
40
  },
41
+ "dependencies": {},
41
42
  "devDependencies": {
42
43
  "typescript": "^5.7.0",
43
44
  "vite": "^6.0.0",