@gamention/pulse-core 0.1.13 → 0.1.15
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 +5 -0
- package/dist/pulse-core.cjs +1 -1
- package/dist/pulse-core.js +42 -22
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ActivityLog } from '@gamention/pulse-shared';
|
|
2
2
|
import { ClientMessage } from '@gamention/pulse-shared';
|
|
3
3
|
import { CursorPosition } from '@gamention/pulse-shared';
|
|
4
|
+
import { EnvironmentConfig } from '@gamention/pulse-shared';
|
|
4
5
|
import { Notification as Notification_2 } from '@gamention/pulse-shared';
|
|
5
6
|
import { PinPosition } from '@gamention/pulse-shared';
|
|
6
7
|
import { PresenceUser } from '@gamention/pulse-shared';
|
|
@@ -95,6 +96,7 @@ export declare class StateManager extends Emitter {
|
|
|
95
96
|
/** HTTP base URL for resolving relative attachment paths (e.g. "http://localhost:4000"). */
|
|
96
97
|
baseUrl: string;
|
|
97
98
|
private _user;
|
|
99
|
+
private _config;
|
|
98
100
|
private _users;
|
|
99
101
|
private _presence;
|
|
100
102
|
private _threads;
|
|
@@ -105,6 +107,7 @@ export declare class StateManager extends Emitter {
|
|
|
105
107
|
private _viewports;
|
|
106
108
|
private _selections;
|
|
107
109
|
get user(): PulseUser | null;
|
|
110
|
+
get config(): EnvironmentConfig;
|
|
108
111
|
/** Optimistically remove a comment from local state (before server round-trip). */
|
|
109
112
|
removeComment(commentId: string): void;
|
|
110
113
|
get presence(): PresenceUser[];
|
|
@@ -117,6 +120,8 @@ export declare class StateManager extends Emitter {
|
|
|
117
120
|
markAllNotificationsRead(): void;
|
|
118
121
|
get activityLogs(): ActivityLog[];
|
|
119
122
|
getUser(userId: string): PulseUser | undefined;
|
|
123
|
+
/** Get all known users (from presence + comment authors). */
|
|
124
|
+
get users(): PulseUser[];
|
|
120
125
|
getReactions(targetId: string): Reaction[];
|
|
121
126
|
getTypingUsers(threadId: string): string[];
|
|
122
127
|
get viewports(): Map<string, ViewportInfo>;
|
package/dist/pulse-core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var f=(o,n,t)=>n in o?p(o,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[n]=t;var i=(o,n,t)=>f(o,typeof n!="symbol"?n+"":n,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _="ws://localhost:4567",d=50,m=3e4,w=1e3,v=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 l 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??_}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(w*2**this.reconnectAttempt,v);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}}class u extends h{constructor(){super(...arguments);i(this,"baseUrl","");i(this,"_user",null);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}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._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._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 y 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 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)}),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>=d?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},d))}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"})},m)}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=l;exports.Emitter=h;exports.PulseClient=y;exports.StateManager=u;
|
|
1
|
+
"use strict";var _=Object.defineProperty;var f=(o,n,t)=>n in o?_(o,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[n]=t;var i=(o,n,t)=>f(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)}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[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;
|
package/dist/pulse-core.js
CHANGED
|
@@ -1,8 +1,20 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var i = (o, n, t) =>
|
|
4
|
-
const
|
|
5
|
-
|
|
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;
|
|
17
|
+
class d {
|
|
6
18
|
constructor() {
|
|
7
19
|
i(this, "handlers", /* @__PURE__ */ new Map());
|
|
8
20
|
}
|
|
@@ -23,7 +35,7 @@ class c {
|
|
|
23
35
|
this.handlers.clear();
|
|
24
36
|
}
|
|
25
37
|
}
|
|
26
|
-
class
|
|
38
|
+
class v extends d {
|
|
27
39
|
constructor(t) {
|
|
28
40
|
super();
|
|
29
41
|
i(this, "ws", null);
|
|
@@ -31,7 +43,7 @@ class u extends c {
|
|
|
31
43
|
i(this, "reconnectAttempt", 0);
|
|
32
44
|
i(this, "reconnectTimer", null);
|
|
33
45
|
i(this, "_state", "disconnected");
|
|
34
|
-
this.endpoint = t ??
|
|
46
|
+
this.endpoint = t ?? _;
|
|
35
47
|
}
|
|
36
48
|
get state() {
|
|
37
49
|
return this._state;
|
|
@@ -59,20 +71,21 @@ class u extends c {
|
|
|
59
71
|
}
|
|
60
72
|
scheduleReconnect() {
|
|
61
73
|
const t = Math.min(
|
|
62
|
-
|
|
63
|
-
|
|
74
|
+
m * 2 ** this.reconnectAttempt,
|
|
75
|
+
w
|
|
64
76
|
);
|
|
65
77
|
this.reconnectAttempt++, this.reconnectTimer = setTimeout(() => {
|
|
66
78
|
this.reconnectTimer = null, this.connect();
|
|
67
79
|
}, t);
|
|
68
80
|
}
|
|
69
81
|
}
|
|
70
|
-
class
|
|
82
|
+
class y extends d {
|
|
71
83
|
constructor() {
|
|
72
84
|
super(...arguments);
|
|
73
85
|
/** HTTP base URL for resolving relative attachment paths (e.g. "http://localhost:4000"). */
|
|
74
86
|
i(this, "baseUrl", "");
|
|
75
87
|
i(this, "_user", null);
|
|
88
|
+
i(this, "_config", { ...c });
|
|
76
89
|
i(this, "_users", /* @__PURE__ */ new Map());
|
|
77
90
|
i(this, "_presence", /* @__PURE__ */ new Map());
|
|
78
91
|
i(this, "_threads", /* @__PURE__ */ new Map());
|
|
@@ -86,6 +99,9 @@ class _ extends c {
|
|
|
86
99
|
get user() {
|
|
87
100
|
return this._user;
|
|
88
101
|
}
|
|
102
|
+
get config() {
|
|
103
|
+
return this._config;
|
|
104
|
+
}
|
|
89
105
|
/** Optimistically remove a comment from local state (before server round-trip). */
|
|
90
106
|
removeComment(t) {
|
|
91
107
|
for (const [e, s] of this._threads) {
|
|
@@ -126,6 +142,10 @@ class _ extends c {
|
|
|
126
142
|
getUser(t) {
|
|
127
143
|
return this._users.get(t);
|
|
128
144
|
}
|
|
145
|
+
/** Get all known users (from presence + comment authors). */
|
|
146
|
+
get users() {
|
|
147
|
+
return [...this._users.values()];
|
|
148
|
+
}
|
|
129
149
|
getReactions(t) {
|
|
130
150
|
return this._reactions.get(t) ?? [];
|
|
131
151
|
}
|
|
@@ -169,7 +189,7 @@ class _ extends c {
|
|
|
169
189
|
handleMessage(t) {
|
|
170
190
|
switch (t.type) {
|
|
171
191
|
case "auth:ok":
|
|
172
|
-
this._user = t.user, this._users.clear();
|
|
192
|
+
this._config = t.config ?? { ...c }, this._user = t.user, this._users.clear();
|
|
173
193
|
for (const e of t.users) this._users.set(e.id, e);
|
|
174
194
|
this._presence.clear();
|
|
175
195
|
for (const e of t.presence)
|
|
@@ -299,10 +319,10 @@ class _ extends c {
|
|
|
299
319
|
}
|
|
300
320
|
}
|
|
301
321
|
reset() {
|
|
302
|
-
this._user = null, 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();
|
|
322
|
+
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();
|
|
303
323
|
}
|
|
304
324
|
}
|
|
305
|
-
class
|
|
325
|
+
class b extends d {
|
|
306
326
|
constructor(t) {
|
|
307
327
|
var s;
|
|
308
328
|
super();
|
|
@@ -313,9 +333,9 @@ class m extends c {
|
|
|
313
333
|
i(this, "lastCursorSend", 0);
|
|
314
334
|
i(this, "pendingCursor", null);
|
|
315
335
|
i(this, "cursorTimer", null);
|
|
316
|
-
this.config = t, this.state = new
|
|
336
|
+
this.config = t, this.state = new y(), this.state.baseUrl = (t.endpoint ?? "").replace(/^ws(s?):/, "http$1:").replace(/\/$/, "");
|
|
317
337
|
const e = ((s = t.endpoint) == null ? void 0 : s.replace(/^http/, "ws")) ?? void 0;
|
|
318
|
-
this.connection = new
|
|
338
|
+
this.connection = new v(e), this.connection.on("message", (r) => {
|
|
319
339
|
this.state.handleMessage(r), this.emit(r.type, r);
|
|
320
340
|
}), this.connection.on("state", (r) => {
|
|
321
341
|
this.emit("connection", r), r === "connected" ? (this.authenticate(), this.startHeartbeat()) : r === "disconnected" && this.stopHeartbeat();
|
|
@@ -345,9 +365,9 @@ class m extends c {
|
|
|
345
365
|
// ── Cursors ──
|
|
346
366
|
moveCursor(t) {
|
|
347
367
|
const e = Date.now();
|
|
348
|
-
this.pendingCursor = t, e - this.lastCursorSend >=
|
|
368
|
+
this.pendingCursor = t, e - this.lastCursorSend >= l ? this.flushCursor() : this.cursorTimer || (this.cursorTimer = setTimeout(() => {
|
|
349
369
|
this.cursorTimer = null, this.flushCursor();
|
|
350
|
-
},
|
|
370
|
+
}, l));
|
|
351
371
|
}
|
|
352
372
|
flushCursor() {
|
|
353
373
|
this.pendingCursor && (this.send({ type: "cursor:move", position: this.pendingCursor }), this.lastCursorSend = Date.now(), this.pendingCursor = null);
|
|
@@ -359,7 +379,7 @@ class m extends c {
|
|
|
359
379
|
startHeartbeat() {
|
|
360
380
|
this.heartbeatTimer = setInterval(() => {
|
|
361
381
|
this.send({ type: "presence:update", status: "online" });
|
|
362
|
-
},
|
|
382
|
+
}, f);
|
|
363
383
|
}
|
|
364
384
|
stopHeartbeat() {
|
|
365
385
|
this.heartbeatTimer && (clearInterval(this.heartbeatTimer), this.heartbeatTimer = null);
|
|
@@ -455,8 +475,8 @@ class m extends c {
|
|
|
455
475
|
}
|
|
456
476
|
}
|
|
457
477
|
export {
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
478
|
+
v as Connection,
|
|
479
|
+
d as Emitter,
|
|
480
|
+
b as PulseClient,
|
|
481
|
+
y as StateManager
|
|
462
482
|
};
|
package/package.json
CHANGED