@thalesrc/hermes 7.1.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2019 Thales Rocks
3
+ Copyright (c) 2019 Thalesrc
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -231,6 +231,63 @@ mainService.sendDataToWorker([1, 2, 3, 4, 5]).subscribe(result => {
231
231
  });
232
232
  ```
233
233
 
234
+ ##### Flexible Worker Initialization
235
+
236
+ The worker parameter supports multiple initialization patterns for different use cases:
237
+
238
+ ```typescript
239
+ // Direct Worker instance
240
+ const service1 = new MainThread(new Worker('./worker.js'));
241
+
242
+ // Promise that resolves to a Worker (for async initialization)
243
+ const workerPromise = import('./worker.js').then(m => new Worker(m.default));
244
+ const service2 = new MainThread(workerPromise);
245
+
246
+ // Function that returns a Worker (for lazy initialization)
247
+ const service3 = new MainThread(() => new Worker('./worker.js'));
248
+
249
+ // Function that returns a Promise<Worker> (for async lazy initialization)
250
+ const service4 = new MainThread(async () => {
251
+ const module = await import('./worker.js');
252
+ return new Worker(module.default);
253
+ });
254
+ ```
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
+
234
291
  #### Worker Thread
235
292
 
236
293
  ```typescript
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thalesrc/hermes",
3
- "version": "7.1.0",
3
+ "version": "7.3.0",
4
4
  "description": "Javascript messaging library",
