@thalesrc/hermes 7.2.0 → 7.3.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
@@ -231,9 +231,9 @@ mainService.sendDataToWorker([1, 2, 3, 4, 5]).subscribe(result => {
231
231
  });
232
232
  ```
233
233
 
234
- ##### Async Worker Initialization
234
+ ##### Flexible Worker Initialization
235
235
 
236
- The worker parameter supports flexible initialization patterns:
236
+ The worker parameter supports multiple initialization patterns for different use cases:
237
237
 
238
238
  ```typescript
239
239
  // Direct Worker instance
@@ -253,6 +253,41 @@ const service4 = new MainThread(async () => {
253
253
  });
254
254
  ```
255
255
 
256
+ ##### Dynamic Worker Management with `initialize()`
257
+
258
+ The `initialize()` method allows you to switch workers at runtime or re-establish connections:
259
+
260
+ ```typescript
261
+ class MainThread extends WorkerMessageService {
262
+ // ... decorators and methods
263
+ }
264
+
265
+ // Start without a worker
266
+ const service = new MainThread();
267
+
268
+ // Later, connect to a worker dynamically
269
+ service.initialize(new Worker('./worker.js'));
270
+
271
+ // Switch to a different worker
272
+ service.initialize(new Worker('./different-worker.js'));
273
+
274
+ // Re-establish connection after worker error
275
+ const worker = new Worker('./worker.js');
276
+ worker.onerror = (error) => {
277
+ console.error('Worker error, reinitializing...', error);
278
+ service.initialize(new Worker('./worker.js'));
279
+ };
280
+ service.initialize(worker);
281
+
282
+ // Conditional worker initialization
283
+ function getWorker() {
284
+ return navigator.hardwareConcurrency > 2
285
+ ? new Worker('./heavy-worker.js')
286
+ : new Worker('./light-worker.js');
287
+ }
288
+ service.initialize(getWorker);
289
+ ```
290
+
256
291
  #### Worker Thread
257
292
 
258
293
  ```typescript
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thalesrc/hermes",
3
- "version": "7.2.0",
3
+ "version": "7.3.0",
4
4
  "description": "Javascript messaging library",
