@hybrid-compute/worker 0.38.0 → 0.39.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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.39.0](https://github.com/phun-ky/hybrid-compute/compare/%40hybrid-compute%2Fworker%400.38.1...%40hybrid-compute%2Fworker%400.39.0) (2026-10-20)
4
+
5
+ ### ⚠ BREAKING CHANGES
6
+
7
+ * the packages are compiled to ES2022 instead of ES2020.
8
+ They need Node.js 22 (as engines already says) or a browser from 2022 or
9
+
10
+ ### Tasks
11
+
12
+ * 🤖 @hybrid-compute/core@0.40.0 ([7a36295](https://github.com/phun-ky/hybrid-compute/commit/7a3629597fa33cd43867ccf283f8d4a4cfd4052f))
13
+ * 🤖 compile to ES2022, publish src, and add an exports map ([da90b30](https://github.com/phun-ky/hybrid-compute/commit/da90b30788ad52b33bd99f7739d8d32191024464)), references [#87](https://github.com/phun-ky/hybrid-compute/issues/87)
14
+
15
+ ## [0.38.1](https://github.com/phun-ky/hybrid-compute/compare/%40hybrid-compute%2Fworker%400.38.0...%40hybrid-compute%2Fworker%400.38.1) (2026-10-20)
16
+
17
+ ### Bug
18
+
19
+ * 🐛 publish the built files: add files to every package.json ([6cb3c1a](https://github.com/phun-ky/hybrid-compute/commit/6cb3c1a91bd0cefd9eb12e0718b183a47f68181c))
20
+
3
21
  ## [0.38.0](https://github.com/phun-ky/hybrid-compute/compare/%40hybrid-compute%2Fworker%400.37.3...%40hybrid-compute%2Fworker%400.38.0) (2026-10-20)
4
22
 
5
23
  ### ⚠ BREAKING CHANGES
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Why a worker task failed: the worker script replied with an `error`, the
3
+ * reply was unusable, the worker crashed or couldn't start, the input couldn't
4
+ * be sent, the timeout passed, or the backend was closed.
5
+ *
6
+ * A task cancelled with an `AbortSignal` rejects with the signal's reason
7
+ * instead, so a `WorkerTaskError` always means something went wrong.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * try {
12
+ * await threaded.runTask('resizeImage', blob);
13
+ * } catch (error) {
14
+ * if (error instanceof WorkerTaskError) {
15
+ * console.warn(`${error.taskName} failed`, error.detail);
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export declare class WorkerTaskError extends Error {
21
+ /** The name of the task that failed. */
22
+ readonly taskName: string;
23
+ /** The worker script's `error` value as it was sent, if it sent one. */
24
+ readonly detail?: unknown;
25
+ /**
26
+ * @param taskName - The name of the task that failed.
27
+ * @param message - What went wrong.
28
+ * @param details - The worker script's error value and the underlying
29
+ * error, where there is one.
30
+ */
31
+ constructor(taskName: string, message: string, details?: {
32
+ detail?: unknown;
33
+ cause?: unknown;
34
+ });
35
+ }
36
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,wCAAwC;IACxC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,wEAAwE;IACxE,SAAiB,MAAM,CAAC,EAAE,OAAO,CAAC;IAElC;;;;;OAKG;gBAED,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAO;CAYtD"}
package/dist/errors.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Why a worker task failed: the worker script replied with an `error`, the
3
+ * reply was unusable, the worker crashed or couldn't start, the input couldn't
4
+ * be sent, the timeout passed, or the backend was closed.
5
+ *
6
+ * A task cancelled with an `AbortSignal` rejects with the signal's reason
7
+ * instead, so a `WorkerTaskError` always means something went wrong.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * try {
12
+ * await threaded.runTask('resizeImage', blob);
13
+ * } catch (error) {
14
+ * if (error instanceof WorkerTaskError) {
15
+ * console.warn(`${error.taskName} failed`, error.detail);
16
+ * }
17
+ * }
18
+ * ```
19
+ */
20
+ export class WorkerTaskError extends Error {
21
+ /** The name of the task that failed. */
22
+ taskName;
23
+ /**
24
+ * @param taskName - The name of the task that failed.
25
+ * @param message - What went wrong.
26
+ * @param details - The worker script's error value and the underlying
27
+ * error, where there is one.
28
+ */
29
+ constructor(taskName, message, details = {}) {
30
+ // Error's own cause option (ES2022), only when there is a cause
31
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
32
+ this.name = 'WorkerTaskError';
33
+ this.taskName = taskName;
34
+ if ('detail' in details)
35
+ this.detail = details.detail;
36
+ }
37
+ }
38
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,wCAAwC;IAC/B,QAAQ,CAAS;IAK1B;;;;;OAKG;IACH,YACE,QAAgB,EAChB,OAAe,EACf,UAAiD,EAAE;QAEnD,gEAAgE;QAChE,KAAK,CACH,OAAO,EACP,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CACnE,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,QAAQ,IAAI,OAAO;YAAE,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACxD,CAAC;CACF"}
@@ -0,0 +1,39 @@
1
+ import type { WorkerScopeInterface, WorkerTaskType } from './types.js';
2
+ /**
3
+ * Answers tasks from {@link ThreadedCompute} in a worker script: it listens
4
+ * for task messages, runs the task with that name, and replies with its
5
+ * result, or with an error if the task throws, rejects or doesn't exist.
6
+ *
7
+ * Each task gets the input and a context with a `signal`, which aborts when
8
+ * the caller cancels the task or its timeout passes. A task that checks the
9
+ * signal can stop early; its reply is then not sent.
10
+ *
11
+ * @param tasks - The tasks, by name. List the same names in `canRunTasks`.
12
+ * @param scope - Where to listen and reply. Defaults to the worker's global
13
+ * scope.
14
+ *
15
+ * @throws {TypeError} If `tasks` isn't an object of functions, or if it's
16
+ * called outside a worker without a `scope`.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * // worker.js
21
+ * import { exposeTasks } from '@hybrid-compute/worker';
22
+ *
23
+ * exposeTasks({
24
+ * double: (n: number) => n * 2,
25
+ * slowSum: async (numbers: number[], { signal }) => {
26
+ * let sum = 0;
27
+ *
28
+ * for (const n of numbers) {
29
+ * signal.throwIfAborted();
30
+ * sum += n;
31
+ * }
32
+ *
33
+ * return sum;
34
+ * }
35
+ * });
36
+ * ```
37
+ */
38
+ export declare function exposeTasks(tasks: Readonly<Record<string, WorkerTaskType>>, scope?: WorkerScopeInterface): void;
39
+ //# sourceMappingURL=expose.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expose.d.ts","sourceRoot":"","sources":["../src/expose.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA6BvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,EAC/C,KAAK,CAAC,EAAE,oBAAoB,GAC3B,IAAI,CA6DN"}
package/dist/expose.js ADDED
@@ -0,0 +1,111 @@
1
+ import { describeValue, isPlainObject } from './utils.js';
2
+ /** An error as a value the structured clone algorithm can copy. */
3
+ const toErrorValue = (error) => {
4
+ if (error instanceof Error)
5
+ return { name: error.name, message: error.message };
6
+ if (typeof error === 'string')
7
+ return error;
8
+ return { message: String(error) };
9
+ };
10
+ /** The worker's global scope, or a TypeError outside a worker. */
11
+ const workerScope = () => {
12
+ const scope = globalThis;
13
+ if (!('WorkerGlobalScope' in globalThis) ||
14
+ typeof scope.addEventListener !== 'function' ||
15
+ typeof scope.postMessage !== 'function') {
16
+ throw new TypeError('exposeTasks must be called in a worker script, or be given a scope to listen on');
17
+ }
18
+ return scope;
19
+ };
20
+ /**
21
+ * Answers tasks from {@link ThreadedCompute} in a worker script: it listens
22
+ * for task messages, runs the task with that name, and replies with its
23
+ * result, or with an error if the task throws, rejects or doesn't exist.
24
+ *
25
+ * Each task gets the input and a context with a `signal`, which aborts when
26
+ * the caller cancels the task or its timeout passes. A task that checks the
27
+ * signal can stop early; its reply is then not sent.
28
+ *
29
+ * @param tasks - The tasks, by name. List the same names in `canRunTasks`.
30
+ * @param scope - Where to listen and reply. Defaults to the worker's global
31
+ * scope.
32
+ *
33
+ * @throws {TypeError} If `tasks` isn't an object of functions, or if it's
34
+ * called outside a worker without a `scope`.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * // worker.js
39
+ * import { exposeTasks } from '@hybrid-compute/worker';
40
+ *
41
+ * exposeTasks({
42
+ * double: (n: number) => n * 2,
43
+ * slowSum: async (numbers: number[], { signal }) => {
44
+ * let sum = 0;
45
+ *
46
+ * for (const n of numbers) {
47
+ * signal.throwIfAborted();
48
+ * sum += n;
49
+ * }
50
+ *
51
+ * return sum;
52
+ * }
53
+ * });
54
+ * ```
55
+ */
56
+ export function exposeTasks(tasks, scope) {
57
+ if (!isPlainObject(tasks) ||
58
+ !Object.values(tasks).every((task) => typeof task === 'function')) {
59
+ throw new TypeError(`exposeTasks expects an object of task functions, got ${describeValue(tasks)}`);
60
+ }
61
+ const target = scope ?? workerScope();
62
+ const running = new Map();
63
+ const reply = (message) => {
64
+ try {
65
+ target.postMessage(message);
66
+ }
67
+ catch (error) {
68
+ // A result the structured clone algorithm can't copy
69
+ target.postMessage({
70
+ id: message.id,
71
+ error: {
72
+ name: 'DataCloneError',
73
+ message: `the result couldn't be sent: ${error instanceof Error ? error.message : String(error)}`
74
+ }
75
+ });
76
+ }
77
+ };
78
+ const run = async (id, name, input) => {
79
+ const controller = new AbortController();
80
+ running.set(id, controller);
81
+ try {
82
+ if (!Object.hasOwn(tasks, name)) {
83
+ throw new Error(`No task '${name}' in this worker`);
84
+ }
85
+ const result = await tasks[name](input, {
86
+ signal: controller.signal
87
+ });
88
+ if (!controller.signal.aborted)
89
+ reply({ id, result });
90
+ }
91
+ catch (error) {
92
+ if (!controller.signal.aborted)
93
+ reply({ id, error: toErrorValue(error) });
94
+ }
95
+ finally {
96
+ running.delete(id);
97
+ }
98
+ };
99
+ target.addEventListener('message', ({ data }) => {
100
+ if (!isPlainObject(data) || typeof data.id !== 'number')
101
+ return;
102
+ if (data.cancel === true) {
103
+ running.get(data.id)?.abort();
104
+ return;
105
+ }
106
+ if (typeof data.task !== 'string')
107
+ return;
108
+ void run(data.id, data.task, data.input);
109
+ });
110
+ }
111
+ //# sourceMappingURL=expose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expose.js","sourceRoot":"","sources":["../src/expose.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE1D,mEAAmE;AACnE,MAAM,YAAY,GAAG,CAAC,KAAc,EAAE,EAAE;IACtC,IAAI,KAAK,YAAY,KAAK;QACxB,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAEtD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5C,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACpC,CAAC,CAAC;AACF,kEAAkE;AAClE,MAAM,WAAW,GAAG,GAAyB,EAAE;IAC7C,MAAM,KA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C,IAAI,KAAK,QAAQ;YAAE,OAAO;QAE1C,KAAK,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,115 @@
1
+ import { type ComputeBackendInterface, type RunTaskOptionsInterface } from '@hybrid-compute/core';
2
+ import type { ThreadedComputeOptionsInterface } from './types.js';
3
+ export * from './errors.js';
4
+ export * from './expose.js';
5
+ export * from './types.js';
6
+ /**
7
+ * ThreadedCompute is a backend that runs tasks in a dedicated module Web
8
+ * Worker, so heavy work doesn't block the main thread.
9
+ *
10
+ * It starts the worker on the first task, not when it's created, sends each
11
+ * task with an id and matches the replies by id. Write the worker script with
12
+ * {@link exposeTasks}, or by hand following {@link WorkerTaskMessageInterface}
13
+ * and {@link WorkerResultMessageInterface}.
14
+ *
15
+ * Every failure (an `error` in the reply, a crash, the timeout) rejects with a
16
+ * {@link WorkerTaskError}. If the worker crashes, a new one starts on the next
17
+ * task. Call {@link ThreadedCompute.close} when you're done with it.
18
+ *
19
+ * Web Workers only exist in browsers (and Deno and Bun): where there is no
20
+ * global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
21
+ * another backend.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const threaded = createThreadedCompute({
26
+ * url: new URL('./worker.js', import.meta.url),
27
+ * canRunTasks: ['add']
28
+ * });
29
+ *
30
+ * const result = await threaded.runTask<number, number>('add', 5);
31
+ * ```
32
+ *
33
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
34
+ */
35
+ export declare class ThreadedCompute implements ComputeBackendInterface {
36
+ private readonly settings;
37
+ private worker?;
38
+ private readonly pending;
39
+ private nextId;
40
+ /**
41
+ * Creates the backend. It checks the options, and starts no worker until
42
+ * the first task.
43
+ *
44
+ * @param options - The worker script, the tasks it can run and,
45
+ * optionally, a timeout.
46
+ *
47
+ * @throws {TypeError} For a missing or wrongly typed option.
48
+ * @throws {RangeError} For a negative timeout.
49
+ */
50
+ constructor(options: ThreadedComputeOptionsInterface);
51
+ /**
52
+ * Determines if this backend can run the given task.
53
+ *
54
+ * @param taskName - Name of the task.
55
+ * @returns `true` if the task is in `canRunTasks` and this runtime has Web
56
+ * Workers.
57
+ */
58
+ canRun(taskName: string): boolean;
59
+ /**
60
+ * Runs a task in the worker and waits for its reply.
61
+ *
62
+ * @typeParam Input - The input type of the task.
63
+ * @typeParam Output - The output type of the task.
64
+ *
65
+ * @param taskName - The name of the task to run.
66
+ * @param input - The input for the task. It's copied with the structured
67
+ * clone algorithm, so it can't hold functions or DOM nodes.
68
+ * @param options - Options for this call. With a `signal`, `runTask`
69
+ * rejects with the signal's reason as soon as it aborts, and the worker is
70
+ * told to cancel the task.
71
+ * @returns A Promise resolving to the reply's `result`. It rejects with a
72
+ * `NoBackendError` (from `@hybrid-compute/core`) if the task isn't in
73
+ * `canRunTasks`, a `TypeError` if this runtime has no Web Workers, a
74
+ * {@link WorkerTaskError} if the task fails, and with the signal's reason
75
+ * if the call is cancelled.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * const result = await threaded.runTask('square', 9); // 81
80
+ * ```
81
+ */
82
+ runTask<Input, Output>(taskName: string, input: Input, options?: RunTaskOptionsInterface): Promise<Output>;
83
+ /**
84
+ * Terminates the worker, if one is running. Tasks still waiting for a
85
+ * reply reject with a {@link WorkerTaskError}. The next task starts a new
86
+ * worker.
87
+ */
88
+ close(): void;
89
+ /** The running worker, starting one first if needed. */
90
+ private start;
91
+ /** Match a reply to its task by id; ignore anything that can't be matched. */
92
+ private onMessage;
93
+ /** Reject every task still waiting for a reply. */
94
+ private rejectPending;
95
+ }
96
+ /**
97
+ * Creates a ThreadedCompute backend.
98
+ *
99
+ * @param options - The worker script, the tasks it can run and,
100
+ * optionally, a timeout.
101
+ * @returns A new `ThreadedCompute` instance.
102
+ *
103
+ * @throws {TypeError} For a missing or wrongly typed option.
104
+ * @throws {RangeError} For a negative timeout.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const backend = createThreadedCompute({
109
+ * url: new URL('./worker.js', import.meta.url),
110
+ * canRunTasks: ['resizeImage']
111
+ * });
112
+ * ```
113
+ */
114
+ export declare function createThreadedCompute(options: ThreadedComputeOptionsInterface): ThreadedCompute;
115
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC7B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,KAAK,EACV,+BAA+B,EAGhC,MAAM,YAAY,CAAC;AAGpB,cAAc,aAAa,CAAC;AAE5B,cAAc,aAAa,CAAC;AAE5B,cAAc,YAAY,CAAC;AA+D3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,eAAgB,YAAW,uBAAuB;IAC7D,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgC;IACzD,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsC;IAC9D,OAAO,CAAC,MAAM,CAAK;IAEnB;;;;;;;;;OASG;gBACS,OAAO,EAAE,+BAA+B;IAIpD;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAIjC;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACG,OAAO,CAAC,KAAK,EAAE,MAAM,EACzB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,KAAK,EACZ,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,CAAC,MAAM,CAAC;IA2FlB;;;;OAIG;IACH,KAAK,IAAI,IAAI;IAQb,wDAAwD;IACxD,OAAO,CAAC,KAAK;IA4Cb,8EAA8E;IAC9E,OAAO,CAAC,SAAS;IAkCjB,mDAAmD;IACnD,OAAO,CAAC,aAAa;CAWtB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,+BAA+B,mBAGzC"}
package/dist/index.js ADDED
@@ -0,0 +1,278 @@
1
+ import { NoBackendError } from '@hybrid-compute/core';
2
+ import { WorkerTaskError } from './errors.js';
3
+ import { describeValue, isPlainObject, messageOf } from './utils.js';
4
+ export * from './errors.js';
5
+ export * from './expose.js';
6
+ export * from './types.js';
7
+ /** Whether this runtime has Web Workers. */
8
+ const hasWorkers = () => typeof Worker === 'function';
9
+ /**
10
+ * Check the options and return them normalised.
11
+ *
12
+ * @throws {TypeError} For a missing or wrongly typed option.
13
+ * @throws {RangeError} For a negative timeout.
14
+ */
15
+ const toSettings = (options) => {
16
+ if (!isPlainObject(options)) {
17
+ throw new TypeError(`createThreadedCompute expects an options object, got ${describeValue(options)}`);
18
+ }
19
+ const { url, canRunTasks, timeout } = options;
20
+ if (!(url instanceof URL) && (typeof url !== 'string' || url === '')) {
21
+ throw new TypeError(`url must be a URL or a non-empty string, got ${describeValue(url)}`);
22
+ }
23
+ if (!Array.isArray(canRunTasks) ||
24
+ !canRunTasks.every((name) => typeof name === 'string' && name !== '')) {
25
+ throw new TypeError(`canRunTasks must be an array of task names, got ${describeValue(canRunTasks)}`);
26
+ }
27
+ if (timeout !== undefined &&
28
+ (typeof timeout !== 'number' || !Number.isFinite(timeout))) {
29
+ throw new TypeError(`timeout must be a number of milliseconds, got ${describeValue(timeout)}`);
30
+ }
31
+ if (typeof timeout === 'number' && timeout < 0) {
32
+ throw new RangeError(`timeout must be 0 (no timeout) or more, got ${timeout}`);
33
+ }
34
+ return {
35
+ url: url,
36
+ tasks: new Set(canRunTasks),
37
+ timeout: timeout ?? 0
38
+ };
39
+ };
40
+ /**
41
+ * ThreadedCompute is a backend that runs tasks in a dedicated module Web
42
+ * Worker, so heavy work doesn't block the main thread.
43
+ *
44
+ * It starts the worker on the first task, not when it's created, sends each
45
+ * task with an id and matches the replies by id. Write the worker script with
46
+ * {@link exposeTasks}, or by hand following {@link WorkerTaskMessageInterface}
47
+ * and {@link WorkerResultMessageInterface}.
48
+ *
49
+ * Every failure (an `error` in the reply, a crash, the timeout) rejects with a
50
+ * {@link WorkerTaskError}. If the worker crashes, a new one starts on the next
51
+ * task. Call {@link ThreadedCompute.close} when you're done with it.
52
+ *
53
+ * Web Workers only exist in browsers (and Deno and Bun): where there is no
54
+ * global `Worker`, `canRun` returns `false`, so the `auto` strategy uses
55
+ * another backend.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const threaded = createThreadedCompute({
60
+ * url: new URL('./worker.js', import.meta.url),
61
+ * canRunTasks: ['add']
62
+ * });
63
+ *
64
+ * const result = await threaded.runTask<number, number>('add', 5);
65
+ * ```
66
+ *
67
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker
68
+ */
69
+ export class ThreadedCompute {
70
+ settings;
71
+ worker;
72
+ pending = new Map();
73
+ nextId = 1;
74
+ /**
75
+ * Creates the backend. It checks the options, and starts no worker until
76
+ * the first task.
77
+ *
78
+ * @param options - The worker script, the tasks it can run and,
79
+ * optionally, a timeout.
80
+ *
81
+ * @throws {TypeError} For a missing or wrongly typed option.
82
+ * @throws {RangeError} For a negative timeout.
83
+ */
84
+ constructor(options) {
85
+ this.settings = toSettings(options);
86
+ }
87
+ /**
88
+ * Determines if this backend can run the given task.
89
+ *
90
+ * @param taskName - Name of the task.
91
+ * @returns `true` if the task is in `canRunTasks` and this runtime has Web
92
+ * Workers.
93
+ */
94
+ canRun(taskName) {
95
+ return hasWorkers() && this.settings.tasks.has(taskName);
96
+ }
97
+ /**
98
+ * Runs a task in the worker and waits for its reply.
99
+ *
100
+ * @typeParam Input - The input type of the task.
101
+ * @typeParam Output - The output type of the task.
102
+ *
103
+ * @param taskName - The name of the task to run.
104
+ * @param input - The input for the task. It's copied with the structured
105
+ * clone algorithm, so it can't hold functions or DOM nodes.
106
+ * @param options - Options for this call. With a `signal`, `runTask`
107
+ * rejects with the signal's reason as soon as it aborts, and the worker is
108
+ * told to cancel the task.
109
+ * @returns A Promise resolving to the reply's `result`. It rejects with a
110
+ * `NoBackendError` (from `@hybrid-compute/core`) if the task isn't in
111
+ * `canRunTasks`, a `TypeError` if this runtime has no Web Workers, a
112
+ * {@link WorkerTaskError} if the task fails, and with the signal's reason
113
+ * if the call is cancelled.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const result = await threaded.runTask('square', 9); // 81
118
+ * ```
119
+ */
120
+ async runTask(taskName, input, options) {
121
+ if (!this.settings.tasks.has(taskName)) {
122
+ throw new NoBackendError(taskName, 'worker', `The worker can't run task '${taskName}'; it isn't in canRunTasks`);
123
+ }
124
+ if (!hasWorkers()) {
125
+ throw new TypeError('Web Workers are not available in this runtime; @hybrid-compute/worker needs a global Worker');
126
+ }
127
+ const signal = options?.signal;
128
+ if (signal?.aborted)
129
+ throw signal.reason;
130
+ const worker = this.start(taskName);
131
+ const { timeout } = this.settings;
132
+ const id = this.nextId++;
133
+ return new Promise((resolve, reject) => {
134
+ let timer;
135
+ const finish = () => {
136
+ clearTimeout(timer);
137
+ signal?.removeEventListener('abort', onAbort);
138
+ this.pending.delete(id);
139
+ };
140
+ // Settled before the worker replied: tell the worker to stop
141
+ const cancel = () => {
142
+ const message = { id, cancel: true };
143
+ worker.postMessage(message);
144
+ };
145
+ const onAbort = () => {
146
+ finish();
147
+ cancel();
148
+ reject(signal?.reason);
149
+ };
150
+ if (timeout > 0) {
151
+ timer = setTimeout(() => {
152
+ finish();
153
+ cancel();
154
+ reject(new WorkerTaskError(taskName, `Worker task '${taskName}' timed out after ${timeout} ms`));
155
+ }, timeout);
156
+ }
157
+ signal?.addEventListener('abort', onAbort, { once: true });
158
+ this.pending.set(id, {
159
+ taskName,
160
+ resolve: (value) => {
161
+ finish();
162
+ resolve(value);
163
+ },
164
+ reject: (reason) => {
165
+ finish();
166
+ reject(reason);
167
+ }
168
+ });
169
+ const message = {
170
+ id,
171
+ task: taskName,
172
+ input
173
+ };
174
+ try {
175
+ worker.postMessage(message);
176
+ }
177
+ catch (error) {
178
+ this.pending
179
+ .get(id)
180
+ ?.reject(new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't send its input to the worker`, { cause: error }));
181
+ }
182
+ });
183
+ }
184
+ /**
185
+ * Terminates the worker, if one is running. Tasks still waiting for a
186
+ * reply reject with a {@link WorkerTaskError}. The next task starts a new
187
+ * worker.
188
+ */
189
+ close() {
190
+ const { worker } = this;
191
+ this.worker = undefined;
192
+ worker?.terminate();
193
+ this.rejectPending('the worker was closed');
194
+ }
195
+ /** The running worker, starting one first if needed. */
196
+ start(taskName) {
197
+ if (this.worker)
198
+ return this.worker;
199
+ let worker;
200
+ try {
201
+ worker = new Worker(this.settings.url, { type: 'module' });
202
+ }
203
+ catch (error) {
204
+ throw new WorkerTaskError(taskName, `Worker task '${taskName}' couldn't start the worker ${String(this.settings.url)}`, { cause: error });
205
+ }
206
+ worker.addEventListener('message', (event) => this.onMessage(event));
207
+ // An uncaught error, or a script that fails to load: the worker is in an
208
+ // unknown state, so reject what it was doing and start over next time
209
+ worker.addEventListener('error', (event) => {
210
+ if (this.worker !== worker)
211
+ return;
212
+ const detail = event.message;
213
+ this.worker = undefined;
214
+ worker.terminate();
215
+ this.rejectPending(detail
216
+ ? `the worker threw: ${detail}`
217
+ : 'the worker failed: its script did not load, or threw while starting', event);
218
+ });
219
+ // A reply that couldn't be deserialised: nothing tells which task it
220
+ // was for, so reject them all instead of letting one wait forever
221
+ worker.addEventListener('messageerror', (event) => {
222
+ if (this.worker !== worker)
223
+ return;
224
+ this.rejectPending('a reply from the worker could not be read', event);
225
+ });
226
+ this.worker = worker;
227
+ return worker;
228
+ }
229
+ /** Match a reply to its task by id; ignore anything that can't be matched. */
230
+ onMessage(event) {
231
+ const reply = event.data;
232
+ if (!isPlainObject(reply) || typeof reply.id !== 'number')
233
+ return;
234
+ const task = this.pending.get(reply.id);
235
+ if (!task)
236
+ return;
237
+ const { taskName } = task;
238
+ const { error } = reply;
239
+ if (error !== undefined && error !== null) {
240
+ const text = messageOf(error);
241
+ task.reject(new WorkerTaskError(taskName, `Worker task '${taskName}' failed${text ? `: ${text}` : ''}`, { detail: error }));
242
+ }
243
+ else if ('result' in reply) {
244
+ task.resolve(reply.result);
245
+ }
246
+ else {
247
+ task.reject(new WorkerTaskError(taskName, `Worker task '${taskName}' got a reply with neither a result nor an error`));
248
+ }
249
+ }
250
+ /** Reject every task still waiting for a reply. */
251
+ rejectPending(why, cause) {
252
+ for (const task of [...this.pending.values()]) {
253
+ task.reject(new WorkerTaskError(task.taskName, `Worker task '${task.taskName}' got no reply: ${why}`, { cause }));
254
+ }
255
+ }
256
+ }
257
+ /**
258
+ * Creates a ThreadedCompute backend.
259
+ *
260
+ * @param options - The worker script, the tasks it can run and,
261
+ * optionally, a timeout.
262
+ * @returns A new `ThreadedCompute` instance.
263
+ *
264
+ * @throws {TypeError} For a missing or wrongly typed option.
265
+ * @throws {RangeError} For a negative timeout.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * const backend = createThreadedCompute({
270
+ * url: new URL('./worker.js', import.meta.url),
271
+ * canRunTasks: ['resizeImage']
272
+ * });
273
+ * ```
274
+ */
275
+ export function createThreadedCompute(options) {
276
+ return new ThreadedCompute(options);
277
+ }
278
+ //# sourceMappingURL=index.js.map