5
5
  "keywords": [
6
6
  "javascript",
package/worker/index.cjs CHANGED
@@ -1,8 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Listen = exports.Request = exports.WorkerMessageService = void 0;
3
+ exports.Listen = exports.Request = exports.WorkerMessageHost = exports.WorkerMessageClient = exports.WorkerMessageService = void 0;
4
4
  var message_service_1 = require("./message-service");
5
5
  Object.defineProperty(exports, "WorkerMessageService", { enumerable: true, get: function () { return message_service_1.WorkerMessageService; } });
6
+ var message_client_1 = require("./message-client");
7
+ Object.defineProperty(exports, "WorkerMessageClient", { enumerable: true, get: function () { return message_client_1.WorkerMessageClient; } });
8
+ var message_host_1 = require("./message-host");
9
+ Object.defineProperty(exports, "WorkerMessageHost", { enumerable: true, get: function () { return message_host_1.WorkerMessageHost; } });
6
10
  var request_decorator_1 = require("../request.decorator");
7
11
  Object.defineProperty(exports, "Request", { enumerable: true, get: function () { return request_decorator_1.Request; } });
8
12
  var listen_decorator_1 = require("../listen.decorator");
package/worker/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  export { WorkerMessageService } from './message-service';
2
+ export { WorkerMessageClient } from './message-client';
3
+ export { WorkerMessageHost } from './message-host';
2
4
  export { Request } from '../request.decorator';
3
5
  export { Listen } from '../listen.decorator';
package/worker/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { WorkerMessageService } from './message-service';
2
+ export { WorkerMessageClient } from './message-client';
3
+ export { WorkerMessageHost } from './message-host';
2
4
  export { Request } from '../request.decorator';
3
5
  export { Listen } from '../listen.decorator';
4
6
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../libs/hermes/src/worker/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC","file":"index.js","sourcesContent":["export { WorkerMessageService } from './message-service';\nexport { Request } from '../request.decorator';\nexport { Listen } from '../listen.decorator';\n"]}
1
+ {"version":3,"sources":["../../../../../libs/hermes/src/worker/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC","file":"index.js","sourcesContent":["export { WorkerMessageService } from './message-service';\nexport { WorkerMessageClient } from './message-client';\nexport { WorkerMessageHost } from './message-host';\nexport { Request } from '../request.decorator';\nexport { Listen } from '../listen.decorator';\n"]}
@@ -1,40 +1,174 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WorkerMessageClient = void 0;
4
- const js_utils_1 = require("@thalesrc/js-utils");
4
+ const unique_id_1 = require("@thalesrc/js-utils/unique-id");
5
+ const noop_1 = require("@thalesrc/js-utils/function/noop");
6
+ const promisify_1 = require("@thalesrc/js-utils/promise/promisify");
5
7
  const rxjs_1 = require("rxjs");
6
8
  const message_client_1 = require("../message-client");
7
9
  const selectors_1 = require("../selectors");
8
- const WORKER = Symbol('Worker');
9
- const HANDLER = Symbol('Handler');
10
- const INSTANCE_ID = Symbol('Instance Id');
10
+ /**
11
+ * WorkerMessageClient
12
+ *
13
+ * Client implementation for Web Worker communication. Sends messages to and receives
14
+ * responses from Web Workers using the Worker postMessage API.
15
+ *
16
+ * This class can be used in two contexts:
17
+ * - **Main thread**: Provide a Worker instance to communicate with that specific worker
18
+ * - **Worker thread**: Omit the worker parameter to communicate with the main thread via self
19
+ *
20
+ * The worker parameter supports multiple types for flexibility:
21
+ * - Direct Worker instance
22
+ * - Promise that resolves to a Worker (for async worker initialization)
23
+ * - Function that returns a Worker (for lazy initialization)
24
+ * - Function that returns a Promise<Worker> (for async lazy initialization)
25
+ *
26
+ * The `initialize()` method allows dynamic worker management, enabling you to switch
27
+ * workers at runtime or re-establish connections after errors.
28
+ *
29
+ * @example
30
+ * // In main thread - communicate with a specific worker
31
+ * const worker = new Worker('./worker.js');
32
+ * const client = new WorkerMessageClient(worker);
33
+ *
34
+ * @example
35
+ * // In worker thread - communicate with main thread
36
+ * const client = new WorkerMessageClient();
37
+ *
38
+ * @example
39
+ * // With async worker initialization
40
+ * const workerPromise = import('./worker.js').then(m => new m.MyWorker());
41
+ * const client = new WorkerMessageClient(workerPromise);
42
+ *
43
+ * @example
44
+ * // With lazy initialization
45
+ * const client = new WorkerMessageClient(() =>
46
+ * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined
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'));
54
+ */
11
55
  class WorkerMessageClient extends message_client_1.MessageClient {
56
+ /**
57
+ * Promise resolving to the Worker instance or undefined if running in worker context
58
+ * @private
59
+ */
60
+ #worker = Promise.resolve(undefined);
61
+ /**
62
+ * Unique identifier for this client instance to prevent ID collisions
63
+ * @private
64
+ */
65
+ #instanceId = Date.now();
66
+ /**
67
+ * Observable stream of message responses from the worker or main thread
68
+ */
12
69
  [selectors_1.RESPONSES$] = new rxjs_1.Subject();
13
- [WORKER];
14
- [INSTANCE_ID] = Date.now();
70
+ /**
71
+ * Creates a new WorkerMessageClient instance
72
+ *
73
+ * @param worker - Optional worker configuration:
74
+ * - Worker: Direct worker instance (main thread)
75
+ * - Promise<Worker>: Promise resolving to worker (async initialization)
76
+ * - () => Worker: Function returning worker (lazy initialization)
77
+ * - () => Promise<Worker>: Function returning promise (async lazy initialization)
78
+ * - undefined: Omit for worker thread context (uses self)
79
+ */
15
80
  constructor(worker) {
16
81
  super();
17
- this[WORKER] = worker;
18
- if (worker) {
19
- worker.addEventListener('message', this[HANDLER]);
20
- }
21
- else {
22
- addEventListener('message', this[HANDLER]);
23
- }
82
+ this.initialize(worker);
24
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);
122
+ // Resolve worker parameter: execute function if provided, otherwise use value directly
123
+ const _worker = typeof worker === 'function' ? worker() : worker;
124
+ // Ensure worker is wrapped in a promise for consistent async handling
125
+ this.#worker = (0, promisify_1.promisify)(_worker);
126
+ // Set up message listener once worker is resolved
127
+ this.#worker.then(worker => {
128
+ if (worker) {
129
+ // Main thread context: listen to specific worker
130
+ worker.addEventListener('message', this.#handler);
131
+ }
132
+ else {
133
+ // Worker thread context: listen to messages from main thread
134
+ addEventListener('message', this.#handler);
135
+ }
136
+ }).catch(noop_1.noop);
137
+ }
138
+ /**
139
+ * Sends a message to the worker or main thread
140
+ *
141
+ * @param message - The message to send
142
+ * @template T - Type of the message body
143
+ * @internal Used by @Request decorator
144
+ */
25
145
  [selectors_1.SEND](message) {
26
- if (this[WORKER]) {
27
- this[WORKER].postMessage(message);
28
- }
29
- else {
30
- postMessage(message);
31
- }
146
+ this.#worker.then(worker => {
147
+ if (worker) {
148
+ // Main thread: send to worker
149
+ worker.postMessage(message);
150
+ }
151
+ else {
152
+ // Worker thread: send to main thread
153
+ postMessage(message);
154
+ }
155
+ }).catch(noop_1.noop);
32
156
  }