5
5
  "keywords": [
6
6
  "javascript",
@@ -23,6 +23,9 @@ const selectors_1 = require("../selectors");
23
23
  * - Function that returns a Worker (for lazy initialization)
24
24
  * - Function that returns a Promise<Worker> (for async lazy initialization)
25
25
  *
26
+ * The `initialize()` method allows dynamic worker management, enabling you to switch
27
+ * workers at runtime or re-establish connections after errors.
28
+ *
26
29
  * @example
27
30
  * // In main thread - communicate with a specific worker
28
31
  * const worker = new Worker('./worker.js');
@@ -42,13 +45,19 @@ const selectors_1 = require("../selectors");
42
45
  * const client = new WorkerMessageClient(() =>
43
46
  * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined
44
47
  * );
48
+ *
49
+ * @example
50
+ * // Re-initialize with a different worker
51
+ * const client = new WorkerMessageClient();
52
+ * // Later, switch to a different worker
53
+ * client.initialize(new Worker('./different-worker.js'));
45
54
  */
46
55
  class WorkerMessageClient extends message_client_1.MessageClient {
47
56
  /**
48
57
  * Promise resolving to the Worker instance or undefined if running in worker context
49
58
  * @private
50
59
  */
51
- #worker = null;
60
+ #worker = Promise.resolve(undefined);
52
61
  /**
53
62
  * Unique identifier for this client instance to prevent ID collisions
54
63
  * @private
@@ -70,6 +79,46 @@ class WorkerMessageClient extends message_client_1.MessageClient {
70
79
  */
71
80
  constructor(worker) {
72
81
  super();
82
+ this.initialize(worker);
83
+ }
84
+ /**
85
+ * Initializes or re-initializes the worker connection.
86
+ *
87
+ * This method sets up message listeners for the provided worker. If a worker
88
+ * was previously initialized, it cleans up the old connection before establishing
89
+ * the new one. This allows for dynamic worker management, such as:
90
+ * - Switching between different workers at runtime
91
+ * - Re-establishing connections after worker errors
92
+ * - Lazy initialization when the worker is conditionally needed
93
+ *
94
+ * @param worker - Optional worker configuration:
95
+ * - Worker: Direct worker instance (main thread)
96
+ * - Promise<Worker>: Promise resolving to worker (async initialization)
97
+ * - () => Worker: Function returning worker (lazy initialization)
98
+ * - () => Promise<Worker>: Function returning promise (async lazy initialization)
99
+ * - undefined: Omit for worker thread context (uses self)
100
+ *
101
+ * @example
102
+ * // Switch to a different worker dynamically
103
+ * const client = new WorkerMessageClient(oldWorker);
104
+ * client.initialize(newWorker); // Cleans up old listener, sets up new one
105
+ *
106
+ * @example
107
+ * // Re-initialize after worker error
108
+ * worker.onerror = () => {
109
+ * client.initialize(new Worker('./worker.js'));
110
+ * };
111
+ */
112
+ initialize(worker) {
113
+ // Deinitialize previous worker if any
114
+ this.#worker.then(prevWorker => {
115
+ if (prevWorker) {
116
+ prevWorker.removeEventListener('message', this.#handler);
117
+ }
118
+ else {
119
+ removeEventListener('message', this.#handler);
120
+ }
121
+ }).catch(noop_1.noop);
73
122
  // Resolve worker parameter: execute function if provided, otherwise use value directly
74
123
  const _worker = typeof worker === 'function' ? worker() : worker;
75
124
  // Ensure worker is wrapped in a promise for consistent async handling
@@ -3,6 +3,10 @@ import { MessageClient } from "../message-client";
3
3
  import { MessageResponse } from "../message-response.type";
4
4
  import { Message } from "../message.interface";
5
5
  import { GET_NEW_ID, RESPONSES$, SEND } from "../selectors";
6
+ type ClientWorkerType = Worker | undefined;
7
+ type ClientWorkerPromise = Promise<ClientWorkerType>;
8
+ type ClientWorkerFactory = () => ClientWorkerType | ClientWorkerPromise;
9
+ type ClientWorkerArg = ClientWorkerType | ClientWorkerPromise | ClientWorkerFactory;
6
10
  /**
7
11
  * WorkerMessageClient
8
12
  *
@@ -19,6 +23,9 @@ import { GET_NEW_ID, RESPONSES$, SEND } from "../selectors";
19
23
  * - Function that returns a Worker (for lazy initialization)
20
24
  * - Function that returns a Promise<Worker> (for async lazy initialization)
21
25
  *
26
+ * The `initialize()` method allows dynamic worker management, enabling you to switch
27
+ * workers at runtime or re-establish connections after errors.
28
+ *
22
29
  * @example
23
30
  * // In main thread - communicate with a specific worker
24
31
  * const worker = new Worker('./worker.js');
@@ -38,6 +45,12 @@ import { GET_NEW_ID, RESPONSES$, SEND } from "../selectors";
38
45
  * const client = new WorkerMessageClient(() =>
39
46
  * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined
40
47
  * );
48
+ *
49
+ * @example
50
+ * // Re-initialize with a different worker
51
+ * const client = new WorkerMessageClient();
52
+ * // Later, switch to a different worker
53
+ * client.initialize(new Worker('./different-worker.js'));
41
54
  */
42
55
  export declare class WorkerMessageClient extends MessageClient {
43
56
  #private;
@@ -55,7 +68,36 @@ export declare class WorkerMessageClient extends MessageClient {
55
68
  * - () => Promise<Worker>: Function returning promise (async lazy initialization)
56
69
  * - undefined: Omit for worker thread context (uses self)
57
70
  */
58
- constructor(worker?: Worker | Promise<Worker | undefined> | (() => Worker | undefined) | (() => Promise<Worker | undefined>));
71
+ constructor(worker?: ClientWorkerArg);
72
+ /**
73
+ * Initializes or re-initializes the worker connection.
74
+ *
75
+ * This method sets up message listeners for the provided worker. If a worker
76
+ * was previously initialized, it cleans up the old connection before establishing
77
+ * the new one. This allows for dynamic worker management, such as:
78
+ * - Switching between different workers at runtime
79
+ * - Re-establishing connections after worker errors
80
+ * - Lazy initialization when the worker is conditionally needed
81
+ *
82
+ * @param worker - Optional worker configuration:
83
+ * - Worker: Direct worker instance (main thread)
84
+ * - Promise<Worker>: Promise resolving to worker (async initialization)
85
+ * - () => Worker: Function returning worker (lazy initialization)
86
+ * - () => Promise<Worker>: Function returning promise (async lazy initialization)
87
+ * - undefined: Omit for worker thread context (uses self)
88
+ *
89
+ * @example
90
+ * // Switch to a different worker dynamically
91
+ * const client = new WorkerMessageClient(oldWorker);
92
+ * client.initialize(newWorker); // Cleans up old listener, sets up new one
93
+ *
94
+ * @example
95
+ * // Re-initialize after worker error
96
+ * worker.onerror = () => {
97
+ * client.initialize(new Worker('./worker.js'));
98
+ * };
99
+ */
100
+ initialize(worker?: ClientWorkerArg): void;
59
101
  /**
60
102
  * Sends a message to the worker or main thread
61
103
  *
@@ -72,3 +114,4 @@ export declare class WorkerMessageClient extends MessageClient {
72
114
  */
73
115
  protected [GET_NEW_ID](): string;
74
116
  }
117
+ export {};
@@ -20,6 +20,9 @@ import { GET_NEW_ID, RESPONSES$, SEND } from "../selectors";
20
20
  * - Function that returns a Worker (for lazy initialization)
21
21
  * - Function that returns a Promise<Worker> (for async lazy initialization)
22
22
  *
23
+ * The `initialize()` method allows dynamic worker management, enabling you to switch
24
+ * workers at runtime or re-establish connections after errors.
25
+ *
23
26
  * @example
24
27
  * // In main thread - communicate with a specific worker
25
28
  * const worker = new Worker('./worker.js');
@@ -39,13 +42,19 @@ import { GET_NEW_ID, RESPONSES$, SEND } from "../selectors";
39
42
  * const client = new WorkerMessageClient(() =>
40
43
  * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined
41
44
  * );
45
+ *
46
+ * @example
47
+ * // Re-initialize with a different worker
48
+ * const client = new WorkerMessageClient();
49
+ * // Later, switch to a different worker
50
+ * client.initialize(new Worker('./different-worker.js'));
42
51
  */
43
52
  export class WorkerMessageClient extends MessageClient {
44
53
  /**
45
54
  * Promise resolving to the Worker instance or undefined if running in worker context
46
55
  * @private
47
56
  */
48
- #worker = null;
57
+ #worker = Promise.resolve(undefined);
49
58
  /**
50
59
  * Unique identifier for this client instance to prevent ID collisions
51
60
  * @private
@@ -67,6 +76,46 @@ export class WorkerMessageClient extends MessageClient {
67
76
  */
68
77
  constructor(worker) {
69
78
  super();
79
+ this.initialize(worker);
80
+ }
81
+ /**
82
+ * Initializes or re-initializes the worker connection.
83
+ *
84
+ * This method sets up message listeners for the provided worker. If a worker
85
+ * was previously initialized, it cleans up the old connection before establishing
86
+ * the new one. This allows for dynamic worker management, such as:
87
+ * - Switching between different workers at runtime
88
+ * - Re-establishing connections after worker errors
89
+ * - Lazy initialization when the worker is conditionally needed
90
+ *
91
+ * @param worker - Optional worker configuration:
92
+ * - Worker: Direct worker instance (main thread)
93
+ * - Promise<Worker>: Promise resolving to worker (async initialization)
94
+ * - () => Worker: Function returning worker (lazy initialization)
95
+ * - () => Promise<Worker>: Function returning promise (async lazy initialization)
96
+ * - undefined: Omit for worker thread context (uses self)
97
+ *
98
+ * @example
99
+ * // Switch to a different worker dynamically
100
+ * const client = new WorkerMessageClient(oldWorker);
101
+ * client.initialize(newWorker); // Cleans up old listener, sets up new one
102
+ *
103
+ * @example
104
+ * // Re-initialize after worker error
105
+ * worker.onerror = () => {
106
+ * client.initialize(new Worker('./worker.js'));
107
+ * };
108
+ */
109
+ initialize(worker) {
110
+ // Deinitialize previous worker if any
111
+ this.#worker.then(prevWorker => {
112
+ if (prevWorker) {
113
+ prevWorker.removeEventListener('message', this.#handler);
114
+ }
115
+ else {
116
+ removeEventListener('message', this.#handler);
117
+ }
118
+ }).catch(noop);
70
119
  // Resolve worker parameter: execute function if provided, otherwise use value directly
71
120
  const _worker = typeof worker === 'function' ? worker() : worker;
72
121
  // Ensure worker is wrapped in a promise for consistent async handling
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../libs/hermes/src/worker/message-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EAAE,IAAI,EAAE,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,sCAAsC,CAAC;AACjE,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGlD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,OAAO,mBAAoB,SAAQ,aAAa;IACpD;;;OAGG;IACH,OAAO,GAAgC,IAAK,CAAC;IAE7C;;;OAGG;IACH,WAAW,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEzB;;OAEG;IACI,CAAC,UAAU,CAAC,GAAG,IAAI,OAAO,EAAmB,CAAC;IAErD;;;;;;;;;OASG;IACH,YAAY,MAAgH;QAC1H,KAAK,EAAE,CAAC;QAER,uFAAuF;QACvF,MAAM,OAAO,GAAqD,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;QAEnH,sEAAsE;QACtE,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;QAElC,kDAAkD;QAClD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;YACzB,IAAI,MAAM,EAAE,CAAC;gBACX,iDAAiD;gBACjD,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;YACpD,CAAC;iBAAM,CAAC;gBACN,6DAA6D;gBAC7D,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;IAED;;;;;;OAMG;IACI,CAAC,IAAI,CAAC,CAAI,OAAmB;QAClC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;YACzB,IAAI,MAAM,EAAE,CAAC;gBACX,8BAA8B;gBAC9B,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YAC9B,CAAC;iBAAM,CAAC;gBACN,qCAAqC;gBACpC,WAAmB,CAAC,OAAO,CAAC,CAAC;YAChC,CAAC;QACH,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;IAED;;;OAGG;IACH,QAAQ,GAAG,CAAC,KAAoC,EAAE,EAAE;QAClD,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC,CAAA;IAED;;;;;OAKG;IACO,CAAC,UAAU,CAAC;QACpB,OAAO,QAAQ,CAAC,wBAAwB,GAAG,IAAI,CAAC,WAAW,CAAW,CAAC;IACzE,CAAC;CACF","file":"message-client.js","sourcesContent":["import { uniqueId } from \"@thalesrc/js-utils/unique-id\";\nimport { noop } from \"@thalesrc/js-utils/function/noop\";\nimport { promisify } from '@thalesrc/js-utils/promise/promisify';\nimport { Subject } from \"rxjs\";\nimport { MessageClient } from \"../message-client\";\nimport { MessageResponse } from \"../message-response.type\";\nimport { Message } from \"../message.interface\";\nimport { GET_NEW_ID, RESPONSES$, SEND } from \"../selectors\";\n\n/**\n * WorkerMessageClient\n *\n * Client implementation for Web Worker communication. Sends messages to and receives\n * responses from Web Workers using the Worker postMessage API.\n *\n * This class can be used in two contexts:\n * - **Main thread**: Provide a Worker instance to communicate with that specific worker\n * - **Worker thread**: Omit the worker parameter to communicate with the main thread via self\n *\n * The worker parameter supports multiple types for flexibility:\n * - Direct Worker instance\n * - Promise that resolves to a Worker (for async worker initialization)\n * - Function that returns a Worker (for lazy initialization)\n * - Function that returns a Promise<Worker> (for async lazy initialization)\n *\n * @example\n * // In main thread - communicate with a specific worker\n * const worker = new Worker('./worker.js');\n * const client = new WorkerMessageClient(worker);\n *\n * @example\n * // In worker thread - communicate with main thread\n * const client = new WorkerMessageClient();\n *\n * @example\n * // With async worker initialization\n * const workerPromise = import('./worker.js').then(m => new m.MyWorker());\n * const client = new WorkerMessageClient(workerPromise);\n *\n * @example\n * // With lazy initialization\n * const client = new WorkerMessageClient(() =>\n * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined\n * );\n */\nexport class WorkerMessageClient extends MessageClient {\n /**\n * Promise resolving to the Worker instance or undefined if running in worker context\n * @private\n */\n #worker: Promise<Worker | undefined> = null!;\n\n /**\n * Unique identifier for this client instance to prevent ID collisions\n * @private\n */\n #instanceId = Date.now();\n\n /**\n * Observable stream of message responses from the worker or main thread\n */\n public [RESPONSES$] = new Subject<MessageResponse>();\n\n /**\n * Creates a new WorkerMessageClient instance\n *\n * @param worker - Optional worker configuration:\n * - Worker: Direct worker instance (main thread)\n * - Promise<Worker>: Promise resolving to worker (async initialization)\n * - () => Worker: Function returning worker (lazy initialization)\n * - () => Promise<Worker>: Function returning promise (async lazy initialization)\n * - undefined: Omit for worker thread context (uses self)\n */\n constructor(worker?: Worker | Promise<Worker | undefined> | (() => Worker | undefined) | (() => Promise<Worker | undefined>)) {\n super();\n\n // Resolve worker parameter: execute function if provided, otherwise use value directly\n const _worker: Worker | Promise<Worker | undefined> | undefined = typeof worker === 'function' ? worker() : worker;\n\n // Ensure worker is wrapped in a promise for consistent async handling\n this.#worker = promisify(_worker);\n\n // Set up message listener once worker is resolved\n this.#worker.then(worker => {\n if (worker) {\n // Main thread context: listen to specific worker\n worker.addEventListener('message', this.#handler);\n } else {\n // Worker thread context: listen to messages from main thread\n addEventListener('message', this.#handler);\n }\n }).catch(noop);\n }\n\n /**\n * Sends a message to the worker or main thread\n *\n * @param message - The message to send\n * @template T - Type of the message body\n * @internal Used by @Request decorator\n */\n public [SEND]<T>(message: Message<T>) {\n this.#worker.then(worker => {\n if (worker) {\n // Main thread: send to worker\n worker.postMessage(message);\n } else {\n // Worker thread: send to main thread\n (postMessage as any)(message);\n }\n }).catch(noop);\n }\n\n /**\n * Handles incoming messages and forwards them to the responses stream\n * @private\n */\n #handler = (event: MessageEvent<MessageResponse>) => {\n this[RESPONSES$].next(event.data);\n }\n\n /**\n * Generates a unique message ID for tracking request-response pairs\n *\n * @returns Unique message identifier\n * @internal Used by @Request decorator\n */\n protected [GET_NEW_ID](): string {\n return uniqueId('hermes-worker-message-' + this.#instanceId) as string;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../../../libs/hermes/src/worker/message-client.ts"],"names":[],"mappings":"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","file":"message-client.js","sourcesContent":["import { uniqueId } from \"@thalesrc/js-utils/unique-id\";\nimport { noop } from \"@thalesrc/js-utils/function/noop\";\nimport { promisify } from '@thalesrc/js-utils/promise/promisify';\nimport { Subject } from \"rxjs\";\nimport { MessageClient } from \"../message-client\";\nimport { MessageResponse } from \"../message-response.type\";\nimport { Message } from \"../message.interface\";\nimport { GET_NEW_ID, RESPONSES$, SEND } from \"../selectors\";\n\ntype ClientWorkerType = Worker | undefined;\ntype ClientWorkerPromise = Promise<ClientWorkerType>;\ntype ClientWorkerFactory = () => ClientWorkerType | ClientWorkerPromise;\ntype ClientWorkerArg = ClientWorkerType | ClientWorkerPromise | ClientWorkerFactory;\n\n/**\n * WorkerMessageClient\n *\n * Client implementation for Web Worker communication. Sends messages to and receives\n * responses from Web Workers using the Worker postMessage API.\n *\n * This class can be used in two contexts:\n * - **Main thread**: Provide a Worker instance to communicate with that specific worker\n * - **Worker thread**: Omit the worker parameter to communicate with the main thread via self\n *\n * The worker parameter supports multiple types for flexibility:\n * - Direct Worker instance\n * - Promise that resolves to a Worker (for async worker initialization)\n * - Function that returns a Worker (for lazy initialization)\n * - Function that returns a Promise<Worker> (for async lazy initialization)\n *\n * The `initialize()` method allows dynamic worker management, enabling you to switch\n * workers at runtime or re-establish connections after errors.\n *\n * @example\n * // In main thread - communicate with a specific worker\n * const worker = new Worker('./worker.js');\n * const client = new WorkerMessageClient(worker);\n *\n * @example\n * // In worker thread - communicate with main thread\n * const client = new WorkerMessageClient();\n *\n * @example\n * // With async worker initialization\n * const workerPromise = import('./worker.js').then(m => new m.MyWorker());\n * const client = new WorkerMessageClient(workerPromise);\n *\n * @example\n * // With lazy initialization\n * const client = new WorkerMessageClient(() =>\n * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined\n * );\n *\n * @example\n * // Re-initialize with a different worker\n * const client = new WorkerMessageClient();\n * // Later, switch to a different worker\n * client.initialize(new Worker('./different-worker.js'));\n */\nexport class WorkerMessageClient extends MessageClient {\n /**\n * Promise resolving to the Worker instance or undefined if running in worker context\n * @private\n */\n #worker: ClientWorkerPromise = Promise.resolve(undefined);\n\n /**\n * Unique identifier for this client instance to prevent ID collisions\n * @private\n */\n #instanceId = Date.now();\n\n /**\n * Observable stream of message responses from the worker or main thread\n */\n public [RESPONSES$] = new Subject<MessageResponse>();\n\n /**\n * Creates a new WorkerMessageClient instance\n *\n * @param worker - Optional worker configuration:\n * - Worker: Direct worker instance (main thread)\n * - Promise<Worker>: Promise resolving to worker (async initialization)\n * - () => Worker: Function returning worker (lazy initialization)\n * - () => Promise<Worker>: Function returning promise (async lazy initialization)\n * - undefined: Omit for worker thread context (uses self)\n */\n constructor(worker?: ClientWorkerArg) {\n super();\n\n this.initialize(worker);\n }\n\n /**\n * Initializes or re-initializes the worker connection.\n *\n * This method sets up message listeners for the provided worker. If a worker\n * was previously initialized, it cleans up the old connection before establishing\n * the new one. This allows for dynamic worker management, such as:\n * - Switching between different workers at runtime\n * - Re-establishing connections after worker errors\n * - Lazy initialization when the worker is conditionally needed\n *\n * @param worker - Optional worker configuration:\n * - Worker: Direct worker instance (main thread)\n * - Promise<Worker>: Promise resolving to worker (async initialization)\n * - () => Worker: Function returning worker (lazy initialization)\n * - () => Promise<Worker>: Function returning promise (async lazy initialization)\n * - undefined: Omit for worker thread context (uses self)\n *\n * @example\n * // Switch to a different worker dynamically\n * const client = new WorkerMessageClient(oldWorker);\n * client.initialize(newWorker); // Cleans up old listener, sets up new one\n *\n * @example\n * // Re-initialize after worker error\n * worker.onerror = () => {\n * client.initialize(new Worker('./worker.js'));\n * };\n */\n initialize(worker?: ClientWorkerArg) {\n // Deinitialize previous worker if any\n this.#worker.then(prevWorker => {\n if (prevWorker) {\n prevWorker.removeEventListener('message', this.#handler);\n } else {\n removeEventListener('message', this.#handler);\n }\n }).catch(noop);\n\n // Resolve worker parameter: execute function if provided, otherwise use value directly\n const _worker: ClientWorkerType | ClientWorkerPromise | undefined = typeof worker === 'function' ? worker() : worker;\n // Ensure worker is wrapped in a promise for consistent async handling\n this.#worker = promisify(_worker);\n\n // Set up message listener once worker is resolved\n this.#worker.then(worker => {\n if (worker) {\n // Main thread context: listen to specific worker\n worker.addEventListener('message', this.#handler);\n } else {\n // Worker thread context: listen to messages from main thread\n addEventListener('message', this.#handler);\n }\n }).catch(noop);\n }\n\n /**\n * Sends a message to the worker or main thread\n *\n * @param message - The message to send\n * @template T - Type of the message body\n * @internal Used by @Request decorator\n */\n public [SEND]<T>(message: Message<T>) {\n this.#worker.then(worker => {\n if (worker) {\n // Main thread: send to worker\n worker.postMessage(message);\n } else {\n // Worker thread: send to main thread\n (postMessage as any)(message);\n }\n }).catch(noop);\n }\n\n /**\n * Handles incoming messages and forwards them to the responses stream\n * @private\n */\n #handler = (event: MessageEvent<MessageResponse>) => {\n this[RESPONSES$].next(event.data);\n }\n\n /**\n * Generates a unique message ID for tracking request-response pairs\n *\n * @returns Unique message identifier\n * @internal Used by @Request decorator\n */\n protected [GET_NEW_ID](): string {\n return uniqueId('hermes-worker-message-' + this.#instanceId) as string;\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { WorkerMessageClient } from "./message-client";
2
- declare const WorkerMessageService_base: new (args_0: [worker?: Worker | undefined], args_1: [worker?: Worker | Promise<Worker | undefined> | (() => Worker | undefined) | (() => Promise<Worker | undefined>) | undefined]) => {
2
+ declare const WorkerMessageService_base: new (args_0: [worker?: Worker | undefined], args_1: [worker?: (Worker | undefined) | Promise<Worker | undefined> | (() => (Worker | undefined) | Promise<Worker | undefined>)]) => {
3
3
  terminate: () => void;
4
4
  } & WorkerMessageClient;
5
5
  export declare class WorkerMessageService extends WorkerMessageService_base {