@hybrid-compute/worker 0.38.0 → 0.38.1

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.
@@ -1,5 +1,4 @@
1
1
  import type { TaskContextInterface } from '@hybrid-compute/core';
2
-
3
2
  /**
4
3
  * Options for {@link createThreadedCompute}.
5
4
  *
@@ -21,11 +20,10 @@ import type { TaskContextInterface } from '@hybrid-compute/core';
21
20
  * ```
22
21
  */
23
22
  export interface ThreadedComputeOptionsInterface {
24
- url: string | URL;
25
- canRunTasks: readonly string[];
26
- timeout?: number;
23
+ url: string | URL;
24
+ canRunTasks: readonly string[];
25
+ timeout?: number;
27
26
  }
28
-
29
27
  /**
30
28
  * What the worker script receives for each task: the task name, its input
31
29
  * and an `id`, which the reply must repeat. The input is copied with the
@@ -39,11 +37,10 @@ export interface ThreadedComputeOptionsInterface {
39
37
  * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
40
38
  */
41
39
  export interface WorkerTaskMessageInterface<Input = unknown> {
42
- id: number;
43
- task: string;
44
- input: Input;
40
+ id: number;
41
+ task: string;
42
+ input: Input;
45
43
  }
46
-
47
44
  /**
48
45
  * What the worker script receives when a task is cancelled or times out:
49
46
  * the task's `id` and `cancel: true`. {@link exposeTasks} aborts the task's
@@ -55,10 +52,9 @@ export interface WorkerTaskMessageInterface<Input = unknown> {
55
52
  * ```
56
53
  */
57
54
  export interface WorkerCancelMessageInterface {
58
- id: number;
59
- cancel: true;
55
+ id: number;
56
+ cancel: true;
60
57
  }
61
-
62
58
  /**
63
59
  * What the worker script sends back: the task's `id` with either a `result`
64
60
  * or an `error`. An `error` (a message string, or an object with a `message`)
@@ -70,11 +66,10 @@ export interface WorkerCancelMessageInterface {
70
66
  * ```
71
67
  */
72
68
  export interface WorkerResultMessageInterface<Output = unknown> {
73
- id: number;
74
- result?: Output;
75
- error?: unknown;
69
+ id: number;
70
+ result?: Output;
71
+ error?: unknown;
76
72
  }
77
-
78
73
  /**
79
74
  * A task in the worker script, for {@link exposeTasks}. It gets the input and
80
75
  * a context with a `signal`, which aborts when the caller cancels the task or
@@ -83,20 +78,16 @@ export interface WorkerResultMessageInterface<Output = unknown> {
83
78
  * @typeParam Input - The input type of the task.
84
79
  * @typeParam Output - The output type of the task.
85
80
  */
86
- export type WorkerTaskType<Input = never, Output = unknown> = (
87
- input: Input,
88
- context: Required<TaskContextInterface>
89
- ) => Output | Promise<Output>;
90
-
81
+ export type WorkerTaskType<Input = never, Output = unknown> = (input: Input, context: Required<TaskContextInterface>) => Output | Promise<Output>;
91
82
  /**
92
83
  * Where {@link exposeTasks} listens and replies. Defaults to the worker's
93
84
  * global scope (`self`); pass another one to adapt it, for example to a
94
85
  * `MessagePort`.
95
86
  */
96
87
  export interface WorkerScopeInterface {
97
- addEventListener(
98
- type: 'message',
99
- listener: (event: { data: unknown }) => void
100
- ): void;
101
- postMessage(message: unknown): void;
88
+ addEventListener(type: 'message', listener: (event: {
89
+ data: unknown;
90
+ }) => void): void;
91
+ postMessage(message: unknown): void;
102
92
  }