33
- [HANDLER] = (event) => {
157
+ /**
158
+ * Handles incoming messages and forwards them to the responses stream
159
+ * @private
160
+ */
161
+ #handler = (event) => {
34
162
  this[selectors_1.RESPONSES$].next(event.data);
35
163
  };
164
+ /**
165
+ * Generates a unique message ID for tracking request-response pairs
166
+ *
167
+ * @returns Unique message identifier
168
+ * @internal Used by @Request decorator
169
+ */
36
170
  [selectors_1.GET_NEW_ID]() {
37
- return (0, js_utils_1.uniqueId)('hermes-worker-message-' + this[INSTANCE_ID]);
171
+ return (0, unique_id_1.uniqueId)('hermes-worker-message-' + this.#instanceId);
38
172
  }
39
173
  }
40
174
  exports.WorkerMessageClient = WorkerMessageClient;
@@ -3,19 +3,115 @@ 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
- interface MessageEvent<T> {
7
- data: T;
8
- }
9
- declare const WORKER: unique symbol;
10
- declare const HANDLER: unique symbol;
11
- declare const INSTANCE_ID: unique symbol;
6
+ type ClientWorkerType = Worker | undefined;
7
+ type ClientWorkerPromise = Promise<ClientWorkerType>;
8
+ type ClientWorkerFactory = () => ClientWorkerType | ClientWorkerPromise;
9
+ type ClientWorkerArg = ClientWorkerType | ClientWorkerPromise | ClientWorkerFactory;
10
+ /**
11
+ * WorkerMessageClient
12
+ *
13
+ * Client implementation for Web Worker communication. Sends messages to and receives
14
+ * responses from Web Workers using the Worker postMessage API.
15
+ *
16
+ * This class can be used in two contexts:
17
+ * - **Main thread**: Provide a Worker instance to communicate with that specific worker
18
+ * - **Worker thread**: Omit the worker parameter to communicate with the main thread via self
19
+ *
20
+ * The worker parameter supports multiple types for flexibility:
21
+ * - Direct Worker instance
22
+ * - Promise that resolves to a Worker (for async worker initialization)
23
+ * - Function that returns a Worker (for lazy initialization)
24
+ * - Function that returns a Promise<Worker> (for async lazy initialization)
25
+ *
26
+ * The `initialize()` method allows dynamic worker management, enabling you to switch
27
+ * workers at runtime or re-establish connections after errors.
28
+ *
29
+ * @example
30
+ * // In main thread - communicate with a specific worker
31
+ * const worker = new Worker('./worker.js');
32
+ * const client = new WorkerMessageClient(worker);
33
+ *
34
+ * @example
35
+ * // In worker thread - communicate with main thread
36
+ * const client = new WorkerMessageClient();
37
+ *
38
+ * @example
39
+ * // With async worker initialization
40
+ * const workerPromise = import('./worker.js').then(m => new m.MyWorker());
41
+ * const client = new WorkerMessageClient(workerPromise);
42
+ *
43
+ * @example
44
+ * // With lazy initialization
45
+ * const client = new WorkerMessageClient(() =>
46
+ * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined
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'));
54
+ */
12
55
  export declare class WorkerMessageClient extends MessageClient {
56
+ #private;
57
+ /**
58
+ * Observable stream of message responses from the worker or main thread
59
+ */
13
60
  [RESPONSES$]: Subject<MessageResponse>;
14
- protected [WORKER]: Worker | undefined;
15
- private [INSTANCE_ID];
16
- constructor(worker?: Worker);
61
+ /**
62
+ * Creates a new WorkerMessageClient instance
63
+ *
64
+ * @param worker - Optional worker configuration:
65
+ * - Worker: Direct worker instance (main thread)
66
+ * - Promise<Worker>: Promise resolving to worker (async initialization)
67
+ * - () => Worker: Function returning worker (lazy initialization)
68
+ * - () => Promise<Worker>: Function returning promise (async lazy initialization)
69
+ * - undefined: Omit for worker thread context (uses self)
70
+ */
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;
101
+ /**
102
+ * Sends a message to the worker or main thread
103
+ *
104
+ * @param message - The message to send
105
+ * @template T - Type of the message body
106
+ * @internal Used by @Request decorator
107
+ */
17
108
  [SEND]<T>(message: Message<T>): void;
18
- protected [HANDLER]: (event: MessageEvent<MessageResponse>) => void;
109
+ /**
110
+ * Generates a unique message ID for tracking request-response pairs
111
+ *
112
+ * @returns Unique message identifier
113
+ * @internal Used by @Request decorator
114
+ */
19
115
  protected [GET_NEW_ID](): string;
20
116
  }
21
117
  export {};
