@player-devtools/messenger 0.0.7--canary.8.483

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/src/index.ts ADDED
@@ -0,0 +1,414 @@
1
+ import uid from "tiny-uid";
2
+ import type {
3
+ BaseEvent,
4
+ Connection,
5
+ DisconnectEvent,
6
+ EventsBatchEvent,
7
+ InternalEvent,
8
+ MessengerEvent,
9
+ MessengerOptions,
10
+ RequestLostEventsEvent,
11
+ Transaction,
12
+ TransactionMetadata,
13
+ } from "@player-devtools/types";
14
+
15
+ const internalEvents: Array<InternalEvent<BaseEvent<string, unknown>>["type"]> =
16
+ [
17
+ "MESSENGER_BEACON",
18
+ "MESSENGER_DISCONNECT",
19
+ "MESSENGER_REQUEST_LOST_EVENTS",
20
+ "MESSENGER_EVENT_BATCH",
21
+ ];
22
+
23
+ /**
24
+ * Messenger<EventsType>
25
+ *
26
+ * Self-sufficient, lossless communication between instances.
27
+ *
28
+ * @param options
29
+ * @param options.context - context to use for this instance
30
+ * @param options.id - unique id for this instance, will be generated if not provided
31
+ * @param options.beaconIntervalMS - time to wait between beacons in milliseconds, defaults to 1000
32
+ * @param options.debug - if true, will log debug messages to console, defaults to false
33
+ * @param options.messageCallback - callback to handle messages
34
+ * @param options.sendMessage - function to send messages
35
+ * @param options.addListener - function to add a listener
36
+ * @param options.removeListener - function to remove a listener
37
+ * @param options.handleFailedMessage - function to handle failed messages
38
+ * @param options.log - function to handle logging
39
+ * @returns Messenger
40
+ * @example
41
+ * ```typescript
42
+ * const messenger = new Messenger({{
43
+ * context: "devtools",
44
+ * target: "player",
45
+ * messageCallback: (message) => dispatch(message),
46
+ * sendMessage: (message) =>
47
+ * browser.tabs
48
+ * ? browser.tabs
49
+ * .query({ active: true, currentWindow: true })
50
+ * .then((tabs) => {
51
+ * if (tabs[0].id) {
52
+ * browser.tabs.sendMessage(tabs[0].id, message);
53
+ * }
54
+ * })
55
+ * : browser.runtime.sendMessage(message),
56
+ * addListener: (callback) => {
57
+ * browser.runtime.onMessage.addListener(callback);
58
+ * },
59
+ * removeListener: (callback) => {
60
+ * browser.runtime.onMessage.removeListener(callback);
61
+ * },
62
+ * });
63
+ * ```
64
+ */
65
+ export class Messenger<T extends BaseEvent<string, unknown>> {
66
+ /** static record of events by isntance ID */
67
+ private static events: Record<
68
+ string,
69
+ Array<MessageEvent<BaseEvent<string, unknown>>>
70
+ > = {};
71
+
72
+ /** static connections record by instance ID */
73
+ private static connections: Record<string, Record<string, Connection>> = {};
74
+
75
+ /** beacon interval */
76
+ private beaconInterval: NodeJS.Timeout | null = null;
77
+
78
+ /** time between beacons milliseconds */
79
+ private beaconIntervalMS: number;
80
+
81
+ /** callback to handle messages, here for instance binding */
82
+ private handleMessage: (
83
+ message: TransactionMetadata & MessengerEvent<T>,
84
+ ) => void;
85
+
86
+ /** unique id */
87
+ private id: string;
88
+
89
+ constructor(private options: MessengerOptions<T>) {
90
+ // set defaults:
91
+ this.id = options.id || uid();
92
+ this.beaconIntervalMS = options.beaconIntervalMS || 1000;
93
+
94
+ // start beacon interval:
95
+ this.beaconInterval = setInterval(
96
+ this.beacon.bind(this),
97
+ this.beaconIntervalMS,
98
+ );
99
+
100
+ // bind message handler:
101
+ this.handleMessage = this._handleMessage.bind(this);
102
+
103
+ // add listener:
104
+ this.options.addListener(this.handleMessage);
105
+ }
106
+
107
+ private log(message: string) {
108
+ if (this.options.debug) {
109
+ this.options.logger.log(
110
+ `[MESSENGER-${this.id}](${this.options.context}): ${message}`,
111
+ );
112
+ }
113
+ }
114
+
115
+ private getConnection(id: string) {
116
+ if (!Messenger.connections[this.id]) {
117
+ Messenger.connections[this.id] = {};
118
+ }
119
+
120
+ return Messenger.connections[this.id][id];
121
+ }
122
+
123
+ private addConnection(id: string) {
124
+ Messenger.connections[this.id][id] = {
125
+ id,
126
+ messagesReceived: 0,
127
+ messagesSent: 0,
128
+ desync: false,
129
+ };
130
+ }
131
+
132
+ private getEvents() {
133
+ if (!Messenger.events[this.id]) {
134
+ Messenger.events[this.id] = [];
135
+ }
136
+
137
+ return Messenger.events[this.id] as unknown as MessengerEvent<T>[];
138
+ }
139
+
140
+ private addEvent(event: MessengerEvent<T>) {
141
+ const events = this.getEvents();
142
+ events.push(event);
143
+ }
144
+
145
+ /** generate a sequential id for each non-internal message */
146
+ private getTransactionID(message: MessengerEvent<T>) {
147
+ if (
148
+ !message.target ||
149
+ internalEvents.includes(message.type as InternalEvent<T>["type"])
150
+ ) {
151
+ return -1;
152
+ }
153
+
154
+ if (!this.getConnection(message.target)) {
155
+ this.addConnection(message.target);
156
+ }
157
+
158
+ const connection = this.getConnection(message.target);
159
+ connection.messagesSent += 1;
160
+ return connection.messagesSent;
161
+ }
162
+
163
+ private addTransactionMetadata(event: MessengerEvent<T>): Transaction<T> {
164
+ const metadata = {
165
+ _messenger_: true,
166
+ id: this.getTransactionID(event),
167
+ sender: this.id,
168
+ timestamp: Date.now(),
169
+ context: this.options.context,
170
+ ...(event.target && { target: event.target }),
171
+ };
172
+
173
+ return {
174
+ ...metadata,
175
+ ...event,
176
+ };
177
+ }
178
+
179
+ /** there is no persistent layer bookkeeping connections,
180
+ * so beacon to inform others of its presence */
181
+ private beacon() {
182
+ this.options.sendMessage(
183
+ this.addTransactionMetadata({
184
+ type: "MESSENGER_BEACON",
185
+ payload: null,
186
+ }),
187
+ );
188
+ }
189
+
190
+ private _handleMessage(transaction: Transaction<T>) {
191
+ const parsed: Transaction<T> =
192
+ typeof transaction === "string" ? JSON.parse(transaction) : transaction;
193
+
194
+ const isFromMessenger = parsed._messenger_;
195
+ const isFromSelf = parsed.sender === this.id;
196
+ const isFromSameContext = parsed.context === this.options.context;
197
+ const isTargetingOthers = parsed.target ? parsed.target !== this.id : false;
198
+ const connection = this.getConnection(parsed.sender);
199
+ const isKnownConnection = Boolean(connection);
200
+
201
+ if (
202
+ !isFromMessenger ||
203
+ isFromSelf ||
204
+ isFromSameContext ||
205
+ isTargetingOthers ||
206
+ (isKnownConnection && parsed.type === "MESSENGER_BEACON")
207
+ ) {
208
+ return;
209
+ }
210
+
211
+ const handlers: Record<string, (parsed: Transaction<T>) => void> = {
212
+ MESSENGER_BEACON: this.handleBeaconMessage.bind(this),
213
+ MESSENGER_DISCONNECT: this.handleDisconnectMessage.bind(this),
214
+ MESSENGER_REQUEST_LOST_EVENTS: this.handleLostEventsRequest.bind(this),
215
+ };
216
+
217
+ const handler = handlers[(parsed as BaseEvent<string, unknown>).type];
218
+
219
+ if (handler) {
220
+ handler(parsed);
221
+ return;
222
+ }
223
+
224
+ if (isKnownConnection) {
225
+ const isBatch = parsed.type === "MESSENGER_EVENT_BATCH";
226
+
227
+ const transactionID = isBatch
228
+ ? (parsed.payload as EventsBatchEvent<T>["payload"]).events[0].id
229
+ : parsed.id;
230
+
231
+ const { messagesReceived, desync } = connection;
232
+
233
+ // if we already received this message, ignore:
234
+ if (transactionID > -1 && transactionID <= messagesReceived) {
235
+ return;
236
+ }
237
+
238
+ // if we missed messages, request them, unless we already did:
239
+ if (
240
+ !desync &&
241
+ transactionID > -1 &&
242
+ transactionID > messagesReceived + 1
243
+ ) {
244
+ const message: RequestLostEventsEvent = {
245
+ type: "MESSENGER_REQUEST_LOST_EVENTS",
246
+ payload: {
247
+ messagesReceived,
248
+ },
249
+ target: parsed.sender,
250
+ };
251
+
252
+ this.options.sendMessage(this.addTransactionMetadata(message));
253
+
254
+ this.log(
255
+ `requesting lost messages from ${parsed.context}:${parsed.sender}`,
256
+ );
257
+
258
+ // set desync, so we don't request again:
259
+ connection.desync = true;
260
+
261
+ // don't process this message, since we requested missing ones:
262
+ return;
263
+ }
264
+
265
+ if (isBatch) {
266
+ // clear desync flag on event batch:
267
+ connection.desync = false;
268
+ connection.messagesReceived += (
269
+ parsed.payload as EventsBatchEvent<T>["payload"]
270
+ ).events.length;
271
+ } else {
272
+ connection.messagesReceived += 1;
273
+ }
274
+ }
275
+
276
+ this.options.messageCallback(parsed);
277
+
278
+ this.log(
279
+ `message received: ${(parsed as BaseEvent<string, unknown>).type}`,
280
+ );
281
+ }
282
+
283
+ private handleBeaconMessage(parsed: Transaction<T>) {
284
+ if (this.getConnection(parsed.sender)) {
285
+ return;
286
+ }
287
+
288
+ this.addConnection(parsed.sender);
289
+ const events = this.getEvents();
290
+
291
+ if (events.length > 0) {
292
+ const message: EventsBatchEvent<T> = {
293
+ type: "MESSENGER_EVENT_BATCH",
294
+ payload: {
295
+ events: events.map((event) => this.addTransactionMetadata(event)),
296
+ },
297
+ target: parsed.sender,
298
+ };
299
+
300
+ this.options.sendMessage(this.addTransactionMetadata(message));
301
+
302
+ this.log(
303
+ `messages [0 - ${events.length - 1}] sent to ${parsed.context}:${
304
+ parsed.sender
305
+ }`,
306
+ );
307
+
308
+ const connection = this.getConnection(parsed.sender);
309
+ connection.messagesSent = events.length;
310
+ }
311
+
312
+ this.log(`new connection added - ${parsed.context}:${parsed.sender}`);
313
+ }
314
+
315
+ private handleLostEventsRequest(parsed: Transaction<T>) {
316
+ const connection = this.getConnection(parsed.sender);
317
+ const events = this.getEvents();
318
+
319
+ if (!connection || events.length === 0) {
320
+ return;
321
+ }
322
+
323
+ const missingEvents = events.slice(connection.messagesSent, events.length);
324
+
325
+ if (missingEvents.length === 0) {
326
+ return;
327
+ }
328
+
329
+ const message: EventsBatchEvent<T> = {
330
+ type: "MESSENGER_EVENT_BATCH",
331
+ payload: {
332
+ events: missingEvents.map((event) =>
333
+ this.addTransactionMetadata(event),
334
+ ),
335
+ },
336
+ target: parsed.sender,
337
+ };
338
+
339
+ this.options.sendMessage(this.addTransactionMetadata(message));
340
+
341
+ connection.messagesSent = events.length;
342
+
343
+ this.log(
344
+ `messages [0 - ${events.length - 1}] sent to ${parsed.context}:${
345
+ parsed.sender
346
+ }`,
347
+ );
348
+ }
349
+
350
+ private handleDisconnectMessage(
351
+ parsed: TransactionMetadata & MessengerEvent<T>,
352
+ ) {
353
+ delete Messenger.connections[parsed.sender];
354
+
355
+ this.log(`disconnected - ${parsed.context}:${parsed.sender}`);
356
+ }
357
+
358
+ public sendMessage(message: T | string): Promise<void> {
359
+ let parsed: T;
360
+ try {
361
+ parsed = typeof message === "string" ? JSON.parse(message) : message;
362
+ } catch (e) {
363
+ this.log(`Failed to parse message to JSON. Message: ${message}`);
364
+ return Promise.reject(e);
365
+ }
366
+
367
+ this.addEvent(parsed);
368
+
369
+ const target = parsed.target || null;
370
+ const msg = this.addTransactionMetadata(parsed);
371
+ const connection = target ? this.getConnection(target) : null;
372
+
373
+ if (connection) {
374
+ connection.messagesSent += 1;
375
+ }
376
+
377
+ return this.options.sendMessage(msg).catch(() => {
378
+ this.options.handleFailedMessage?.(msg);
379
+
380
+ this.log(
381
+ `failed to send message: ${
382
+ (parsed as BaseEvent<string, unknown>).type
383
+ } from ${this.id} to ${target || "all"}`,
384
+ );
385
+ });
386
+ }
387
+
388
+ public destroy() {
389
+ if (this.beaconInterval) {
390
+ clearInterval(this.beaconInterval);
391
+ }
392
+ // iOS does not leverage this because iOS cannot compare functions
393
+ this.options.removeListener(this.handleMessage);
394
+
395
+ Object.keys(Messenger.connections).forEach((connection) => {
396
+ const event: DisconnectEvent = {
397
+ type: "MESSENGER_DISCONNECT",
398
+ payload: null,
399
+ target: connection,
400
+ };
401
+ const message = this.addTransactionMetadata(event);
402
+ this.options.sendMessage(message);
403
+ });
404
+
405
+ Messenger.reset();
406
+ this.log("destroyed");
407
+ }
408
+
409
+ /** reset static records */
410
+ static reset() {
411
+ Messenger.events = {};
412
+ Messenger.connections = {};
413
+ }
414
+ }
@@ -0,0 +1,79 @@
1
+ import type { BaseEvent, MessengerOptions } from "@player-devtools/types";
2
+ /**
3
+ * Messenger<EventsType>
4
+ *
5
+ * Self-sufficient, lossless communication between instances.
6
+ *
7
+ * @param options
8
+ * @param options.context - context to use for this instance
9
+ * @param options.id - unique id for this instance, will be generated if not provided
10
+ * @param options.beaconIntervalMS - time to wait between beacons in milliseconds, defaults to 1000
11
+ * @param options.debug - if true, will log debug messages to console, defaults to false
12
+ * @param options.messageCallback - callback to handle messages
13
+ * @param options.sendMessage - function to send messages
14
+ * @param options.addListener - function to add a listener
15
+ * @param options.removeListener - function to remove a listener
16
+ * @param options.handleFailedMessage - function to handle failed messages
17
+ * @param options.log - function to handle logging
18
+ * @returns Messenger
19
+ * @example
20
+ * ```typescript
21
+ * const messenger = new Messenger({{
22
+ * context: "devtools",
23
+ * target: "player",
24
+ * messageCallback: (message) => dispatch(message),
25
+ * sendMessage: (message) =>
26
+ * browser.tabs
27
+ * ? browser.tabs
28
+ * .query({ active: true, currentWindow: true })
29
+ * .then((tabs) => {
30
+ * if (tabs[0].id) {
31
+ * browser.tabs.sendMessage(tabs[0].id, message);
32
+ * }
33
+ * })
34
+ * : browser.runtime.sendMessage(message),
35
+ * addListener: (callback) => {
36
+ * browser.runtime.onMessage.addListener(callback);
37
+ * },
38
+ * removeListener: (callback) => {
39
+ * browser.runtime.onMessage.removeListener(callback);
40
+ * },
41
+ * });
42
+ * ```
43
+ */
44
+ export declare class Messenger<T extends BaseEvent<string, unknown>> {
45
+ private options;
46
+ /** static record of events by isntance ID */
47
+ private static events;
48
+ /** static connections record by instance ID */
49
+ private static connections;
50
+ /** beacon interval */
51
+ private beaconInterval;
52
+ /** time between beacons milliseconds */
53
+ private beaconIntervalMS;
54
+ /** callback to handle messages, here for instance binding */
55
+ private handleMessage;
56
+ /** unique id */
57
+ private id;
58
+ constructor(options: MessengerOptions<T>);
59
+ private log;
60
+ private getConnection;
61
+ private addConnection;
62
+ private getEvents;
63
+ private addEvent;
64
+ /** generate a sequential id for each non-internal message */
65
+ private getTransactionID;
66
+ private addTransactionMetadata;
67
+ /** there is no persistent layer bookkeeping connections,
68
+ * so beacon to inform others of its presence */
69
+ private beacon;
70
+ private _handleMessage;
71
+ private handleBeaconMessage;
72
+ private handleLostEventsRequest;
73
+ private handleDisconnectMessage;
74
+ sendMessage(message: T | string): Promise<void>;
75
+ destroy(): void;
76
+ /** reset static records */
77
+ static reset(): void;
78
+ }
79
+ //# sourceMappingURL=index.d.ts.map