93
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAEjE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,WAAW,+BAA+B;IAC9C,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,0BAA0B,CAAC,KAAK,GAAG,OAAO;IACzD,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,KAAK,CAAC;CACd;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,4BAA4B;IAC3C,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,IAAI,CAAC;CACd;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,4BAA4B,CAAC,MAAM,GAAG,OAAO;IAC5D,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,cAAc,CAAC,KAAK,GAAG,KAAK,EAAE,MAAM,GAAG,OAAO,IAAI,CAC5D,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,QAAQ,CAAC,oBAAoB,CAAC,KACpC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAE9B;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC,gBAAgB,CACd,IAAI,EAAE,SAAS,EACf,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAC3C,IAAI,CAAC;IACR,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;CACrC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,6 @@
1
+ /** What a value is, for error messages: null, an array, or its typeof. */
2
+ export declare const describeValue: (value: unknown) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | "null" | "an array" | "an empty string";
3
+ export declare const isPlainObject: (value: unknown) => value is Record<string, unknown>;
4
+ /** The message for an `error` value: a string, or an object's message. */
5
+ export declare const messageOf: (error: unknown) => string;
6
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,0IAQ3C,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,OAAO,OAAO,KACb,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CACoC,CAAC;AAEvE,0EAA0E;AAC1E,eAAO,MAAM,SAAS,GAAI,OAAO,OAAO,WAYvC,CAAC"}
package/dist/utils.js ADDED
@@ -0,0 +1,26 @@
1
+ /** What a value is, for error messages: null, an array, or its typeof. */
2
+ export const describeValue = (value) => {
3
+ if (value === null)
4
+ return 'null';
5
+ if (Array.isArray(value))
6
+ return 'an array';
7
+ if (value === '')
8
+ return 'an empty string';
9
+ return typeof value;
10
+ };
11
+ export const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
12
+ /** The message for an `error` value: a string, or an object's message. */
13
+ export const messageOf = (error) => {
14
+ if (typeof error === 'string')
15
+ return error;
16
+ if (isPlainObject(error) && typeof error.message === 'string') {
17
+ return error.message;
18
+ }
19
+ try {
20
+ return JSON.stringify(error);
21
+ }
22
+ catch {
23
+ return String(error);
24
+ }
25
+ };
26
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAAc,EAAE,EAAE;IAC9C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAElC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,UAAU,CAAC;IAE5C,IAAI,KAAK,KAAK,EAAE;QAAE,OAAO,iBAAiB,CAAC;IAE3C,OAAO,OAAO,KAAK,CAAC;AACtB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,KAAc,EACoB,EAAE,CACpC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAEvE,0EAA0E;AAC1E,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5C,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC9D,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hybrid-compute/worker",
3
- "version": "0.38.0",
3
+ "version": "0.38.1",
4
4
  "description": "Threaded compute backend for executing tasks in Web Workers.",