@@ -1,37 +1,171 @@
1
- import { uniqueId } from "@thalesrc/js-utils";
1
+ import { uniqueId } from "@thalesrc/js-utils/unique-id";
2
+ import { noop } from "@thalesrc/js-utils/function/noop";
3
+ import { promisify } from '@thalesrc/js-utils/promise/promisify';
2
4
  import { Subject } from "rxjs";
3
5
  import { MessageClient } from "../message-client";
4
6
  import { GET_NEW_ID, RESPONSES$, SEND } from "../selectors";
5
- const WORKER = Symbol('Worker');
6
- const HANDLER = Symbol('Handler');
7
- const INSTANCE_ID = Symbol('Instance Id');
7
+ /**
8
+ * WorkerMessageClient
9
+ *
10
+ * Client implementation for Web Worker communication. Sends messages to and receives
11
+ * responses from Web Workers using the Worker postMessage API.
12
+ *
13
+ * This class can be used in two contexts:
14
+ * - **Main thread**: Provide a Worker instance to communicate with that specific worker
15
+ * - **Worker thread**: Omit the worker parameter to communicate with the main thread via self
16
+ *
17
+ * The worker parameter supports multiple types for flexibility:
18
+ * - Direct Worker instance
19
+ * - Promise that resolves to a Worker (for async worker initialization)
20
+ * - Function that returns a Worker (for lazy initialization)
21
+ * - Function that returns a Promise<Worker> (for async lazy initialization)
22
+ *
23
+ * The `initialize()` method allows dynamic worker management, enabling you to switch
24
+ * workers at runtime or re-establish connections after errors.
25
+ *
26
+ * @example
27
+ * // In main thread - communicate with a specific worker
28
+ * const worker = new Worker('./worker.js');
29
+ * const client = new WorkerMessageClient(worker);
30
+ *
31
+ * @example
32
+ * // In worker thread - communicate with main thread
33
+ * const client = new WorkerMessageClient();
34
+ *
35
+ * @example
36
+ * // With async worker initialization
37
+ * const workerPromise = import('./worker.js').then(m => new m.MyWorker());
38
+ * const client = new WorkerMessageClient(workerPromise);
39
+ *
40
+ * @example
41
+ * // With lazy initialization
42
+ * const client = new WorkerMessageClient(() =>
43
+ * document.querySelector('[data-worker]') ? new Worker('./worker.js') : undefined
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'));
51
+ */
8
52
  export class WorkerMessageClient extends MessageClient {
53
+ /**
54
+ * Promise resolving to the Worker instance or undefined if running in worker context
55
+ * @private
56
+ */
57
+ #worker = Promise.resolve(undefined);
58
+ /**
59
+ * Unique identifier for this client instance to prevent ID collisions
60
+ * @private
61
+ */
62
+ #instanceId = Date.now();
63
+ /**
64
+ * Observable stream of message responses from the worker or main thread
65
+ */
9
66
  [RESPONSES$] = new Subject();
10
- [WORKER];
11
- [INSTANCE_ID] = Date.now();
67
+ /**
68
+ * Creates a new WorkerMessageClient instance
69
+ *
70
+ * @param worker - Optional worker configuration:
71
+ * - Worker: Direct worker instance (main thread)
72
+ * - Promise<Worker>: Promise resolving to worker (async initialization)
73
+ * - () => Worker: Function returning worker (lazy initialization)
74
+ * - () => Promise<Worker>: Function returning promise (async lazy initialization)
75
+ * - undefined: Omit for worker thread context (uses self)
76
+ */
12
77
  constructor(worker) {
13
78
  super();
14
- this[WORKER] = worker;
15
- if (worker) {
16
- worker.addEventListener('message', this[HANDLER]);
17
- }
18
- else {
19
- addEventListener('message', this[HANDLER]);
20
- }
79
+ this.initialize(worker);
21
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);
119
+ // Resolve worker parameter: execute function if provided, otherwise use value directly
120
+ const _worker = typeof worker === 'function' ? worker() : worker;
121
+ // Ensure worker is wrapped in a promise for consistent async handling
122
+ this.#worker = promisify(_worker);
123
+ // Set up message listener once worker is resolved
124
+ this.#worker.then(worker => {
125
+ if (worker) {
126
+ // Main thread context: listen to specific worker
127
+ worker.addEventListener('message', this.#handler);
128
+ }
129
+ else {
130
+ // Worker thread context: listen to messages from main thread
131
+ addEventListener('message', this.#handler);
132
+ }
133
+ }).catch(noop);
134
+ }
135
+ /**
136
+ * Sends a message to the worker or main thread
137
+ *
138
+ * @param message - The message to send
139
+ * @template T - Type of the message body
140
+ * @internal Used by @Request decorator
141
+ */
22
142
  [SEND](message) {
23
- if (this[WORKER]) {
24
- this[WORKER].postMessage(message);
25
- }
26
- else {
27
- postMessage(message);
28
- }
143
+ this.#worker.then(worker => {
144
+ if (worker) {
145
+ // Main thread: send to worker
146
+ worker.postMessage(message);
147
+ }
148
+ else {
149
+ // Worker thread: send to main thread
150
+ postMessage(message);
151
+ }
152
+ }).catch(noop);
29
153
  }
