@telperion/messenger 8.3.1 → 8.4.0

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/README.md CHANGED
@@ -405,9 +405,18 @@ const client = new PeerA(peerConnection);
405
405
  // Optional: custom channel name
406
406
  const clientWithChannel = new PeerA(peerConnection, 'game-events');
407
407
 
408
+ // Optional: explicit negotiated channel ID (overrides hash-derived default)
409
+ const clientWithId = new PeerA(peerConnection, 'game-events', 42);
410
+
408
411
  client.sendMove([3, 4]).subscribe(ok => {
409
412
  console.log('Move accepted:', ok);
410
413
  });
414
+
415
+ // Wait for the channel to be created (not necessarily open yet)
416
+ await client.created;
417
+
418
+ // Wait for the channel to be open and ready
419
+ await client.ready;
411
420
  ```
412
421
 
413
422
  #### Peer B (Host)
@@ -428,6 +437,12 @@ const host = new PeerB(peerConnection);
428
437
 
429
438
  // Optional: custom channel name (must match the client)
430
439
  const hostWithChannel = new PeerB(peerConnection, 'game-events');
440
+
441
+ // Optional: explicit negotiated channel ID (must match the client)
442
+ const hostWithId = new PeerB(peerConnection, 'game-events', 42);
443
+
444
+ // Graceful teardown
445
+ host.terminate();
431
446
  ```
432
447
 
433
448
  #### Bidirectional Communication (MessageService)