5
5
  "keywords": [
6
6
  "web-worker",
@@ -27,6 +27,10 @@
27
27
  "type": "module",
28
28
  "exports": "./dist/index.js",
29
29
  "types": "./dist/index.d.ts",
30
+ "files": [
31
+ "dist",
32
+ "CHANGELOG.md"
33
+ ],
30
34
  "scripts": {
31
35
  "clean": "rm -rf dist *.tsbuildinfo",
32
36
  "typecheck": "tsc -p tsconfig.json",
package/.release-it.json DELETED
@@ -1,83 +0,0 @@
1
- {
2
- "git": {
3
- "requireCleanWorkingDir": false,
4
- "tagName": "@hybrid-compute/worker@${version}",
5
- "commitMessage": "chore: 🤖 ${name}@${version}",
6
- "commitArgs": ["-s"]
7
- },
8
- "github": {
9
- "release": true,
10
- "releaseName": "@hybrid-compute/worker@${version}",
11
- "tokenRef": "GH_TOKEN"
12
- },
13
- "npm": {
14
- "publish": true,
15
- "skipChecks": true
16
- },
17
- "hooks": {
18
- "after:bump": [
19
- "node ../../scripts/sync-sibling-ranges.mjs ${name} ${version}",
20
- "node ../../scripts/sync-lockfile.mjs"
21
- ],
22
- "after:release": "echo Successfully released ${name} v${version}."
23
- },
24
- "plugins": {
25
- "@release-it/conventional-changelog": {
26
- "header": "# Changelog",
27
- "preset": {
28
- "name": "conventionalcommits",
29
- "types": [
30
- {
31
- "type": "chore",
32
- "section": "Tasks"
33
- },
34
- {
35
- "type": "docs",
36
- "section": "Documentation"
37
- },
38
- {
39
- "type": "feat",
40
- "section": "Feature"
41
- },
42
- {
43
- "type": "fix",
44
- "section": "Bug"
45
- },
46
- {
47
- "type": "perf",
48
- "section": "Performance change"
49
- },
50
- {
51
- "type": "refactor",
52
- "section": "Refactoring"
53
- },
54
- {
55
- "type": "release",
56
- "section": "Create a release commit",
57
- "hidden": true
58
- },
59
- {
60
- "type": "style",
61
- "section": "Markup, white-space, formatting, missing semi-colons...",
62
- "hidden": true
63
- },
64
- {
65
- "type": "test",
66
- "section": "Adding missing tests",
67
- "hidden": true
68
- }
69
- ]
70
- },
71
- "infile": "CHANGELOG.md",
72
- "tagOpts": {
73
- "prefix": "@hybrid-compute/worker@"
74
- },
75
- "commitsOpts": {
76
- "path": "."
77
- },
78
- "gitRawCommitsOpts": {
79
- "path": "."
80
- }
81
- }
82
- }
83
- }
package/eslint.config.mjs DELETED
@@ -1,3 +0,0 @@
1
- import SharedConfig from '../../eslint.config.mjs';
2
-
3
- export default SharedConfig;
@@ -1,175 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import test, { describe } from 'node:test';
3
-
4
- import { exposeTasks, WorkerScopeInterface, WorkerTaskType } from '..';
5
-
6
- /** A scope that records replies, and sends messages to the listener. */
7
- const createScope = (postMessage?: (message: unknown) => void) => {
8
- const replies: unknown[] = [];
9
- let listener: (event: { data: unknown }) => void = () => {};
10
- const scope: WorkerScopeInterface = {
11
- addEventListener: (_type, fn) => {
12
- listener = fn;
13
- },
14
- postMessage: postMessage ?? ((message) => replies.push(message))
15
- };
16
-
17
- return {
18
- scope,
19
- replies,
20
- send: (data: unknown) => listener({ data }),
21
- settled: () => new Promise((resolve) => setTimeout(resolve, 10))
22
- };
23
- };
24
- const tasks = (value: unknown) =>
25
- value as unknown as Record<string, WorkerTaskType>;
26
-
27
- describe('exposeTasks', () => {
28
- test('throws a TypeError for something that is not an object of functions', () => {
29
- for (const value of [undefined, null, [], { add: 1 }]) {
30
- assert.throws(
31
- () => exposeTasks(tasks(value), createScope().scope),
32
- TypeError
33
- );
34
- }
35
- });
36
-
37
- test('throws a TypeError outside a worker without a scope', () => {
38
- assert.throws(() => exposeTasks({}), {
39
- name: 'TypeError',
40
- message: /must be called in a worker script/
41
- });
42
- });
43
-
44
- test('listens on the global scope in a worker', async () => {
45
- const global = globalThis as Record<string, unknown>;
46
- const { scope, replies, send, settled } = createScope();
47
-
48
- Object.assign(global, {
49
- WorkerGlobalScope: class {},
50
- addEventListener: scope.addEventListener,
51
- postMessage: scope.postMessage
52
- });
53
-
54
- try {
55
- exposeTasks({ double: (n: number) => n * 2 });
56
- send({ id: 1, task: 'double', input: 4 });
57
- await settled();
58
- } finally {
59
- delete global.WorkerGlobalScope;
60
- delete global.addEventListener;
61
- delete global.postMessage;
62
- }
63
-
64
- assert.deepEqual(replies, [{ id: 1, result: 8 }]);
65
- });
66
-
67
- test('replies with the result, or with the error the task throws', async () => {
68
- const { scope, replies, send, settled } = createScope();
69
-
70
- exposeTasks(
71
- {
72
- sum: async (numbers: number[]) => numbers.reduce((a, b) => a + b, 0),
73
- error: () => {
74
- throw new RangeError('out of range');
75
- },
76
- string: () => Promise.reject('just a string'),
77
- other: () => {
78
- throw 42;
79
- }
80
- },
81
- scope
82
- );
83
- send({ id: 1, task: 'sum', input: [1, 2, 3] });
84
- send({ id: 2, task: 'error', input: null });
85
- send({ id: 3, task: 'string', input: null });
86
- send({ id: 4, task: 'other', input: null });
87
- send({ id: 5, task: 'toString', input: null });
88
- await settled();
89
- // Async tasks finish in their own time, so compare in id order
90
- replies.sort((a, b) => (a as { id: number }).id - (b as { id: number }).id);
91
- assert.deepEqual(replies, [
92
- { id: 1, result: 6 },
93
- { id: 2, error: { name: 'RangeError', message: 'out of range' } },
94
- { id: 3, error: 'just a string' },
95
- { id: 4, error: { message: '42' } },
96
- {
97
- id: 5,
98
- error: { name: 'Error', message: "No task 'toString' in this worker" }
99
- }
100
- ]);
101
- });
102
-
103
- test('ignores messages it cannot use', async () => {
104
- const { scope, replies, send, settled } = createScope();
105
-
106
- exposeTasks({ echo: (input: unknown) => input }, scope);
107
-
108
- for (const data of [
109
- null,
110
- 'echo',
111
- [],
112
- { task: 'echo' },
113
- { id: 1 },
114
- { id: 2, cancel: true }
115
- ]) {
116
- send(data);
117
- }
118
-
119
- await settled();
120
- assert.deepEqual(replies, []);
121
- });
122
-
123
- test('aborts the signal on cancel, and sends no reply', async () => {
124
- const { scope, replies, send, settled } = createScope();
125
- const seen: string[] = [];
126
-
127
- exposeTasks(
128
- {
129
- wait: (_input: unknown, { signal }) =>
130
- new Promise((resolve, reject) =>
131
- signal.addEventListener('abort', () => {
132
- seen.push('aborted');
133
- reject(signal.reason);
134
- })
135
- ),
136
- resolveAnyway: (_input: unknown, { signal }) =>
137
- new Promise((resolve) =>
138
- signal.addEventListener('abort', () => resolve('done'))
139
- )
140
- },
141
- scope
142
- );
143
- send({ id: 1, task: 'wait', input: null });
144
- send({ id: 2, task: 'resolveAnyway', input: null });
145
- send({ id: 1, cancel: true });
146
- send({ id: 2, cancel: true });
147
- await settled();
148
- assert.deepEqual(seen, ['aborted']);
149
- assert.deepEqual(replies, []);
150
- });
151
-
152
- test('replies with an error when the result cannot be sent', async () => {
153
- const replies: unknown[] = [];
154
- const { scope, send, settled } = createScope((message) => {
155
- if (typeof (message as { result?: unknown }).result === 'function') {
156
- throw new Error('() => 1 could not be cloned');
157
- }
158
-
159
- replies.push(message);
160
- });
161
-
162
- exposeTasks({ fn: () => () => 1 }, scope);
163
- send({ id: 1, task: 'fn', input: null });
164
- await settled();
165
- assert.deepEqual(replies, [
166
- {
167
- id: 1,
168
- error: {
169
- name: 'DataCloneError',
170
- message: "the result couldn't be sent: () => 1 could not be cloned"
171
- }
172
- }
173
- ]);
174
- });
175
- });
@@ -1,30 +0,0 @@
1
- // A worker script written with exposeTasks, adapted to worker_threads
2
- import { parentPort } from 'node:worker_threads';
3
-
4
- import { exposeTasks } from '../../expose.js';
5
-
6
- let aborted = 0;
7
-
8
- exposeTasks(
9
- {
10
- echo: (input: unknown) => input,
11
- double: async (n: number) => n * 2,
12
- fail: () => {
13
- throw new Error('boom');
14
- },
15
- unclonable: () => () => 1,
16
- waitForAbort: (_input: unknown, { signal }) =>
17
- new Promise((resolve) =>
18
- signal.addEventListener('abort', () => {
19
- aborted++;
20
- resolve('aborted');
21
- })
22
- ),
23
- abortedCount: () => aborted
24
- },
25
- {
26
- addEventListener: (_type, listener) =>
27
- parentPort?.on('message', (data) => listener({ data })),
28
- postMessage: (message) => parentPort?.postMessage(message)
29
- }
30
- );
@@ -1,21 +0,0 @@
1
- // A hand written worker script, answering by task name, with the replies a
2
- // worker script can get wrong
3
- import { parentPort } from 'node:worker_threads';
4
-
5
- parentPort?.on('message', ({ id, task, input }) => {
6
- const reply = (message: unknown) => parentPort?.postMessage(message);
7
-
8
- if (task === 'echo') reply({ id, result: input });
9
- else if (task === 'errorString') reply({ id, error: 'task failed' });
10
- else if (task === 'errorObject')
11
- reply({ id, error: { code: 'E_TASK', message: 'bad input' } });
12
- else if (task === 'errorEmpty') reply({ id, error: '' });
13
- else if (task === 'errorOther') reply({ id, error: 42 });
14
- // JSON can't hold a BigInt, so the message falls back to String()
15
- else if (task === 'errorBigInt') reply({ id, error: 10n });
16
- else if (task === 'noResult') reply({ id });
17
- else if (task === 'null') reply(null);
18
- else if (task === 'stranger') reply({ id: 9999, result: 'not yours' });
19
- else if (task === 'throw') throw new Error('thrown inside the worker');
20
- // 'hang', and anything else: never answer
21
- });
@@ -1,69 +0,0 @@
1
- // A small Web Worker on top of node:worker_threads, so the tests run tasks in
2
- // real threads instead of mocks. Node has no global Worker of its own.
3
- import { Worker as Thread } from 'node:worker_threads';
4
-
5
- export class ThreadWorker extends EventTarget {
6
- /** Workers started so far. */
7
- static started = 0;
8
- /** The last worker started, to send it events in tests. */
9
- static last?: ThreadWorker;
10
- private readonly thread: Thread;
11
-
12
- constructor(url: string | URL) {
13
- super();
14
-
15
- if (String(url).includes('constructor-throws')) {
16
- throw new TypeError(`Failed to construct 'Worker': bad URL ${url}`);
17
- }
18
-
19
- ThreadWorker.started++;
20
- ThreadWorker.last = this;
21
- this.thread = new Thread(new URL(url));
22
- this.thread.on('message', (data) =>
23
- this.dispatchEvent(new MessageEvent('message', { data }))
24
- );
25
- this.thread.on('error', (error: Error & { code?: string }) => {
26
- const event = new Event('error');
27
-
28
- // Browsers give no message when the script fails to load
29
- if (error.code !== 'ERR_MODULE_NOT_FOUND') {
30
- Object.assign(event, { message: error.message, error });
31
- }
32
-
33
- this.dispatchEvent(event);
34
- });
35
- }
36
-
37
- postMessage(message: unknown) {
38
- this.thread.postMessage(message);
39
- }
40
-
41
- terminate() {
42
- void this.thread.terminate();
43
- }
44
- }
45
-
46
- /** Run fn with the global Worker set to worker. */
47
- const withGlobalWorker = async <T>(
48
- worker: unknown,
49
- fn: () => T | Promise<T>
50
- ) => {
51
- const global = globalThis as { Worker?: unknown };
52
- const original = global.Worker;
53
-
54
- global.Worker = worker;
55
-
56
- try {
57
- return await fn();
58
- } finally {
59
- global.Worker = original;
60
- }
61
- };
62
-
63
- /** Run fn with ThreadWorker as the global Worker. */
64
- export const withWorker = <T>(fn: () => T | Promise<T>) =>
65
- withGlobalWorker(ThreadWorker, fn);
66
-
67
- /** Run fn with no global Worker, as in Node. */
68
- export const withoutWorker = <T>(fn: () => T | Promise<T>) =>
69
- withGlobalWorker(undefined, fn);