@gamention/pulse-core 0.1.15 → 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 +3 -0
- package/dist/pulse-core.cjs +1 -1
- package/dist/pulse-core.js +49 -47
- package/package.json +4 -3
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;
|
package/dist/pulse-core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
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;
|
package/dist/pulse-core.js
CHANGED
|
@@ -1,19 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var i = (
|
|
4
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
56
|
-
|
|
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
|
-
|
|
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
|
|
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((
|
|
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;
|
|
@@ -153,8 +149,8 @@ class y extends d {
|
|
|
153
149
|
const e = this._typing.get(t);
|
|
154
150
|
if (!e) return [];
|
|
155
151
|
const s = Date.now(), r = [];
|
|
156
|
-
for (const [
|
|
157
|
-
s -
|
|
152
|
+
for (const [o, a] of e)
|
|
153
|
+
s - a < 3e3 && r.push(o);
|
|
158
154
|
return r;
|
|
159
155
|
}
|
|
160
156
|
get viewports() {
|
|
@@ -313,6 +309,9 @@ class y extends d {
|
|
|
313
309
|
case "activity:logged":
|
|
314
310
|
this._activityLogs.unshift(t.activityLog), this._activityLogs.length > 100 && (this._activityLogs = this._activityLogs.slice(0, 100)), this.emit("activity-logs", this._activityLogs);
|
|
315
311
|
break;
|
|
312
|
+
case "auth:error":
|
|
313
|
+
this.emit("auth:error", t);
|
|
314
|
+
break;
|
|
316
315
|
case "error":
|
|
317
316
|
this.emit("error", t);
|
|
318
317
|
break;
|
|
@@ -322,7 +321,7 @@ class y extends d {
|
|
|
322
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();
|
|
323
322
|
}
|
|
324
323
|
}
|
|
325
|
-
class
|
|
324
|
+
class T extends d {
|
|
326
325
|
constructor(t) {
|
|
327
326
|
var s;
|
|
328
327
|
super();
|
|
@@ -333,10 +332,10 @@ class b extends d {
|
|
|
333
332
|
i(this, "lastCursorSend", 0);
|
|
334
333
|
i(this, "pendingCursor", null);
|
|
335
334
|
i(this, "cursorTimer", null);
|
|
336
|
-
this.config = t, this.state = new
|
|
335
|
+
this.config = t, this.state = new I(), this.state.baseUrl = (t.endpoint ?? "").replace(/^ws(s?):/, "http$1:").replace(/\/$/, "");
|
|
337
336
|
const e = ((s = t.endpoint) == null ? void 0 : s.replace(/^http/, "ws")) ?? void 0;
|
|
338
|
-
this.connection = new
|
|
339
|
-
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();
|
|
340
339
|
}), this.connection.on("state", (r) => {
|
|
341
340
|
this.emit("connection", r), r === "connected" ? (this.authenticate(), this.startHeartbeat()) : r === "disconnected" && this.stopHeartbeat();
|
|
342
341
|
});
|
|
@@ -349,7 +348,10 @@ class b extends d {
|
|
|
349
348
|
this.connection.connect();
|
|
350
349
|
}
|
|
351
350
|
disconnect() {
|
|
352
|
-
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();
|
|
353
355
|
}
|
|
354
356
|
authenticate() {
|
|
355
357
|
this.send({
|
|
@@ -377,9 +379,9 @@ class b extends d {
|
|
|
377
379
|
this.send({ type: "presence:update", status: t });
|
|
378
380
|
}
|
|
379
381
|
startHeartbeat() {
|
|
380
|
-
this.heartbeatTimer = setInterval(() => {
|
|
382
|
+
this.heartbeatTimer || (this.heartbeatTimer = setInterval(() => {
|
|
381
383
|
this.send({ type: "presence:update", status: "online" });
|
|
382
|
-
},
|
|
384
|
+
}, v));
|
|
383
385
|
}
|
|
384
386
|
stopHeartbeat() {
|
|
385
387
|
this.heartbeatTimer && (clearInterval(this.heartbeatTimer), this.heartbeatTimer = null);
|
|
@@ -397,8 +399,8 @@ class b extends d {
|
|
|
397
399
|
}), s;
|
|
398
400
|
}
|
|
399
401
|
reply(t, e, s = [], r) {
|
|
400
|
-
const
|
|
401
|
-
return this.send({ type: "comment:create", threadId: t, id:
|
|
402
|
+
const o = crypto.randomUUID();
|
|
403
|
+
return this.send({ type: "comment:create", threadId: t, id: o, body: e, mentions: s, attachmentIds: r }), o;
|
|
402
404
|
}
|
|
403
405
|
editComment(t, e, s = []) {
|
|
404
406
|
this.send({ type: "comment:edit", commentId: t, body: e, mentions: s });
|
|
@@ -452,22 +454,22 @@ class b extends d {
|
|
|
452
454
|
}
|
|
453
455
|
// ── File Upload ──
|
|
454
456
|
async uploadFile(t) {
|
|
455
|
-
const e = (this.config.endpoint ??
|
|
456
|
-
|
|
457
|
-
const
|
|
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`, {
|
|
458
460
|
method: "POST",
|
|
459
461
|
headers: {
|
|
460
462
|
"X-Pulse-Key": this.config.apiKey,
|
|
461
463
|
"X-Pulse-Token": this.config.token
|
|
462
464
|
},
|
|
463
|
-
body:
|
|
465
|
+
body: r
|
|
464
466
|
});
|
|
465
|
-
if (!
|
|
466
|
-
const
|
|
467
|
-
throw new Error(
|
|
467
|
+
if (!o.ok) {
|
|
468
|
+
const u = await o.json().catch(() => ({ error: "Upload failed" }));
|
|
469
|
+
throw new Error(u.error ?? "Upload failed");
|
|
468
470
|
}
|
|
469
|
-
const a = await
|
|
470
|
-
return a.url && !a.url.startsWith("http") && (a.url = `${
|
|
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;
|
|
471
473
|
}
|
|
472
474
|
// ── Presence control ──
|
|
473
475
|
setAppearOffline(t) {
|
|
@@ -475,8 +477,8 @@ class b extends d {
|
|
|
475
477
|
}
|
|
476
478
|
}
|
|
477
479
|
export {
|
|
478
|
-
|
|
480
|
+
y as Connection,
|
|
479
481
|
d as Emitter,
|
|
480
|
-
|
|
481
|
-
|
|
482
|
+
T as PulseClient,
|
|
483
|
+
I as StateManager
|
|
482
484
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gamention/pulse-core",
|
|
3
|
-
"version": "0.1.
|
|
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
|
-
"
|
|
39
|
-
"@gamention/pulse-shared": "0.1.
|
|
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",
|