@@ -478,7 +493,7 @@ const service4 = new GamePeer(async () => {
478
493
 
479
494
  ##### Dynamic Connection Management with `initialize()`
480
495
 
481
- The `initialize()` method allows you to switch connections at runtime:
496
+ The `initialize()` method allows you to switch connections at runtime. It waits for the previous channel to be cleaned up (with a 5 s timeout) before establishing the new one:
482
497
 
483
498
  ```typescript
484
499
  class GamePeer extends RTCMessageService {
@@ -491,8 +506,8 @@ const peer = new GamePeer();
491
506
  // Connect later when RTCPeerConnection is ready
492
507
  peer.initialize(peerConnection);
493
508
 
494
- // Switch to a different connection
495
- peer.initialize(newPeerConnection);
509
+ // Switch to a different connection (optionally with a new channel ID)
510
+ peer.initialize(newPeerConnection, 42);
496
511
 
497
512
  // Re-establish after ICE failure
498
513
  peerConnection.oniceconnectionstatechange = () => {
@@ -500,6 +515,10 @@ peerConnection.oniceconnectionstatechange = () => {
500
515
  peer.initialize(createNewConnection());
501
516
  }
502
517
  };
518
+
519
+ // created and ready promises update after each initialize call
520
+ await peer.created; // resolves when the new channel is created
521
+ await peer.ready; // resolves when the new channel is open
503
522
  ```
504
523
 
505
524
  ---
@@ -641,7 +660,7 @@ const client = new ChromeMessageClient('extension-port');
641
660
  **`RTCMessageClient` / `RTCMessageHost` / `RTCMessageService`**
642
661
 
643
662
  ```typescript
644
- constructor(connection?: RTCConnectionArg, channelName?: string)
663
+ constructor(connection?: RTCConnectionArg, channelName?: string, channelId?: number)
645
664
  ```
646
665
 
647
666
  - **`connection`** (optional): RTCPeerConnection to use for the data channel. Can be:
@@ -650,6 +669,15 @@ constructor(connection?: RTCConnectionArg, channelName?: string)
650
669
  - `() => RTCPeerConnection | Promise<RTCPeerConnection>`: Factory function
651
670
  - Omit to initialize later via `initialize()`
652
671
  - **`channelName`** (optional): Name for the negotiated data channel. Default: `'MessengerRTCChannelDefault'`. A deterministic channel ID in [0, 1023] is derived from this name via FNV-1a hash.
672
+ - **`channelId`** (optional): Explicit negotiated channel ID. Overrides the hash-derived default when provided.
673
+
674
+ **Properties:**
675
+ - **`created`**: `Promise<RTCDataChannel>` — resolves once the channel has been created (may not yet be open)
676
+ - **`ready`**: `Promise<RTCDataChannel>` — resolves once the channel is open and ready to transmit
677
+
678
+ **Methods:**
679
+ - **`initialize(connection?, channelId?)`** — (re)initializes the data channel; cleans up the previous channel first
680
+ - **`terminate()`** *(host/service only)* — closes the data channel and removes event listeners
653
681
 
654
682
  **Examples:**
655
683
  ```typescript
@@ -659,6 +687,9 @@ const service = new RTCMessageService(peerConnection);
659
687
  // With custom channel name
660
688
  const service = new RTCMessageService(peerConnection, 'game-events');
661
689
 
690
+ // With explicit channel ID
691
+ const service = new RTCMessageService(peerConnection, 'game-events', 42);
692
+
662
693
  // Lazy initialization
663
694
  const service = new RTCMessageService();
664
695
  service.initialize(peerConnection);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telperion/messenger",
3
- "version": "8.3.1",
3
+ "version": "8.4.0",
4
4
  "description": "Javascript messaging library",
5
5
  "keywords": [
6
6
  "javascript",
@@ -6,8 +6,8 @@ class ChannelController {
6
6
  static #DEFAULT_MAX_CHANNELS = 1024;
7
7
  #connections = new WeakMap();
8
8
  #channels = new WeakMap();
9
- getChannel(connection, channelName) {
10
- const id = this.#getChannelId(channelName);
9
+ getChannel(connection, channelName, channelId) {
10
+ const id = channelId ?? this.#getChannelId(channelName);
11
11
  let channels = this.#connections.get(connection);
12
12
  if (!channels) {
13
13
  channels = {};
@@ -20,7 +20,11 @@ class ChannelController {
20
20
  channels[id] = channel;
21
21
  }
22
22
  this.#channels.set(channel, (this.#channels.get(channel) ?? 0) + 1); // Increment reference count
23
- return channel;
23
+ return [channel, new Promise((resolve) => {
24
+ if (channel.readyState === 'open')
25
+ return resolve(channel);
26
+ channel.addEventListener('open', () => resolve(channel), { once: true });
27
+ })];
24
28
  }
25
29
  close(channel) {
26
30
  const count = this.#channels.get(channel);
@@ -1,6 +1,6 @@
1
1
  declare class ChannelController {
2
2
  #private;
3
- getChannel(connection: RTCPeerConnection, channelName: string): RTCDataChannel;
3
+ getChannel(connection: RTCPeerConnection, channelName: string, channelId?: number): [RTCDataChannel, Promise<RTCDataChannel>];
4
4
  close(channel: RTCDataChannel): void;
5
5
  }
6
6
  export declare const CHANNEL_CONTROLLER: ChannelController;
@@ -3,8 +3,8 @@ class ChannelController {
3
3
  static #DEFAULT_MAX_CHANNELS = 1024;
4
4
  #connections = new WeakMap();
5
5
  #channels = new WeakMap();
6
- getChannel(connection, channelName) {
7
- const id = this.#getChannelId(channelName);
6
+ getChannel(connection, channelName, channelId) {
7
+ const id = channelId ?? this.#getChannelId(channelName);
8
8
  let channels = this.#connections.get(connection);
9
9
  if (!channels) {
10
10
  channels = {};
@@ -17,7 +17,11 @@ class ChannelController {
17
17
  channels[id] = channel;
18
18
  }
19
19
  this.#channels.set(channel, (this.#channels.get(channel) ?? 0) + 1); // Increment reference count
20
- return channel;
20
+ return [channel, new Promise((resolve) => {
21
+ if (channel.readyState === 'open')
22
+ return resolve(channel);
23
+ channel.addEventListener('open', () => resolve(channel), { once: true });
24
+ })];
21
25
  }
22
26
  close(channel) {
23
27
  const count = this.#channels.get(channel);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../libs/messenger/src/rtc/channel-controller.ts"],"names":[],"mappings":";AAAA,MAAM,iBAAiB;IACrB,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAEpC,YAAY,GAAG,IAAI,OAAO,EAAqD,CAAC;IAChF,SAAS,GAAG,IAAI,OAAO,EAA0B,CAAC;IAElD,UAAU,CAAC,UAA6B,EAAE,WAAmB;QAC3D,MAAM,EAAE,GAAG,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAE3C,IAAI,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAEjD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,QAAQ,GAAG,EAAE,CAAC;YACd,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAC9C,CAAC;QAED,IAAI,OAAO,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,UAAU,CAAC,iBAAiB,CAAC,WAAW,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;YAC9F,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YAC/B,QAAQ,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC;QACzB,CAAC;QAED,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,4BAA4B;QAEjG,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,OAAuB;QAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAE1C,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO;QAEhC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,EAAE,CAAC;YAChB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,4BAA4B;QACtE,CAAC;IACH,CAAC;IAED,aAAa,CAAC,WAAmB;QAC/B,IAAI,IAAI,GAAG,UAAU,CAAC,CAAC,4BAA4B;QAEnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5C,IAAI,IAAI,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAClC,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,qCAAqC;QACzE,CAAC;QAED,yCAAyC;QACzC,OAAO,IAAI,GAAG,EAAiB,CAAC,qBAAqB,CAAC;IACxD,CAAC;;;AAGH,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,iBAAiB,EAAE,CAAC","file":"channel-controller.js","sourcesContent":["class ChannelController {\r\n static #DEFAULT_MAX_CHANNELS = 1024;\r\n\r\n #connections = new WeakMap<RTCPeerConnection, Record<number, RTCDataChannel>>();\r\n #channels = new WeakMap<RTCDataChannel, number>();\r\n\r\n getChannel(connection: RTCPeerConnection, channelName: string): RTCDataChannel {\r\n const id = this.#getChannelId(channelName);\r\n\r\n let channels = this.#connections.get(connection);\r\n\r\n if (!channels) {\r\n channels = {};\r\n this.#connections.set(connection, channels);\r\n }\r\n\r\n let channel = channels[id];\r\n\r\n if (!channel) {\r\n channel = connection.createDataChannel(channelName, { negotiated: true, id, ordered: false });\r\n this.#channels.set(channel, 0);\r\n channels[id] = channel;\r\n }\r\n\r\n this.#channels.set(channel, (this.#channels.get(channel) ?? 0) + 1); // Increment reference count\r\n\r\n return channel;\r\n }\r\n\r\n close(channel: RTCDataChannel): void {\r\n const count = this.#channels.get(channel);\r\n\r\n if (count === undefined) return;\r\n\r\n if (count <= 1) {\r\n channel.close();\r\n this.#channels.delete(channel);\r\n } else {\r\n this.#channels.set(channel, count - 1); // Decrement reference count\r\n }\r\n }\r\n\r\n #getChannelId(channelName: string): number {\r\n let hash = 0x811c9dc5; // FNV offset basis (32-bit)\r\n\r\n for (let i = 0; i < channelName.length; i++) {\r\n hash ^= channelName.charCodeAt(i);\r\n hash = (hash * 0x01000193) >>> 0; // FNV prime, keep as unsigned 32-bit\r\n }\r\n\r\n // Truncate to specified range [0, max-1]\r\n return hash % ChannelController.#DEFAULT_MAX_CHANNELS;\r\n }\r\n}\r\n\r\nexport const CHANNEL_CONTROLLER = new ChannelController();\r\n"]}
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/channel-controller.ts"],"names":[],"mappings":";AAAA,MAAM,iBAAiB;IACrB,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAEpC,YAAY,GAAG,IAAI,OAAO,EAAqD,CAAC;IAChF,SAAS,GAAG,IAAI,OAAO,EAA0B,CAAC;IAElD,UAAU,CAAC,UAA6B,EAAE,WAAmB,EAAE,SAAkB;QAC/E,MAAM,EAAE,GAAG,SAAS,IAAI,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;QAExD,IAAI,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,GA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AAC;YACf,OAAO,CAAC,KAAK,EAAE,CAAC;YAChB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,4BAA4B;QACtE,CAAC;IACH,CAAC;IAED,aAAa,CAAC,WAAmB;QAC/B,IAAI,IAAI,GAAG,UAAU,CAAC,CAAC,4BAA4B;QAEnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC5C,IAAI,IAAI,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAClC,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,qCAAqC;QACzE,CAAC;QAED,yCAAyC;QACzC,OAAO,IAAI,GAAG,EAAiB,CAAC,qBAAqB,CAAC;IACxD,CAAC;;;AAGH,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,iBAAiB,EAAE,CAAC","file":"channel-controller.js","sourcesContent":["class ChannelController {\r\n static #DEFAULT_MAX_CHANNELS = 1024;\r\n\r\n #connections = new WeakMap<RTCPeerConnection, Record<number, RTCDataChannel>>();\r\n #channels = new WeakMap<RTCDataChannel, number>();\r\n\r\n getChannel(connection: RTCPeerConnection, channelName: string, channelId?: number): [RTCDataChannel, Promise<RTCDataChannel>] {\r\n const id = channelId ?? this.#getChannelId(channelName);\r\n\r\n let channels = this.#connections.get(connection);\r\n\r\n if (!channels) {\r\n channels = {};\r\n this.#connections.set(connection, channels);\r\n }\r\n\r\n let channel = channels[id];\r\n\r\n if (!channel) {\r\n channel = connection.createDataChannel(channelName, { negotiated: true, id, ordered: false });\r\n this.#channels.set(channel, 0);\r\n channels[id] = channel;\r\n }\r\n\r\n this.#channels.set(channel, (this.#channels.get(channel) ?? 0) + 1); // Increment reference count\r\n\r\n return [channel, new Promise<RTCDataChannel>((resolve) => {\r\n if (channel.readyState === 'open') return resolve(channel);\r\n\r\n channel.addEventListener('open', () => resolve(channel), { once: true });\r\n })];\r\n }\r\n\r\n close(channel: RTCDataChannel): void {\r\n const count = this.#channels.get(channel);\r\n\r\n if (count === undefined) return;\r\n\r\n if (count <= 1) {\r\n channel.close();\r\n this.#channels.delete(channel);\r\n } else {\r\n this.#channels.set(channel, count - 1); // Decrement reference count\r\n }\r\n }\r\n\r\n #getChannelId(channelName: string): number {\r\n let hash = 0x811c9dc5; // FNV offset basis (32-bit)\r\n\r\n for (let i = 0; i < channelName.length; i++) {\r\n hash ^= channelName.charCodeAt(i);\r\n hash = (hash * 0x01000193) >>> 0; // FNV prime, keep as unsigned 32-bit\r\n }\r\n\r\n // Truncate to specified range [0, max-1]\r\n return hash % ChannelController.#DEFAULT_MAX_CHANNELS;\r\n }\r\n}\r\n\r\nexport const CHANNEL_CONTROLLER = new ChannelController();\r\n"]}
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initialize = initialize;
4
+ const noop_1 = require("@telperion/js-utils/function/noop");
5
+ const call_1 = require("@telperion/js-utils/function/call");
6
+ const timeout_1 = require("@telperion/js-utils/promise/timeout");
7
+ const promisify_1 = require("@telperion/js-utils/promise/promisify");
8
+ const never_1 = require("@telperion/js-utils/promise/never");
9
+ const channel_controller_1 = require("./channel-controller");
10
+ const INITIALIZATION_ERROR_TUPLE = [undefined, Promise.resolve(null)];
11
+ function initialize({ context, selectors: { channel, channelOpen, deinit, emitter }, connection, channelName, channelId, messageFilterType }) {
12
+ const channelWithOpen = Promise.race([
13
+ context[deinit],
14
+ (0, timeout_1.timeout)(5000, noop_1.noop)
15
+ ])
16
+ .then(call_1.call)
17
+ .then(() => {
18
+ const conn = typeof connection === 'function' ? connection() : connection;
19
+ return (0, promisify_1.promisify)(conn);
20
+ })
21
+ .then(conn => {
22
+ if (!conn)
23
+ return INITIALIZATION_ERROR_TUPLE;
24
+ return channel_controller_1.CHANNEL_CONTROLLER.getChannel(conn, channelName, channelId);
25
+ })
26
+ .catch(error => {
27
+ console.error('Failed to initialize RTCMessageClient:', error);
28
+ return INITIALIZATION_ERROR_TUPLE;
29
+ });
30
+ context[channel] = channelWithOpen.then(([dataChannel]) => dataChannel ?? never_1.NEVER);
31
+ context[channelOpen] = channelWithOpen.then(([_, open]) => open).then(channel => channel ?? never_1.NEVER);
32
+ context[deinit] = channelWithOpen.then(([channel]) => {
33
+ if (!channel)
34
+ return noop_1.noop;
35
+ const listener = (event) => {
36
+ const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
37
+ if (data.type !== messageFilterType)
38
+ return;
39
+ context[emitter].next(data);
40
+ };
41
+ channel.addEventListener('message', listener);
42
+ return () => {
43
+ channel.removeEventListener('message', listener);
44
+ channel_controller_1.CHANNEL_CONTROLLER.close(channel);
45
+ };
46
+ });
47
+ }
@@ -0,0 +1,16 @@
1
+ import { RTCConnectionArg } from "./rtc.type";
2
+ interface InitializerConfig {
3
+ context: any;
4
+ selectors: {
5
+ channel: symbol;
6
+ channelOpen: symbol;
7
+ deinit: symbol;
8
+ emitter: symbol;
9
+ };
10
+ connection: RTCConnectionArg;
11
+ channelName: string;
12
+ channelId?: number;
13
+ messageFilterType: 'request' | 'response';
14
+ }
15
+ export declare function initialize({ context, selectors: { channel, channelOpen, deinit, emitter }, connection, channelName, channelId, messageFilterType }: InitializerConfig): void;
16
+ export {};
@@ -0,0 +1,46 @@
1
+ import { noop } from "@telperion/js-utils/function/noop";
2
+ import { call } from "@telperion/js-utils/function/call";
3
+ import { timeout } from "@telperion/js-utils/promise/timeout";
4
+ import { promisify } from "@telperion/js-utils/promise/promisify";
5
+ import { NEVER } from "@telperion/js-utils/promise/never";
6
+ import { CHANNEL_CONTROLLER } from "./channel-controller";
7
+ const INITIALIZATION_ERROR_TUPLE = [undefined, Promise.resolve(null)];
8
+ export function initialize({ context, selectors: { channel, channelOpen, deinit, emitter }, connection, channelName, channelId, messageFilterType }) {
9
+ const channelWithOpen = Promise.race([
10
+ context[deinit],
11
+ timeout(5000, noop)
12
+ ])
13
+ .then(call)
14
+ .then(() => {
15
+ const conn = typeof connection === 'function' ? connection() : connection;
16
+ return promisify(conn);
17
+ })
18
+ .then(conn => {
19
+ if (!conn)
20
+ return INITIALIZATION_ERROR_TUPLE;
21
+ return CHANNEL_CONTROLLER.getChannel(conn, channelName, channelId);
22
+ })
23
+ .catch(error => {
24
+ console.error('Failed to initialize RTCMessageClient:', error);
25
+ return INITIALIZATION_ERROR_TUPLE;
26
+ });
27
+ context[channel] = channelWithOpen.then(([dataChannel]) => dataChannel ?? NEVER);
28
+ context[channelOpen] = channelWithOpen.then(([_, open]) => open).then(channel => channel ?? NEVER);
29
+ context[deinit] = channelWithOpen.then(([channel]) => {
30
+ if (!channel)
31
+ return noop;
32
+ const listener = (event) => {
33
+ const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
34
+ if (data.type !== messageFilterType)
35
+ return;
36
+ context[emitter].next(data);
37
+ };
38
+ channel.addEventListener('message', listener);
39
+ return () => {
40
+ channel.removeEventListener('message', listener);
41
+ CHANNEL_CONTROLLER.close(channel);
42
+ };
43
+ });
44
+ }
45
+
46
+ //# sourceMappingURL=initializer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/initializer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,qCAAqC,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAkB1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C,EAAE,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC;IACnG,OAAO,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,EAAE;QACnD,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC;QAE1B,MAAM,QAAQ,GAAG,CAAC,KAAmB,EAAE,EAAE;YACvC,MAAM,IAAI,GAAuD,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;YAEtI,IAAI,IAAI,CAAC,IAAI,KAAK,iBAAiB;gBAAE,OAAO;YAE5C,OAAO,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC,CAAC;QAEF,OAAO,CAAC,gBAAgB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAE9C,OAAO,GAAG,EAAE;YACV,OAAO,CAAC,mBAAmB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;YACjD,kBAAkB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","file":"initializer.js","sourcesContent":["import { noop } from \"@telperion/js-utils/function/noop\";\r\nimport { call } from \"@telperion/js-utils/function/call\";\r\nimport { timeout } from \"@telperion/js-utils/promise/timeout\";\r\nimport { promisify } from \"@telperion/js-utils/promise/promisify\";\r\nimport { NEVER } from \"@telperion/js-utils/promise/never\";\r\n\r\nimport { CHANNEL_CONTROLLER } from \"./channel-controller\";\r\nimport { RTCConnectionArg } from \"./rtc.type\";\r\nimport { MessageResponse } from \"../message-response.type\";\r\n\r\ninterface InitializerConfig {\r\n context: any;\r\n selectors: {\r\n channel: symbol;\r\n channelOpen: symbol;\r\n deinit: symbol;\r\n emitter: symbol;\r\n };\r\n connection: RTCConnectionArg;\r\n channelName: string;\r\n channelId?: number;\r\n messageFilterType: 'request' | 'response';\r\n}\r\n\r\nconst INITIALIZATION_ERROR_TUPLE = [undefined, Promise.resolve(null)] as const;\r\n\r\nexport function initialize({\r\n context,\r\n selectors: { channel, channelOpen, deinit, emitter },\r\n connection,\r\n channelName,\r\n channelId,\r\n messageFilterType\r\n}: InitializerConfig): void {\r\n const channelWithOpen = Promise.race([\r\n context[deinit],\r\n timeout(5000, noop)\r\n ])\r\n .then(call)\r\n .then(() => {\r\n const conn = typeof connection === 'function' ? connection() : connection;\r\n\r\n return promisify(conn);\r\n })\r\n .then(conn => {\r\n if (!conn) return INITIALIZATION_ERROR_TUPLE;\r\n\r\n return CHANNEL_CONTROLLER.getChannel(conn, channelName, channelId);\r\n })\r\n .catch(error => {\r\n console.error('Failed to initialize RTCMessageClient:', error);\r\n\r\n return INITIALIZATION_ERROR_TUPLE;\r\n })\r\n\r\n context[channel] = channelWithOpen.then(([dataChannel]) => dataChannel ?? NEVER);\r\n context[channelOpen] = channelWithOpen.then(([_, open]) => open).then(channel => channel ?? NEVER);\r\n context[deinit] = channelWithOpen.then(([channel]) => {\r\n if (!channel) return noop;\r\n\r\n const listener = (event: MessageEvent) => {\r\n const data: MessageResponse & { type: 'response' | 'request' } = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;\r\n\r\n if (data.type !== messageFilterType) return;\r\n\r\n context[emitter].next(data);\r\n };\r\n\r\n channel.addEventListener('message', listener);\r\n\r\n return () => {\r\n channel.removeEventListener('message', listener);\r\n CHANNEL_CONTROLLER.close(channel);\r\n };\r\n });\r\n}\r\n"]}
@@ -1,25 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RTCMessageClient = exports.READY = void 0;
3
+ exports.RTCMessageClient = exports.CREATED = exports.READY = void 0;
4
4
  const unique_id_1 = require("@telperion/js-utils/unique-id");
5
5
  const noop_1 = require("@telperion/js-utils/function/noop");
6
- const promisify_1 = require("@telperion/js-utils/promise/promisify");
7
- const timeout_1 = require("@telperion/js-utils/promise/timeout");
8
6
  const never_1 = require("@telperion/js-utils/promise/never");
9
7
  const rxjs_1 = require("rxjs");
10
8
  const message_client_1 = require("../message-client");
11
9
  const selectors_1 = require("../selectors");
12
10
  const default_channel_name_1 = require("./default-channel-name");
13
- const channel_controller_1 = require("./channel-controller");
14
- const CONNECTION = Symbol('RTCMessageClient Connection');
11
+ const initializer_1 = require("./initializer");
15
12
  const CHANNEL_NAME = Symbol('RTCMessageClient Channel Name');
13
+ const CHANNEL = Symbol('RTCMessageClient Channel');
14
+ const CHANNEL_OPEN = Symbol('RTCMessageClient Channel Open');
15
+ const DEINITIALIZE = Symbol('RTCMessageClient Deinitialize');
16
16
  exports.READY = Symbol('RTCMessageClient Ready');
17
+ exports.CREATED = Symbol('RTCMessageClient Created');
17
18
  /**
18
- * Message client for WebRTC DataChannel communication.
19
+ * WebRTC DataChannel message client that sends request messages and receives
20
+ * responses over a negotiated channel.
19
21
  *
20
- * Sends request messages over a negotiated RTCDataChannel and receives responses
21
- * on the same channel. Both peers must create the channel with identical
22
- * name and negotiated ID (handled automatically via {@link channelId}).
22
+ * Both peers must create the channel with an identical name and negotiated ID.
23
+ * The ID is derived automatically from the channel name via an FNV-1a hash
24
+ * unless an explicit `channelId` is supplied.
25
+ *
26
+ * Use `@Request` decorators to define outgoing RPC methods. The client can be
27
+ * constructed without a connection and initialized later via {@link initialize}.
23
28
  *
24
29
  * @example
25
30
  * ```typescript
@@ -36,71 +41,59 @@ exports.READY = Symbol('RTCMessageClient Ready');
36
41
  */
37
42
  class RTCMessageClient extends message_client_1.MessageClient {
38
43
  [selectors_1.RESPONSES$] = new rxjs_1.Subject();
39
- [CONNECTION] = Promise.resolve([undefined, noop_1.noop]);
40
44
  [CHANNEL_NAME];
45
+ [CHANNEL] = never_1.NEVER;
46
+ [CHANNEL_OPEN] = never_1.NEVER;
47
+ [DEINITIALIZE] = Promise.resolve(noop_1.noop);
48
+ get [exports.CREATED]() {
49
+ return this[CHANNEL];
50
+ }
51
+ /** Resolves with the `RTCDataChannel` once it has been created (may not yet be open). */
52
+ get created() {
53
+ return this[exports.CREATED];
54
+ }
41
55
  get [exports.READY]() {
42
- return this[CONNECTION].then(([dataChannel]) => dataChannel ?? never_1.NEVER);
56
+ return this[CHANNEL_OPEN];
43
57
  }
58
+ /** Resolves with the `RTCDataChannel` once it is open and ready to transmit. */
44
59
  get ready() {
45
60
  return this[exports.READY];
46
61
  }
47
62
  /**
48
- * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
63
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
49
64
  * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
65
+ * @param channelId - Explicit negotiated channel ID. Overrides the hash-derived default.
50
66
  */
51
- constructor(connection, channelName = default_channel_name_1.DEFAULT_CHANNEL_NAME) {
67
+ constructor(connection, channelName = default_channel_name_1.DEFAULT_CHANNEL_NAME, channelId) {
52
68
  super();
53
69
  this[CHANNEL_NAME] = channelName;
54
- RTCMessageClient.prototype.initialize.call(this, connection);
70
+ RTCMessageClient.prototype.initialize.call(this, connection, channelId);
55
71
  }
56
72
  /**
57
73
  * (Re)initializes the data channel with a new connection.
58
- * Cleans up the previous channel before establishing a new one.
74
+ * Waits for the previous channel to be cleaned up (with a 5 s timeout)
75
+ * before establishing the new one.
59
76
  *
60
77
  * @param connection - RTCPeerConnection instance, promise, or factory function.
61
- * @param channelName - Optional new channel name. Defaults to the current channel name.
78
+ * @param channelId - Optional negotiated channel ID. Defaults to the hash-derived ID.
62
79
  */
63
- initialize(connection) {
64
- this[CONNECTION] = Promise.race([
65
- this[CONNECTION],
66
- (0, timeout_1.timeout)(5000, [null, noop_1.noop])
67
- ])
68
- .then(([_, deinitialize]) => deinitialize())
69
- .catch(noop_1.noop)
70
- .then(() => {
71
- const _conn = typeof connection === 'function' ? connection() : connection;
72
- return (0, promisify_1.promisify)(_conn);
73
- })
74
- .then(conn => {
75
- if (!conn)
76
- return;
77
- const dataChannel = channel_controller_1.CHANNEL_CONTROLLER.getChannel(conn, this[CHANNEL_NAME]);
78
- if (dataChannel.readyState === 'open')
79
- return dataChannel;
80
- return new Promise((resolve) => {
81
- dataChannel.addEventListener('open', () => resolve(dataChannel), { once: true });
82
- });
83
- })
84
- .then(dataChannel => {
85
- if (!dataChannel)
86
- return [undefined, noop_1.noop];
87
- const listener = (event) => {
88
- const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
89
- if (data.type !== 'response')
90
- return;
91
- this[selectors_1.RESPONSES$].next(data);
92
- };
93
- dataChannel.addEventListener('message', listener);
94
- return [dataChannel, () => {
95
- dataChannel.removeEventListener('message', listener);
96
- channel_controller_1.CHANNEL_CONTROLLER.close(dataChannel);
97
- }];
80
+ initialize(connection, channelId) {
81
+ (0, initializer_1.initialize)({
82
+ context: this,
83
+ selectors: {
84
+ channel: CHANNEL,
85
+ channelOpen: CHANNEL_OPEN,
86
+ deinit: DEINITIALIZE,
87
+ emitter: selectors_1.RESPONSES$
88
+ },
89
+ connection,
90
+ channelName: this[CHANNEL_NAME],
91
+ channelId,
92
+ messageFilterType: 'response'
98
93
  });
99
94
  }
100
95
  async [selectors_1.SEND](message) {
101
- const [dataChannel] = await this[CONNECTION];
102
- if (dataChannel?.readyState !== 'open')
103
- return;
96
+ const dataChannel = await this[CHANNEL_OPEN];
104
97
  dataChannel.send(JSON.stringify({ ...message, type: 'request' }));
105
98
  }
106
99
  [selectors_1.GET_NEW_ID]() {
@@ -4,15 +4,22 @@ import { MessageResponse } from '../message-response.type';
4
4
  import { Message } from '../message.interface';
5
5
  import { GET_NEW_ID, RESPONSES$, SEND } from '../selectors';
6
6
  import { RTCConnectionArg } from './rtc.type';
7
- declare const CONNECTION: unique symbol;
8
7
  declare const CHANNEL_NAME: unique symbol;
8
+ declare const CHANNEL: unique symbol;
9
+ declare const CHANNEL_OPEN: unique symbol;
10
+ declare const DEINITIALIZE: unique symbol;
9
11
  export declare const READY: unique symbol;
12
+ export declare const CREATED: unique symbol;
10
13
  /**
11
- * Message client for WebRTC DataChannel communication.
14
+ * WebRTC DataChannel message client that sends request messages and receives
15
+ * responses over a negotiated channel.
12
16
  *
13
- * Sends request messages over a negotiated RTCDataChannel and receives responses
14
- * on the same channel. Both peers must create the channel with identical
15
- * name and negotiated ID (handled automatically via {@link channelId}).
17
+ * Both peers must create the channel with an identical name and negotiated ID.
18
+ * The ID is derived automatically from the channel name via an FNV-1a hash
19
+ * unless an explicit `channelId` is supplied.
20
+ *
21
+ * Use `@Request` decorators to define outgoing RPC methods. The client can be
22
+ * constructed without a connection and initialized later via {@link initialize}.
16
23
  *
17
24
  * @example
18
25
  * ```typescript
@@ -29,23 +36,31 @@ export declare const READY: unique symbol;
29
36
  */
30
37
  export declare class RTCMessageClient extends MessageClient {
31
38
  [RESPONSES$]: Subject<MessageResponse>;
32
- private [CONNECTION];
33
39
  private [CHANNEL_NAME];
40
+ private [CHANNEL];
41
+ private [CHANNEL_OPEN];
42
+ private [DEINITIALIZE];
43
+ private get [CREATED]();
44
+ /** Resolves with the `RTCDataChannel` once it has been created (may not yet be open). */
45
+ get created(): Promise<RTCDataChannel>;
34
46
  private get [READY]();
47
+ /** Resolves with the `RTCDataChannel` once it is open and ready to transmit. */
35
48
  get ready(): Promise<RTCDataChannel>;
36
49
  /**
37
- * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
50
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
38
51
  * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
52
+ * @param channelId - Explicit negotiated channel ID. Overrides the hash-derived default.
39
53
  */
40
- constructor(connection?: RTCConnectionArg, channelName?: string);
54
+ constructor(connection?: RTCConnectionArg, channelName?: string, channelId?: number);
41
55
  /**
42
56
  * (Re)initializes the data channel with a new connection.
43
- * Cleans up the previous channel before establishing a new one.
57
+ * Waits for the previous channel to be cleaned up (with a 5 s timeout)
58
+ * before establishing the new one.
44
59
  *
45
60
  * @param connection - RTCPeerConnection instance, promise, or factory function.
46
- * @param channelName - Optional new channel name. Defaults to the current channel name.
61
+ * @param channelId - Optional negotiated channel ID. Defaults to the hash-derived ID.
47
62
  */
48
- initialize(connection?: RTCConnectionArg): void;
63
+ initialize(connection?: RTCConnectionArg, channelId?: number): void;
49
64
  [SEND]<T>(message: Message<T>): Promise<void>;
50
65
  protected [GET_NEW_ID](): string;
51
66
  }