@eleven-am/pondsocket 0.1.16 → 0.1.17

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.
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Channel = void 0;
4
- const channelEngine_1 = require("../server/channel/channelEngine");
5
- const endpoint_1 = require("../server/endpoint/endpoint");
6
- const presenceEngine_1 = require("../server/presence/presenceEngine");
4
+ const enums_1 = require("../enums");
7
5
  const subjectUtils_1 = require("../server/utils/subjectUtils");
8
6
  class Channel {
9
7
  constructor(publisher, clientState, name, receiver, params = {}) {
@@ -26,9 +24,9 @@ class Channel {
26
24
  throw new Error('This channel has been closed');
27
25
  }
28
26
  const joinMessage = {
29
- action: endpoint_1.ClientActions.JOIN_CHANNEL,
27
+ action: enums_1.ClientActions.JOIN_CHANNEL,
30
28
  channelName: this._name,
31
- event: endpoint_1.ClientActions.JOIN_CHANNEL,
29
+ event: enums_1.ClientActions.JOIN_CHANNEL,
32
30
  payload: this._joinParams,
33
31
  };
34
32
  this._publish(joinMessage);
@@ -38,9 +36,9 @@ class Channel {
38
36
  */
39
37
  leave() {
40
38
  const leaveMessage = {
41
- action: endpoint_1.ClientActions.LEAVE_CHANNEL,
39
+ action: enums_1.ClientActions.LEAVE_CHANNEL,
42
40
  channelName: this._name,
43
- event: endpoint_1.ClientActions.LEAVE_CHANNEL,
41
+ event: enums_1.ClientActions.LEAVE_CHANNEL,
44
42
  payload: {},
45
43
  };
46
44
  this._publish(leaveMessage);
@@ -54,7 +52,7 @@ class Channel {
54
52
  */
55
53
  onMessage(event, callback) {
56
54
  return this._receiver.subscribe((data) => {
57
- if (data.action === channelEngine_1.ServerActions.BROADCAST && data.event === event && data.channelName === this._name) {
55
+ if (data.action === enums_1.ServerActions.BROADCAST && data.event === event && data.channelName === this._name) {
58
56
  return callback(data.payload);
59
57
  }
60
58
  });
@@ -74,7 +72,7 @@ class Channel {
74
72
  */
75
73
  onJoin(callback) {
76
74
  return this._receiver.subscribe((data) => {
77
- if (data.action === channelEngine_1.ServerActions.PRESENCE && data.event === presenceEngine_1.PresenceEventTypes.JOIN && data.channelName === this._name) {
75
+ if (data.action === enums_1.ServerActions.PRESENCE && data.event === enums_1.PresenceEventTypes.JOIN && data.channelName === this._name) {
78
76
  return callback(data.payload.changed);
79
77
  }
80
78
  });
@@ -85,7 +83,7 @@ class Channel {
85
83
  */
86
84
  onLeave(callback) {
87
85
  return this._receiver.subscribe((data) => {
88
- if (data.action === channelEngine_1.ServerActions.PRESENCE && data.event === presenceEngine_1.PresenceEventTypes.LEAVE && data.channelName === this._name) {
86
+ if (data.action === enums_1.ServerActions.PRESENCE && data.event === enums_1.PresenceEventTypes.LEAVE && data.channelName === this._name) {
89
87
  return callback(data.payload.changed);
90
88
  }
91
89
  });
@@ -96,7 +94,7 @@ class Channel {
96
94
  */
97
95
  onPresenceChange(callback) {
98
96
  return this._receiver.subscribe((data) => {
99
- if (data.action === channelEngine_1.ServerActions.PRESENCE && data.event === presenceEngine_1.PresenceEventTypes.UPDATE && data.channelName === this._name) {
97
+ if (data.action === enums_1.ServerActions.PRESENCE && data.event === enums_1.PresenceEventTypes.UPDATE && data.channelName === this._name) {
100
98
  return callback(data.payload);
101
99
  }
102
100
  });
@@ -155,7 +153,7 @@ class Channel {
155
153
  }
156
154
  _send(event, payload, receivers = 'all_users') {
157
155
  const message = {
158
- action: endpoint_1.ClientActions.BROADCAST,
156
+ action: enums_1.ClientActions.BROADCAST,
159
157
  channelName: this._name,
160
158
  event,
161
159
  payload,
@@ -174,9 +172,9 @@ class Channel {
174
172
  const unsubStateChange = this._clientState.subscribe((state) => {
175
173
  if (state === 'OPEN') {
176
174
  const joinMessage = {
177
- action: endpoint_1.ClientActions.JOIN_CHANNEL,
175
+ action: enums_1.ClientActions.JOIN_CHANNEL,
178
176
  channelName: this._name,
179
- event: endpoint_1.ClientActions.JOIN_CHANNEL,
177
+ event: enums_1.ClientActions.JOIN_CHANNEL,
180
178
  payload: this._joinParams,
181
179
  };
182
180
  this._publisher(joinMessage);
@@ -187,7 +185,7 @@ class Channel {
187
185
  }
188
186
  });
189
187
  const unsubPresence = this._receiver.subscribe((data) => {
190
- if (data.action === channelEngine_1.ServerActions.PRESENCE && data.channelName === this._name) {
188
+ if (data.action === enums_1.ServerActions.PRESENCE && data.channelName === this._name) {
191
189
  this._presence.publish(data.payload.presence);
192
190
  }
193
191
  });
@@ -0,0 +1,4 @@
1
+ // eslint-disable-next-line import/no-unresolved
2
+ import { PondSocketClient } from './types';
3
+
4
+ export default PondSocketClient;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const channel_1 = require("./channel");
4
- const subjectUtils_1 = require("../server/utils/subjectUtils");
3
+ const channel_1 = require("./client/channel");
4
+ const subjectUtils_1 = require("./server/utils/subjectUtils");
5
5
  class PondClient {
6
6
  constructor(endpoint, params = {}) {
7
7
  let address;
@@ -0,0 +1,19 @@
1
+
2
+ export enum PresenceEventTypes {
3
+ JOIN = 'JOIN',
4
+ LEAVE = 'LEAVE',
5
+ UPDATE = 'UPDATE'
6
+ }
7
+
8
+ export enum ServerActions {
9
+ PRESENCE = 'PRESENCE',
10
+ SYSTEM = 'SYSTEM',
11
+ BROADCAST = 'BROADCAST',
12
+ ERROR = 'ERROR',
13
+ }
14
+
15
+ export enum ClientActions {
16
+ JOIN_CHANNEL = 'JOIN_CHANNEL',
17
+ LEAVE_CHANNEL = 'LEAVE_CHANNEL',
18
+ BROADCAST = 'BROADCAST',
19
+ }
package/dist/enums.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientActions = exports.ServerActions = exports.PresenceEventTypes = void 0;
4
+ var PresenceEventTypes;
5
+ (function (PresenceEventTypes) {
6
+ PresenceEventTypes["JOIN"] = "JOIN";
7
+ PresenceEventTypes["LEAVE"] = "LEAVE";
8
+ PresenceEventTypes["UPDATE"] = "UPDATE";
9
+ })(PresenceEventTypes = exports.PresenceEventTypes || (exports.PresenceEventTypes = {}));
10
+ var ServerActions;
11
+ (function (ServerActions) {
12
+ ServerActions["PRESENCE"] = "PRESENCE";
13
+ ServerActions["SYSTEM"] = "SYSTEM";
14
+ ServerActions["BROADCAST"] = "BROADCAST";
15
+ ServerActions["ERROR"] = "ERROR";
16
+ })(ServerActions = exports.ServerActions || (exports.ServerActions = {}));
17
+ var ClientActions;
18
+ (function (ClientActions) {
19
+ ClientActions["JOIN_CHANNEL"] = "JOIN_CHANNEL";
20
+ ClientActions["LEAVE_CHANNEL"] = "LEAVE_CHANNEL";
21
+ ClientActions["BROADCAST"] = "BROADCAST";
22
+ })(ClientActions = exports.ClientActions || (exports.ClientActions = {}));
@@ -0,0 +1,3 @@
1
+ import { PondSocketFromExpress } from './types';
2
+
3
+ export default PondSocketFromExpress;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const http_1 = require("http");
4
- const pondSocket_1 = require("../server/server/pondSocket");
4
+ const pondSocket_1 = require("./server/server/pondSocket");
5
5
  /**
6
6
  * @desc Creates a pond socket server
7
7
  * @param app - The Express app to be used by the server
package/dist/index.d.ts CHANGED
@@ -1,340 +1,3 @@
1
- import { Server as HTTPServer, IncomingMessage, IncomingHttpHeaders } from 'http';
2
- import internal from 'stream';
3
-
4
- // eslint-disable-next-line import/no-unresolved
5
- import { Express } from 'express';
6
- import { WebSocketServer, WebSocket } from 'ws';
7
-
8
- export type PondPath = string | RegExp;
9
- type NextFunction = () => void;
10
- export type JoinParams = Record<string, any>;
11
- type PondAssigns = Record<string, any>;
12
- export type PondMessage = Record<string, any>;
13
- export type PondPresence = Record<string, any>;
14
- export type EndpointHandler = (req: IncomingConnection, res: ConnectionResponse) => void;
15
- type SocketCache = Pick<RequestCache, 'socket' | 'clientId' | 'assigns'>;
16
- type AuthorizeMiddleware = (request: JoinRequest, response: JoinResponse) => void | Promise<void>;
17
- type SocketMiddlewareFunction = (req: IncomingMessage, socket: internal.Duplex, head: Buffer, next: NextFunction) => void;
18
-
19
- interface RequestCache {
20
- clientId: string;
21
- socket: WebSocket;
22
- channelName: string;
23
- assigns: PondAssigns;
24
- joinParams: Record<string, any>;
25
- params: Record<string, string>;
26
- query: Record<string, string>;
27
- }
28
- interface UserAssigns {
29
- [userId: string]: PondAssigns;
30
- }
31
- interface UserData {
32
- assigns: PondAssigns;
33
- presence: PondPresence;
34
- id: string;
35
- }
36
- interface EventObject {
37
- event: string;
38
- params: Record<string, string>;
39
- query: Record<string, string>;
40
- payload: PondMessage;
41
- }
42
- interface IncomingConnection {
43
- id: string;
44
- params: Record<string, string>;
45
- query: Record<string, string>;
46
- headers: IncomingHttpHeaders;
47
- address: string;
48
- }
49
- interface UserPresences {
50
- [userId: string]: PondPresence;
51
- }
52
-
53
- declare class AbstractRequest {
54
- get event (): EventObject;
55
-
56
- get channelNme (): string;
57
-
58
- get assigns (): UserAssigns;
59
-
60
- get presence (): UserPresences;
61
- }
62
-
63
- declare class EventRequest extends AbstractRequest {
64
- get user (): UserData;
65
- }
66
-
67
- declare class EventResponse {
68
- /**
69
- * @desc Checks if the response has been sent
70
- */
71
- get responseSent (): boolean;
72
-
73
- /**
74
- * @desc Accepts the request and optionally assigns data to the client
75
- * @param assigns - the data to assign to the client
76
- */
77
- accept (assigns?: PondAssigns): EventResponse;
78
-
79
- /**
80
- * @desc Rejects the request and optionally assigns data to the client
81
- * @param message - the error message
82
- * @param errorCode - the error code
83
- * @param assigns - the data to assign to the client
84
- */
85
- reject (message?: string, errorCode?: number, assigns?: PondAssigns): EventResponse;
86
-
87
- /**
88
- * @desc Emits a direct message to the client
89
- * @param event - the event name
90
- * @param payload - the payload to send
91
- * @param assigns - the data to assign to the client
92
- */
93
- send (event: string, payload: PondMessage, assigns?: PondAssigns): EventResponse;
94
-
95
- /**
96
- * @desc Sends a message to all clients in the channel
97
- * @param event - the event to send
98
- * @param payload - the payload to send
99
- */
100
- broadcast (event: string, payload: PondMessage): EventResponse;
101
-
102
- /**
103
- * @desc Sends a message to all clients in the channel except the client making the request
104
- * @param event - the event to send
105
- * @param payload - the payload to send
106
- */
107
- broadcastFromUser (event: string, payload: PondMessage): EventResponse;
108
-
109
- /**
110
- * @desc Sends a message to a set of clients in the channel
111
- * @param event - the event to send
112
- * @param payload - the payload to send
113
- * @param userIds - the ids of the clients to send the message to
114
- */
115
- sendToUsers (event: string, payload: PondMessage, userIds: string[]): EventResponse;
116
-
117
- /**
118
- * @desc Tracks a user's presence in the channel
119
- * @param presence - the initial presence data
120
- * @param userId - the id of the user to track
121
- */
122
- trackPresence (presence: PondPresence, userId?: string): EventResponse;
123
-
124
- /**
125
- * @desc Updates a user's presence in the channel
126
- * @param presence - the updated presence data
127
- * @param userId - the id of the user to update
128
- */
129
- updatePresence (presence: PondPresence, userId?: string): EventResponse;
130
-
131
- /**
132
- * @desc Removes a user's presence from the channel
133
- * @param userId - the id of the user to remove
134
- */
135
- unTrackPresence (userId?: string): EventResponse;
136
-
137
- /**
138
- * @desc Evicts a user from the channel
139
- * @param reason - the reason for the eviction
140
- * @param userId - the id of the user to evict,
141
- */
142
- evictUser (reason: string, userId?: string): void;
143
-
144
- /**
145
- * @desc Closes the channel from the server side for all clients
146
- * @param reason - the reason for closing the channel
147
- */
148
- closeChannel (reason: string): void;
149
- }
150
-
151
- declare class JoinRequest extends AbstractRequest {
152
- get joinParams (): JoinParams;
153
-
154
- get user (): UserData;
155
-
156
- get event (): EventObject;
157
- }
158
-
159
- declare class JoinResponse {
160
- get responseSent (): boolean;
161
-
162
- /**
163
- * @desc Accepts the request and optionally assigns data to the client
164
- * @param assigns - the data to assign to the client
165
- */
166
- accept (assigns?: PondAssigns): JoinResponse;
167
-
168
- /**
169
- * @desc Rejects the request and optionally assigns data to the client
170
- * @param message - the error message
171
- * @param errorCode - the error code
172
- */
173
- reject (message?: string, errorCode?: number): JoinResponse;
174
-
175
- /**
176
- * @desc Emits a direct message to the client
177
- * @param event - the event name
178
- * @param payload - the payload to send
179
- * @param assigns - the data to assign to the client
180
- */
181
- send (event: string, payload: PondMessage, assigns?: PondAssigns): this;
182
-
183
- /**
184
- * @desc Emits a message to all clients in the channel
185
- * @param event - the event name
186
- * @param payload - the payload to send
187
- */
188
- broadcast (event: string, payload: PondMessage): JoinResponse;
189
-
190
- /**
191
- * @desc Emits a message to all clients in the channel except the sender
192
- * @param event - the event name
193
- * @param payload - the payload to send
194
- */
195
- broadcastFromUser (event: string, payload: PondMessage): JoinResponse;
196
-
197
- /**
198
- * @desc Emits a message to a specific set of clients
199
- * @param event - the event name
200
- * @param payload - the payload to send
201
- * @param userIds - the ids of the clients to send the message to
202
- */
203
- sendToUsers (event: string, payload: PondMessage, userIds: string[]): JoinResponse;
204
-
205
- /**
206
- * @desc tracks the presence of a client
207
- * @param presence - the presence data to track
208
- */
209
- trackPresence (presence: PondPresence): JoinResponse;
210
- }
211
-
212
- declare class PondChannel {
213
- /**
214
- * @desc Authorize a user to join a channel
215
- * @param handler - The handler to authorize the user
216
- * @example
217
- * const pond = new PondChannelEngine();
218
- * pond.onJoinRequest((request, response) => {
219
- * if (request.event.assigns.admin)
220
- * response.accept();
221
- * else
222
- * response.reject('You are not an admin', 403);
223
- * });
224
- */
225
- onJoinRequest (handler: AuthorizeMiddleware): void;
226
-
227
- /**
228
- * @desc Handles an event request made by a user
229
- * @param event - The event to listen for
230
- * @param handler - The handler to execute when the event is received
231
- * @example
232
- * pond.onEvent('echo', (request, response) => {
233
- * response.send('echo', {
234
- * message: request.payload,
235
- * });
236
- * });
237
- */
238
- onEvent (event: PondPath, handler: (request: EventRequest, response: EventResponse) => void | Promise<void>): void;
239
- }
240
-
241
- declare class ConnectionResponse {
242
- /**
243
- * @desc Accepts the request and optionally assigns data to the client
244
- * @param assigns - the data to assign to the client
245
- */
246
- accept (assigns?: PondAssigns): void;
247
-
248
- /**
249
- * @desc Rejects the request with the given error message
250
- * @param message - the error message
251
- * @param errorCode - the error code
252
- */
253
- reject (message?: string, errorCode?: number): void;
254
-
255
- /**
256
- * @desc Emits a direct message to the client
257
- * @param event - the event name
258
- * @param payload - the payload to send
259
- * @param assigns - the data to assign to the client
260
- */
261
- send (event: string, payload: PondMessage, assigns?: PondAssigns): void;
262
- }
263
-
264
- export declare class Endpoint {
265
- /**
266
- * @desc Adds a new PondChannel to this path on this endpoint
267
- * @param path - The path to add the channel to
268
- * @param channel - The channel to add
269
- *
270
- * @example
271
- * endpoint.useChannel('/chat', pondChannelInstance);
272
- */
273
- useChannel (path: PondPath, channel: PondChannel): void;
274
-
275
- /**
276
- * @desc List all clients connected to this endpoint
277
- */
278
- listConnections (): string[];
279
-
280
- /**
281
- * @desc Gets all clients connected to this endpoint
282
- */
283
- getClients (): SocketCache[];
284
-
285
- /**
286
- * @desc Broadcasts a message to all clients connected to this endpoint
287
- * @param event - The event to broadcast
288
- * @param payload - The payload to broadcast
289
- */
290
- broadcast (event: string, payload: PondMessage): void;
291
-
292
- /**
293
- * @desc Closes specific clients connected to this endpoint
294
- * @param clientIds - The id for the client / clients to close
295
- */
296
- closeConnection (clientIds: string | string[]): void;
297
- }
298
-
299
- declare class PondSocket {
300
- constructor (server?: HTTPServer, socketServer?: WebSocketServer);
301
-
302
- /**
303
- * @desc Specifies the port to listen on
304
- * @param port - the port to listen on
305
- * @param callback - the callback to call when the server is listening
306
- */
307
- listen (port: number, callback: (port?: number) => void): HTTPServer<typeof IncomingMessage, typeof import('http').ServerResponse>;
308
-
309
- /**
310
- * @desc Closes the server
311
- * @param callback - the callback to call when the server is closed
312
- */
313
- close (callback?: () => void): HTTPServer<typeof IncomingMessage, typeof import('http').ServerResponse>;
314
-
315
- /**
316
- * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
317
- * @param path - the pattern to accept || can also be a regex
318
- * @param handler - the handler function to authenticate the socket
319
- * @example
320
- * const endpoint = pond.createEndpoint('/api/socket', (req, res) => {
321
- * const token = req.query.token;
322
- * if (!token)
323
- * return res.reject('No token provided');
324
- * res.accept({
325
- * assign: {
326
- * token
327
- * }
328
- * });
329
- * })
330
- */
331
- createEndpoint (path: PondPath, handler: EndpointHandler): Endpoint;
332
-
333
- /**
334
- * @desc Adds a middleware function to the socket server
335
- * @param middleware - the middleware function to add
336
- */
337
- use (middleware: SocketMiddlewareFunction): void;
338
- }
1
+ import { PondSocket } from './types';
339
2
 
340
3
  export default PondSocket;
@@ -0,0 +1,522 @@
1
+ import { Server as HTTPServer, IncomingMessage, IncomingHttpHeaders } from 'http';
2
+ import internal from 'stream';
3
+
4
+ // eslint-disable-next-line import/no-unresolved
5
+ import { Express } from 'express';
6
+ import { WebSocketServer, WebSocket } from 'ws';
7
+
8
+ import { ClientActions, PresenceEventTypes } from './enums.d';
9
+
10
+ export type PondPath = string | RegExp;
11
+ type NextFunction = () => void;
12
+ export type JoinParams = Record<string, any>;
13
+ type PondAssigns = Record<string, any>;
14
+ export type PondMessage = Record<string, any>;
15
+ export type PondPresence = Record<string, any>;
16
+ export type EndpointHandler = (req: IncomingConnection, res: ConnectionResponse) => void;
17
+ type SocketCache = Pick<RequestCache, 'socket' | 'clientId' | 'assigns'>;
18
+ type AuthorizeMiddleware = (request: JoinRequest, response: JoinResponse) => void | Promise<void>;
19
+ type SocketMiddlewareFunction = (req: IncomingMessage, socket: internal.Duplex, head: Buffer, next: NextFunction) => void;
20
+ export type ChannelReceivers = 'all_users' | 'all_except_sender' | string[];
21
+ export type ChannelSenders = 'channel' | string;
22
+ export type ChannelEvent = Event | PresenceEvent;
23
+
24
+ interface Event {
25
+ action: 'SYSTEM' | 'BROADCAST' | 'ERROR';
26
+ event: string;
27
+ payload: PondMessage;
28
+ channelName: string;
29
+ }
30
+ export interface ClientMessage {
31
+ action: ClientActions;
32
+ channelName: string;
33
+ event: string;
34
+ payload: Record<string, any>;
35
+ addresses?: ChannelReceivers;
36
+ }
37
+ interface PresenceEvent {
38
+ action: 'PRESENCE';
39
+ event: PresenceEventTypes;
40
+ channelName: string;
41
+ payload: PresencePayload;
42
+ }
43
+ interface RequestCache {
44
+ clientId: string;
45
+ socket: WebSocket;
46
+ channelName: string;
47
+ assigns: PondAssigns;
48
+ joinParams: Record<string, any>;
49
+ params: Record<string, string>;
50
+ query: Record<string, string>;
51
+ }
52
+ interface UserAssigns {
53
+ [userId: string]: PondAssigns;
54
+ }
55
+ interface UserData {
56
+ assigns: PondAssigns;
57
+ presence: PondPresence;
58
+ id: string;
59
+ }
60
+ interface EventObject {
61
+ event: string;
62
+ params: Record<string, string>;
63
+ query: Record<string, string>;
64
+ payload: PondMessage;
65
+ }
66
+ interface IncomingConnection {
67
+ id: string;
68
+ params: Record<string, string>;
69
+ query: Record<string, string>;
70
+ headers: IncomingHttpHeaders;
71
+ address: string;
72
+ }
73
+ interface UserPresences {
74
+ [userId: string]: PondPresence;
75
+ }
76
+
77
+ declare global {
78
+ // eslint-disable-next-line @typescript-eslint/no-namespace
79
+ namespace Express {
80
+ export interface Application {
81
+ upgrade(path: PondPath, handler: EndpointHandler): Endpoint;
82
+ }
83
+ }
84
+ }
85
+
86
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
87
+ // @ts-ignore
88
+ interface PondSocketExpressApp extends Express {
89
+
90
+ /**
91
+ * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
92
+ * @param path - the pattern to accept || can also be a regex
93
+ * @param handler - the handler function to authenticate the socket
94
+ * @example
95
+ * const endpoint = pond.createEndpoint('/api/socket', (req, res) => {
96
+ * const token = req.query.token;
97
+ * if (!token)
98
+ * return res.reject("No token provided");
99
+ * res.accept({
100
+ * assign: {
101
+ * token
102
+ * }
103
+ * });
104
+ * })
105
+ */
106
+ upgrade(path: PondPath, handler: EndpointHandler): Endpoint;
107
+ }
108
+ export type PondState = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';
109
+ type Unsubscribe = () => void;
110
+
111
+ export interface PresencePayload {
112
+ changed: PondPresence;
113
+ presence: PondPresence[];
114
+ }
115
+
116
+ export declare class Channel {
117
+ /**
118
+ * @desc Connects to the channel.
119
+ */
120
+ public join(): void;
121
+
122
+ /**
123
+ * @desc Disconnects from the channel.
124
+ */
125
+ public leave(): void;
126
+
127
+ /**
128
+ * @desc Monitors the channel for messages.
129
+ * @param event - The event to monitor.
130
+ * @param callback - The callback to call when a message is received.
131
+ */
132
+ public onMessage(event: string, callback: (message: PondMessage) => void): Unsubscribe;
133
+
134
+ /**
135
+ * @desc Monitors the connection state of the channel.
136
+ * @param callback - The callback to call when the connection state changes.
137
+ */
138
+ public onConnectionChange(callback: (connected: boolean) => void): Unsubscribe;
139
+
140
+ /**
141
+ * @desc Detects when clients join the channel.
142
+ * @param callback - The callback to call when a client joins the channel.
143
+ */
144
+ public onJoin(callback: (presence: PondPresence) => void): Unsubscribe;
145
+
146
+ /**
147
+ * @desc Detects when clients leave the channel.
148
+ * @param callback - The callback to call when a client leaves the channel.
149
+ */
150
+ public onLeave(callback: (presence: PondPresence) => void): Unsubscribe;
151
+
152
+ /**
153
+ * @desc Detects when clients change their presence in the channel.
154
+ * @param callback - The callback to call when a client changes their presence in the channel.
155
+ */
156
+ public onPresenceChange(callback: (presence: PresencePayload) => void): Unsubscribe;
157
+
158
+ /**
159
+ * @desc Sends a message to specific clients in the channel.
160
+ * @param event - The event to send.
161
+ * @param payload - The message to send.
162
+ * @param recipient - The clients to send the message to.
163
+ */
164
+ public sendMessage(event: string, payload: PondMessage, recipient: string[]): void;
165
+
166
+ /**
167
+ * @desc Broadcasts a message to every other client in the channel except yourself.
168
+ * @param event - The event to send.
169
+ * @param payload - The message to send.
170
+ */
171
+ public broadcastFrom(event: string, payload: PondMessage): void;
172
+
173
+ /**
174
+ * @desc Broadcasts a message to the channel, including yourself.
175
+ * @param event - The event to send.
176
+ * @param payload - The message to send.
177
+ */
178
+ public broadcast(event: string, payload: PondMessage): void;
179
+
180
+ /**
181
+ * @desc Gets the current connection state of the channel.
182
+ */
183
+ public isConnected(): boolean;
184
+
185
+
186
+ /**
187
+ * @desc check is the channel has been closed.
188
+ */
189
+ public hasClosed(): boolean;
190
+
191
+ /**
192
+ * @desc Gets the current presence of the channel.
193
+ */
194
+ public getPresence(): PondPresence[];
195
+
196
+ /**
197
+ * @desc Monitors the presence of the channel.
198
+ * @param callback - The callback to call when the presence changes.
199
+ */
200
+ public onUsersChange(callback: (users: PondPresence[]) => void): Unsubscribe;
201
+ }
202
+
203
+ export declare class PondSocketClient {
204
+ constructor(endpoint: string, params?: Record<string, any>);
205
+
206
+ /**
207
+ * @desc Connects to the server and returns the socket.
208
+ */
209
+ public connect(backoff?: number): void;
210
+
211
+ /**
212
+ * @desc Returns the current state of the socket.
213
+ */
214
+ public getState(): PondState;
215
+
216
+ /**
217
+ * @desc Disconnects the socket.
218
+ */
219
+ public disconnect(): void;
220
+
221
+ /**
222
+ * @desc Creates a channel with the given name and params.
223
+ * @param name - The name of the channel.
224
+ * @param params - The params to send to the server.
225
+ */
226
+ public createChannel(name: string, params?: JoinParams): Channel;
227
+ }
228
+
229
+ declare class AbstractRequest {
230
+ get event (): EventObject;
231
+
232
+ get channelNme (): string;
233
+
234
+ get assigns (): UserAssigns;
235
+
236
+ get presence (): UserPresences;
237
+ }
238
+
239
+ declare class EventRequest extends AbstractRequest {
240
+ get user (): UserData;
241
+ }
242
+
243
+ declare class EventResponse {
244
+ /**
245
+ * @desc Checks if the response has been sent
246
+ */
247
+ get responseSent (): boolean;
248
+
249
+ /**
250
+ * @desc Accepts the request and optionally assigns data to the client
251
+ * @param assigns - the data to assign to the client
252
+ */
253
+ accept (assigns?: PondAssigns): EventResponse;
254
+
255
+ /**
256
+ * @desc Rejects the request and optionally assigns data to the client
257
+ * @param message - the error message
258
+ * @param errorCode - the error code
259
+ * @param assigns - the data to assign to the client
260
+ */
261
+ reject (message?: string, errorCode?: number, assigns?: PondAssigns): EventResponse;
262
+
263
+ /**
264
+ * @desc Emits a direct message to the client
265
+ * @param event - the event name
266
+ * @param payload - the payload to send
267
+ * @param assigns - the data to assign to the client
268
+ */
269
+ send (event: string, payload: PondMessage, assigns?: PondAssigns): EventResponse;
270
+
271
+ /**
272
+ * @desc Sends a message to all clients in the channel
273
+ * @param event - the event to send
274
+ * @param payload - the payload to send
275
+ */
276
+ broadcast (event: string, payload: PondMessage): EventResponse;
277
+
278
+ /**
279
+ * @desc Sends a message to all clients in the channel except the client making the request
280
+ * @param event - the event to send
281
+ * @param payload - the payload to send
282
+ */
283
+ broadcastFromUser (event: string, payload: PondMessage): EventResponse;
284
+
285
+ /**
286
+ * @desc Sends a message to a set of clients in the channel
287
+ * @param event - the event to send
288
+ * @param payload - the payload to send
289
+ * @param userIds - the ids of the clients to send the message to
290
+ */
291
+ sendToUsers (event: string, payload: PondMessage, userIds: string[]): EventResponse;
292
+
293
+ /**
294
+ * @desc Tracks a user's presence in the channel
295
+ * @param presence - the initial presence data
296
+ * @param userId - the id of the user to track
297
+ */
298
+ trackPresence (presence: PondPresence, userId?: string): EventResponse;
299
+
300
+ /**
301
+ * @desc Updates a user's presence in the channel
302
+ * @param presence - the updated presence data
303
+ * @param userId - the id of the user to update
304
+ */
305
+ updatePresence (presence: PondPresence, userId?: string): EventResponse;
306
+
307
+ /**
308
+ * @desc Removes a user's presence from the channel
309
+ * @param userId - the id of the user to remove
310
+ */
311
+ unTrackPresence (userId?: string): EventResponse;
312
+
313
+ /**
314
+ * @desc Evicts a user from the channel
315
+ * @param reason - the reason for the eviction
316
+ * @param userId - the id of the user to evict,
317
+ */
318
+ evictUser (reason: string, userId?: string): void;
319
+
320
+ /**
321
+ * @desc Closes the channel from the server side for all clients
322
+ * @param reason - the reason for closing the channel
323
+ */
324
+ closeChannel (reason: string): void;
325
+ }
326
+
327
+ declare class JoinRequest extends AbstractRequest {
328
+ get joinParams (): JoinParams;
329
+
330
+ get user (): UserData;
331
+
332
+ get event (): EventObject;
333
+ }
334
+
335
+ declare class JoinResponse {
336
+ get responseSent (): boolean;
337
+
338
+ /**
339
+ * @desc Accepts the request and optionally assigns data to the client
340
+ * @param assigns - the data to assign to the client
341
+ */
342
+ accept (assigns?: PondAssigns): JoinResponse;
343
+
344
+ /**
345
+ * @desc Rejects the request and optionally assigns data to the client
346
+ * @param message - the error message
347
+ * @param errorCode - the error code
348
+ */
349
+ reject (message?: string, errorCode?: number): JoinResponse;
350
+
351
+ /**
352
+ * @desc Emits a direct message to the client
353
+ * @param event - the event name
354
+ * @param payload - the payload to send
355
+ * @param assigns - the data to assign to the client
356
+ */
357
+ send (event: string, payload: PondMessage, assigns?: PondAssigns): this;
358
+
359
+ /**
360
+ * @desc Emits a message to all clients in the channel
361
+ * @param event - the event name
362
+ * @param payload - the payload to send
363
+ */
364
+ broadcast (event: string, payload: PondMessage): JoinResponse;
365
+
366
+ /**
367
+ * @desc Emits a message to all clients in the channel except the sender
368
+ * @param event - the event name
369
+ * @param payload - the payload to send
370
+ */
371
+ broadcastFromUser (event: string, payload: PondMessage): JoinResponse;
372
+
373
+ /**
374
+ * @desc Emits a message to a specific set of clients
375
+ * @param event - the event name
376
+ * @param payload - the payload to send
377
+ * @param userIds - the ids of the clients to send the message to
378
+ */
379
+ sendToUsers (event: string, payload: PondMessage, userIds: string[]): JoinResponse;
380
+
381
+ /**
382
+ * @desc tracks the presence of a client
383
+ * @param presence - the presence data to track
384
+ */
385
+ trackPresence (presence: PondPresence): JoinResponse;
386
+ }
387
+
388
+ declare class PondChannel {
389
+ /**
390
+ * @desc Authorize a user to join a channel
391
+ * @param handler - The handler to authorize the user
392
+ * @example
393
+ * const pond = new PondChannelEngine();
394
+ * pond.onJoinRequest((request, response) => {
395
+ * if (request.event.assigns.admin)
396
+ * response.accept();
397
+ * else
398
+ * response.reject('You are not an admin', 403);
399
+ * });
400
+ */
401
+ onJoinRequest (handler: AuthorizeMiddleware): void;
402
+
403
+ /**
404
+ * @desc Handles an event request made by a user
405
+ * @param event - The event to listen for
406
+ * @param handler - The handler to execute when the event is received
407
+ * @example
408
+ * pond.onEvent('echo', (request, response) => {
409
+ * response.send('echo', {
410
+ * message: request.payload,
411
+ * });
412
+ * });
413
+ */
414
+ onEvent (event: PondPath, handler: (request: EventRequest, response: EventResponse) => void | Promise<void>): void;
415
+ }
416
+
417
+ declare class ConnectionResponse {
418
+ /**
419
+ * @desc Accepts the request and optionally assigns data to the client
420
+ * @param assigns - the data to assign to the client
421
+ */
422
+ accept (assigns?: PondAssigns): void;
423
+
424
+ /**
425
+ * @desc Rejects the request with the given error message
426
+ * @param message - the error message
427
+ * @param errorCode - the error code
428
+ */
429
+ reject (message?: string, errorCode?: number): void;
430
+
431
+ /**
432
+ * @desc Emits a direct message to the client
433
+ * @param event - the event name
434
+ * @param payload - the payload to send
435
+ * @param assigns - the data to assign to the client
436
+ */
437
+ send (event: string, payload: PondMessage, assigns?: PondAssigns): void;
438
+ }
439
+
440
+ export declare class Endpoint {
441
+ /**
442
+ * @desc Adds a new PondChannel to this path on this endpoint
443
+ * @param path - The path to add the channel to
444
+ * @param channel - The channel to add
445
+ *
446
+ * @example
447
+ * endpoint.useChannel('/chat', pondChannelInstance);
448
+ */
449
+ useChannel (path: PondPath, channel: PondChannel): void;
450
+
451
+ /**
452
+ * @desc List all clients connected to this endpoint
453
+ */
454
+ listConnections (): string[];
455
+
456
+ /**
457
+ * @desc Gets all clients connected to this endpoint
458
+ */
459
+ getClients (): SocketCache[];
460
+
461
+ /**
462
+ * @desc Broadcasts a message to all clients connected to this endpoint
463
+ * @param event - The event to broadcast
464
+ * @param payload - The payload to broadcast
465
+ */
466
+ broadcast (event: string, payload: PondMessage): void;
467
+
468
+ /**
469
+ * @desc Closes specific clients connected to this endpoint
470
+ * @param clientIds - The id for the client / clients to close
471
+ */
472
+ closeConnection (clientIds: string | string[]): void;
473
+ }
474
+
475
+ export declare class PondSocket {
476
+ constructor (server?: HTTPServer, socketServer?: WebSocketServer);
477
+
478
+ /**
479
+ * @desc Specifies the port to listen on
480
+ * @param port - the port to listen on
481
+ * @param callback - the callback to call when the server is listening
482
+ */
483
+ listen (port: number, callback: (port?: number) => void): HTTPServer<typeof IncomingMessage, typeof import('http').ServerResponse>;
484
+
485
+ /**
486
+ * @desc Closes the server
487
+ * @param callback - the callback to call when the server is closed
488
+ */
489
+ close (callback?: () => void): HTTPServer<typeof IncomingMessage, typeof import('http').ServerResponse>;
490
+
491
+ /**
492
+ * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
493
+ * @param path - the pattern to accept || can also be a regex
494
+ * @param handler - the handler function to authenticate the socket
495
+ * @example
496
+ * const endpoint = pond.createEndpoint('/api/socket', (req, res) => {
497
+ * const token = req.query.token;
498
+ * if (!token)
499
+ * return res.reject('No token provided');
500
+ * res.accept({
501
+ * assign: {
502
+ * token
503
+ * }
504
+ * });
505
+ * })
506
+ */
507
+ createEndpoint (path: PondPath, handler: EndpointHandler): Endpoint;
508
+
509
+ /**
510
+ * @desc Adds a middleware function to the socket server
511
+ * @param middleware - the middleware function to add
512
+ */
513
+ use (middleware: SocketMiddlewareFunction): void;
514
+ }
515
+
516
+ /**
517
+ * @desc Creates a pond socket server
518
+ * @param app - The Express app to be used by the server
519
+ * @constructor
520
+ */
521
+ export declare const PondSocketFromExpress: (app: Express) => PondSocketExpressApp;
522
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eleven-am/pondsocket",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "PondSocket is a fast simple socket server",
5
5
  "keywords": [
6
6
  "socket",
@@ -33,18 +33,6 @@
33
33
  "dependencies": {
34
34
  "ws": "^8.12.0"
35
35
  },
36
- "exports": {
37
- ".": "./dist/index.js",
38
- "./express": "./dist/express/index.js",
39
- "./client": "./dist/client/index.js"
40
- },
41
- "typesVersions": {
42
- "*": {
43
- "*": [
44
- "dist/*"
45
- ]
46
- }
47
- },
48
36
  "devDependencies": {
49
37
  "@types/express": "^4.17.14",
50
38
  "@types/jest": "^29.5.0",
@@ -1,122 +0,0 @@
1
- // eslint-disable-next-line import/no-unresolved
2
- import { PondMessage, JoinParams, PondPresence } from '../index';
3
- export type PondState = 'CONNECTING' | 'OPEN' | 'CLOSING' | 'CLOSED';
4
- type Unsubscribe = () => void;
5
-
6
- export interface PresencePayload {
7
- changed: PondPresence;
8
- presence: PondPresence[];
9
- }
10
-
11
- export declare class Channel {
12
- /**
13
- * @desc Connects to the channel.
14
- */
15
- public join(): void;
16
-
17
- /**
18
- * @desc Disconnects from the channel.
19
- */
20
- public leave(): void;
21
-
22
- /**
23
- * @desc Monitors the channel for messages.
24
- * @param event - The event to monitor.
25
- * @param callback - The callback to call when a message is received.
26
- */
27
- public onMessage(event: string, callback: (message: PondMessage) => void): Unsubscribe;
28
-
29
- /**
30
- * @desc Monitors the connection state of the channel.
31
- * @param callback - The callback to call when the connection state changes.
32
- */
33
- public onConnectionChange(callback: (connected: boolean) => void): Unsubscribe;
34
-
35
- /**
36
- * @desc Detects when clients join the channel.
37
- * @param callback - The callback to call when a client joins the channel.
38
- */
39
- public onJoin(callback: (presence: PondPresence) => void): Unsubscribe;
40
-
41
- /**
42
- * @desc Detects when clients leave the channel.
43
- * @param callback - The callback to call when a client leaves the channel.
44
- */
45
- public onLeave(callback: (presence: PondPresence) => void): Unsubscribe;
46
-
47
- /**
48
- * @desc Detects when clients change their presence in the channel.
49
- * @param callback - The callback to call when a client changes their presence in the channel.
50
- */
51
- public onPresenceChange(callback: (presence: PresencePayload) => void): Unsubscribe;
52
-
53
- /**
54
- * @desc Sends a message to specific clients in the channel.
55
- * @param event - The event to send.
56
- * @param payload - The message to send.
57
- * @param recipient - The clients to send the message to.
58
- */
59
- public sendMessage(event: string, payload: PondMessage, recipient: string[]): void;
60
-
61
- /**
62
- * @desc Broadcasts a message to every other client in the channel except yourself.
63
- * @param event - The event to send.
64
- * @param payload - The message to send.
65
- */
66
- public broadcastFrom(event: string, payload: PondMessage): void;
67
-
68
- /**
69
- * @desc Broadcasts a message to the channel, including yourself.
70
- * @param event - The event to send.
71
- * @param payload - The message to send.
72
- */
73
- public broadcast(event: string, payload: PondMessage): void;
74
-
75
- /**
76
- * @desc Gets the current connection state of the channel.
77
- */
78
- public isConnected(): boolean;
79
-
80
-
81
- /**
82
- * @desc check is the channel has been closed.
83
- */
84
- public hasClosed(): boolean;
85
-
86
- /**
87
- * @desc Gets the current presence of the channel.
88
- */
89
- public getPresence(): PondPresence[];
90
-
91
- /**
92
- * @desc Monitors the presence of the channel.
93
- * @param callback - The callback to call when the presence changes.
94
- */
95
- public onUsersChange(callback: (users: PondPresence[]) => void): Unsubscribe;
96
- }
97
-
98
- export default class PondClient {
99
- constructor(endpoint: string, params?: Record<string, any>);
100
-
101
- /**
102
- * @desc Connects to the server and returns the socket.
103
- */
104
- public connect(backoff?: number): void;
105
-
106
- /**
107
- * @desc Returns the current state of the socket.
108
- */
109
- public getState(): PondState;
110
-
111
- /**
112
- * @desc Disconnects the socket.
113
- */
114
- public disconnect(): void;
115
-
116
- /**
117
- * @desc Creates a channel with the given name and params.
118
- * @param name - The name of the channel.
119
- * @param params - The params to send to the server.
120
- */
121
- public createChannel(name: string, params?: JoinParams): Channel;
122
- }
@@ -1,36 +0,0 @@
1
- /* eslint-disable import/no-unresolved */
2
- import { Express } from 'express';
3
-
4
- import { EndpointHandler, Endpoint, PondPath } from '../index';
5
-
6
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
7
- // @ts-ignore
8
- interface PondSocketExpressApp extends Express {
9
-
10
- /**
11
- * @desc Accepts a new socket upgrade request on the provided endpoint using the handler function to authenticate the socket
12
- * @param path - the pattern to accept || can also be a regex
13
- * @param handler - the handler function to authenticate the socket
14
- * @example
15
- * const endpoint = pond.createEndpoint('/api/socket', (req, res) => {
16
- * const token = req.query.token;
17
- * if (!token)
18
- * return res.reject("No token provided");
19
- * res.accept({
20
- * assign: {
21
- * token
22
- * }
23
- * });
24
- * })
25
- */
26
- upgrade(path: PondPath, handler: EndpointHandler): Endpoint;
27
- }
28
-
29
- /**
30
- * @desc Creates a pond socket server
31
- * @param app - The Express app to be used by the server
32
- * @constructor
33
- */
34
- declare const PondSocket: (app: Express) => PondSocketExpressApp;
35
-
36
- export default PondSocket;