30
- [HANDLER] = (event) => {
154
+ /**
155
+ * Handles incoming messages and forwards them to the responses stream
156
+ * @private
157
+ */
158
+ #handler = (event) => {
31
159
  this[RESPONSES$].next(event.data);
32
160
  };
161
+ /**
162
+ * Generates a unique message ID for tracking request-response pairs
163
+ *
164
+ * @returns Unique message identifier
165
+ * @internal Used by @Request decorator
166
+ */
33
167
  [GET_NEW_ID]() {
34
- return uniqueId('hermes-worker-message-' + this[INSTANCE_ID]);
168
+ return uniqueId('hermes-worker-message-' + this.#instanceId);
35
169
  }
36
170
  }
37
171
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../libs/hermes/src/worker/message-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,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;AAM5D,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAChC,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAClC,MAAM,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAE1C,MAAM,OAAO,mBAAoB,SAAQ,aAAa;IAC7C,CAAC,UAAU,CAAC,GAAG,IAAI,OAAO,EAAmB,CAAC;IAC3C,CAAC,MAAM,CAAC,CAAqB;IAC/B,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEnC,YAAY,MAAe;QACzB,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;QAEtB,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QACpD,CAAC;aAAM,CAAC;YACN,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;IAEM,CAAC,IAAI,CAAC,CAAI,OAAmB;QAClC,IAAI,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;aAAM,CAAC;YACL,WAAmB,CAAC,OAAO,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAES,CAAC,OAAO,CAAC,GAAG,CAAC,KAAoC,EAAE,EAAE;QAC7D,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC,CAAA;IAES,CAAC,UAAU,CAAC;QACpB,OAAO,QAAQ,CAAC,wBAAwB,GAAG,IAAI,CAAC,WAAW,CAAC,CAAW,CAAC;IAC1E,CAAC;CACF","file":"message-client.js","sourcesContent":["import { uniqueId } from \"@thalesrc/js-utils\";\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\ninterface MessageEvent<T> {\n data: T;\n}\n\nconst WORKER = Symbol('Worker');\nconst HANDLER = Symbol('Handler');\nconst INSTANCE_ID = Symbol('Instance Id');\n\nexport class WorkerMessageClient extends MessageClient {\n public [RESPONSES$] = new Subject<MessageResponse>();\n protected [WORKER]: Worker | undefined;\n private [INSTANCE_ID] = Date.now();\n\n constructor(worker?: Worker) {\n super();\n\n this[WORKER] = worker;\n\n if (worker) {\n worker.addEventListener('message', this[HANDLER]);\n } else {\n addEventListener('message', this[HANDLER]);\n }\n }\n\n public [SEND]<T>(message: Message<T>) {\n if (this[WORKER]) {\n this[WORKER].postMessage(message);\n } else {\n (postMessage as any)(message);\n }\n }\n\n protected [HANDLER] = (event: MessageEvent<MessageResponse>) => {\n this[RESPONSES$].next(event.data);\n }\n\n protected [GET_NEW_ID](): string {\n return uniqueId('hermes-worker-message-' + this[INSTANCE_ID]) as string;\n }\n}\n"]}
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;AAO5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,MAAM,OAAO,mBAAoB,SAAQ,aAAa;IACpD;;;OAGG;IACH,OAAO,GAAwB,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAE1D;;;OAGG;IACH,WAAW,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEzB;;OAEG;IACI,CAAC,UAAU,CAAC,GAAG,IAAI,OAAO,EAAmB,CAAC;IAErD;;;;;;;;;OASG;IACH,YAAY,MAAwB;QAClC,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,UAAU,CAAC,MAAwB;QACjC,sCAAsC;QACtC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;YAC7B,IAAI,UAAU,EAAE,CAAC;gBACf,UAAU,CAAC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC3D,CAAC;iBAAM,CAAC;gBACN,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;YAChD,CAAC;QACH,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAEf,uFAAuF;QACvF,MAAM,OAAO,GAAuD,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;QACrH,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\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 | 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 {