@vielzeug/familiar 1.0.6 → 1.0.8

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/dist/worker.js CHANGED
@@ -1,21 +1,21 @@
1
1
  import { FamiliarError as e, FamiliarInvalidOptionsError as t, FamiliarQueueFullError as n, FamiliarRuntimeError as r, FamiliarTaskError as i, FamiliarTerminatedError as a, FamiliarTimeoutError as o } from "./errors.js";
2
- import { warn as s } from "./_dev.js";
3
- import { unrefTimer as c } from "./_timers.js";
4
- import { createPool as l } from "./_pool.js";
2
+ import "./_dev.js";
3
+ import { unrefTimer as s } from "./_timers.js";
4
+ import { createPool as c } from "./_pool.js";
5
5
  //#region src/worker.ts
6
- function u(e) {
6
+ function l(e) {
7
7
  if (e.toString().includes("[native code]")) throw new t("Task function cannot be a bound or native function");
8
8
  return e;
9
9
  }
10
- var d = 512;
11
- function f(e) {
10
+ var u = 512;
11
+ function d(e) {
12
12
  if (e === void 0) return 1;
13
13
  if (e === "auto") return Math.max(1, globalThis.navigator?.hardwareConcurrency ?? 1);
14
- if (!Number.isInteger(e) || e < 1 || e > d) throw new t(`\`concurrency\` must be a positive integer ≤ ${d} or "auto"`);
14
+ if (!Number.isInteger(e) || e < 1 || e > u) throw new t(`\`concurrency\` must be a positive integer ≤ ${u} or "auto"`);
15
15
  return e;
16
16
  }
17
- function p(e = {}) {
18
- let n = f(e.concurrency), { heartbeatWindow: r, maxQueue: i, onFull: a = "reject", onSlotError: o, timeout: s } = e;
17
+ function f(e = {}) {
18
+ let n = d(e.concurrency), { heartbeatWindow: r, maxQueue: i, onFull: a = "reject", onSlotError: o, timeout: s } = e;
19
19
  if (s !== void 0 && (!Number.isFinite(s) || s <= 0)) throw new t("`timeout` must be a finite number greater than 0");
20
20
  if (i !== void 0 && (!Number.isInteger(i) || i < 1)) throw new t("`maxQueue` must be a positive integer");
21
21
  if (r !== void 0 && (!Number.isFinite(r) || r <= 0)) throw new t("`heartbeatWindow` must be a finite number greater than 0");
@@ -28,7 +28,7 @@ function p(e = {}) {
28
28
  timeout: s
29
29
  };
30
30
  }
31
- function m(e, t) {
31
+ function p(e, t) {
32
32
  return `
33
33
  const __fn = (${e.toString()});
34
34
 
@@ -57,7 +57,7 @@ self.onmessage = async function (event) {
57
57
  }
58
58
  }`.trim();
59
59
  }
60
- var h = class {
60
+ var m = class {
61
61
  config;
62
62
  onSlotError;
63
63
  disposed = !1;
@@ -110,7 +110,7 @@ var h = class {
110
110
  terminate() {
111
111
  this.disposed = !0, this.stopWorker(), this.failPending(new a());
112
112
  }
113
- dispatch(e, t, n, i, s) {
113
+ dispatch(e, t, n, i, c) {
114
114
  if (this.disposed) return Promise.reject(new a());
115
115
  let l;
116
116
  try {
@@ -121,7 +121,7 @@ var h = class {
121
121
  let u = this.config.kind === "inline" && this.config.heartbeatInterval != null ? this.config.heartbeatInterval * 2 : void 0;
122
122
  return new Promise((a, d) => {
123
123
  let f = this.taskId++, p = {
124
- emit: s,
124
+ emit: c,
125
125
  id: f,
126
126
  reject: d,
127
127
  resolve: a,
@@ -129,9 +129,9 @@ var h = class {
129
129
  };
130
130
  n !== void 0 && (p.timer = setTimeout(() => {
131
131
  this.restart(new o(n));
132
- }, n), c(p.timer)), u !== void 0 && (p.heartbeatWatchdog = setTimeout(() => {
132
+ }, n), s(p.timer)), u !== void 0 && (p.heartbeatWatchdog = setTimeout(() => {
133
133
  this.restart(new o(u));
134
- }, u), c(p.heartbeatWatchdog)), this.pending = p;
134
+ }, u), s(p.heartbeatWatchdog)), this.pending = p;
135
135
  try {
136
136
  l.postMessage({
137
137
  id: f,
@@ -153,7 +153,7 @@ var h = class {
153
153
  throw new r("Failed to create Worker", { cause: e });
154
154
  }
155
155
  else try {
156
- let t = new Blob([m(this.config.fn, this.config.heartbeatInterval)], { type: "application/javascript" }), n = URL.createObjectURL(t);
156
+ let t = new Blob([p(this.config.fn, this.config.heartbeatInterval)], { type: "application/javascript" }), n = URL.createObjectURL(t);
157
157
  try {
158
158
  e = new Worker(n);
159
159
  } finally {
@@ -168,7 +168,7 @@ var h = class {
168
168
  if ("heartbeat" in e.data) {
169
169
  t.watchdogMs !== void 0 && (clearTimeout(t.heartbeatWatchdog), t.heartbeatWatchdog = setTimeout(() => {
170
170
  this.restart(new o(t.watchdogMs));
171
- }, t.watchdogMs), c(t.heartbeatWatchdog));
171
+ }, t.watchdogMs), s(t.heartbeatWatchdog));
172
172
  return;
173
173
  }
174
174
  if ("chunk" in e.data) {
@@ -196,34 +196,32 @@ var h = class {
196
196
  this.worker &&= (this.worker.terminate(), null);
197
197
  }
198
198
  };
199
- function g(e, t) {
200
- let { concurrency: n, heartbeatWindow: r, maxQueue: i, onFull: a, onSlotError: o, timeout: s } = p(t), c = r == null ? void 0 : Math.floor(r / 2);
201
- return l(Array.from({ length: n }, () => new h({
199
+ function h(e, t) {
200
+ let { concurrency: n, heartbeatWindow: r, maxQueue: i, onFull: a, onSlotError: o, timeout: s } = f(t), l = r == null ? void 0 : Math.floor(r / 2), u = Array.from({ length: n }, () => new m({
202
201
  fn: e,
203
- heartbeatInterval: c,
202
+ heartbeatInterval: l,
204
203
  kind: "inline"
205
- }, o)), {
204
+ }, o));
205
+ return c(u, {
206
206
  concurrency: n,
207
207
  defaultTimeout: s,
208
208
  maxQueue: i,
209
209
  onFull: a
210
210
  });
211
211
  }
212
- function _(e, t) {
213
- let { concurrency: n, heartbeatWindow: r, maxQueue: i, onFull: a, onSlotError: o, timeout: c } = p(t);
214
- r !== void 0 && s("`heartbeatWindow` has no effect on module workers — the worker script must implement the heartbeat protocol manually.");
215
- let u = typeof e == "string" ? e : e.href;
216
- return l(Array.from({ length: n }, () => new h({
212
+ function g(e, t) {
213
+ let { concurrency: n, heartbeatWindow: r, maxQueue: i, onFull: a, onSlotError: o, timeout: s } = f(t), l = typeof e == "string" ? e : e.href, u = Array.from({ length: n }, () => new m({
217
214
  kind: "module",
218
- url: u
219
- }, o)), {
215
+ url: l
216
+ }, o));
217
+ return c(u, {
220
218
  concurrency: n,
221
- defaultTimeout: c,
219
+ defaultTimeout: s,
222
220
  maxQueue: i,
223
221
  onFull: a
224
222
  });
225
223
  }
226
224
  //#endregion
227
- export { e as FamiliarError, t as FamiliarInvalidOptionsError, n as FamiliarQueueFullError, r as FamiliarRuntimeError, i as FamiliarTaskError, a as FamiliarTerminatedError, o as FamiliarTimeoutError, _ as createModuleWorker, g as createWorker, u as task };
225
+ export { e as FamiliarError, t as FamiliarInvalidOptionsError, n as FamiliarQueueFullError, r as FamiliarRuntimeError, i as FamiliarTaskError, a as FamiliarTerminatedError, o as FamiliarTimeoutError, g as createModuleWorker, h as createWorker, l as task };
228
226
 
229
227
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","names":[],"sources":["../src/worker.ts"],"sourcesContent":["// Re-export all public types and classes so consumers only need one import.\nexport type {\n BatchOptions,\n GroupOptions,\n RunOptions,\n TaskFn,\n TaskGroup,\n WorkerHandle,\n WorkerOptions,\n WorkerStatus,\n} from './types';\nexport {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';\n\nimport type { SlotStrategy, TaskFn, WorkerHandle, WorkerOptions } from './types';\n\nimport { warn } from './_dev';\nimport { createPool } from './_pool';\nimport { unrefTimer } from './_timers';\nimport {\n FamiliarInvalidOptionsError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';\n\n// ─── task() — optional validation helper ─────────────────────────────────────\n\n/**\n * Optional helper that validates a function is safe to serialize for use in `createWorker`.\n *\n * `createWorker` accepts any `TaskFn` directly — this helper exists only to catch the common\n * mistake of passing a bound or native function whose body cannot be serialized.\n *\n * IMPORTANT: The function is serialized via `.toString()` and runs in an isolated Worker scope.\n * It **cannot** close over variables from the surrounding module — any outer reference resolves\n * to `undefined` inside the worker.\n *\n * @throws FamiliarInvalidOptionsError if the function is bound or native.\n *\n * @example\n * // Without task() — works fine for plain arrow functions:\n * const worker = createWorker((n: number) => n * 2);\n *\n * // With task() — catches the mistake of passing Math.sqrt directly:\n * const worker = createWorker(task((n: number) => Math.sqrt(n)));\n */\nexport function task<TInput, TOutput>(fn: TaskFn<TInput, TOutput>): TaskFn<TInput, TOutput> {\n if (fn.toString().includes('[native code]')) {\n throw new FamiliarInvalidOptionsError('Task function cannot be a bound or native function');\n }\n\n return fn;\n}\n\n// ─── Options resolution ───────────────────────────────────────────────────────\n\n/** Upper bound on `concurrency`: generous headroom over realistic hardware/IO limits while still catching obvious misconfiguration (e.g. a typo like `50000`). */\nconst MAX_CONCURRENCY = 512;\n\nfunction resolveConcurrency(value: WorkerOptions['concurrency']): number {\n if (value === undefined) return 1;\n\n if (value === 'auto') {\n return Math.max(1, globalThis.navigator?.hardwareConcurrency ?? 1);\n }\n\n if (!Number.isInteger(value) || value < 1 || value > MAX_CONCURRENCY) {\n throw new FamiliarInvalidOptionsError(`\\`concurrency\\` must be a positive integer ≤ ${MAX_CONCURRENCY} or \"auto\"`);\n }\n\n return value;\n}\n\nfunction resolveOptions(options: WorkerOptions = {}): {\n concurrency: number;\n heartbeatWindow: number | undefined;\n maxQueue: number | undefined;\n onFull: 'reject' | 'wait';\n onSlotError: WorkerOptions['onSlotError'];\n timeout: number | undefined;\n} {\n const concurrency = resolveConcurrency(options.concurrency);\n const { heartbeatWindow, maxQueue, onFull = 'reject', onSlotError, timeout } = options;\n\n if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) {\n throw new FamiliarInvalidOptionsError('`timeout` must be a finite number greater than 0');\n }\n\n if (maxQueue !== undefined && (!Number.isInteger(maxQueue) || maxQueue < 1)) {\n throw new FamiliarInvalidOptionsError('`maxQueue` must be a positive integer');\n }\n\n if (heartbeatWindow !== undefined && (!Number.isFinite(heartbeatWindow) || heartbeatWindow <= 0)) {\n throw new FamiliarInvalidOptionsError('`heartbeatWindow` must be a finite number greater than 0');\n }\n\n return { concurrency, heartbeatWindow, maxQueue, onFull, onSlotError, timeout };\n}\n\n// ─── Worker script builder ────────────────────────────────────────────────────\n\n/**\n * @security `fn.toString()` is injected verbatim into the blob script. Any code embedded in the\n * serialized function executes only inside the isolated Worker scope — no shared memory, no access\n * to the host page's globals. Risk is therefore low, but callers should only pass plain functions\n * that do not close over module scope.\n */\nfunction buildWorkerScript(fn: TaskFn<unknown, unknown>, heartbeatInterval: number | undefined): string {\n return `\nconst __fn = (${fn.toString()});\n\nself.onmessage = async function (event) {\n const { id, input, stream } = event.data;\n\n // Automatically send heartbeats at half the heartbeatWindow interval.\n let heartbeatTimer = null;\n ${heartbeatInterval != null ? `heartbeatTimer = setInterval(() => self.postMessage({ id, heartbeat: true }), ${heartbeatInterval});` : ''}\n\n try {\n if (stream) {\n const iterable = await __fn(input);\n for await (const chunk of iterable) {\n self.postMessage({ id, chunk });\n }\n self.postMessage({ id, result: undefined });\n } else {\n const result = await __fn(input);\n self.postMessage({ id, result });\n }\n } catch (error) {\n self.postMessage({ id, error });\n } finally {\n if (heartbeatTimer) clearInterval(heartbeatTimer);\n }\n}`.trim();\n}\n\n// ─── SlotConfig discriminated union ──────────────────────────────────────────\n\ntype SlotConfig<TInput, TOutput> =\n | { fn: TaskFn<TInput, TOutput>; heartbeatInterval: number | undefined; kind: 'inline' }\n | { kind: 'module'; url: string };\n\n// ─── PendingTask ─────────────────────────────────────────────────────────────\n\ntype SlotMessage<TOutput> =\n | { error: unknown; id: number }\n | { chunk: TOutput; id: number }\n | { heartbeat: true; id: number }\n | { id: number; result: TOutput };\n\ntype PendingTask<TOutput> = {\n /** Emits intermediate stream chunks. Undefined for non-streaming tasks. */\n emit?: (chunk: TOutput) => void;\n /** Called with an error when the streaming dispatch is cancelled mid-flight, so the finish closure drains its waiters. */\n finishStream?: (err: unknown) => void;\n /**\n * Single-shot timer that fires if no heartbeat is received within watchdogMs.\n * Reset (cleared + recreated) on every incoming heartbeat message.\n * Uses setTimeout because the watchdog is conceptually one-shot with manual reset,\n * not a recurring interval.\n */\n heartbeatWatchdog?: ReturnType<typeof setTimeout>;\n id: number;\n reject: (reason: unknown) => void;\n resolve: (value: TOutput) => void;\n timer?: ReturnType<typeof setTimeout>;\n /** Watchdog window in ms (= heartbeatWindow). Stored on PendingTask to reset the timer on each heartbeat. */\n watchdogMs?: number;\n};\n\n// ─── Slot — implements SlotStrategy ──────────────────────────────────────────\n\nclass Slot<TInput, TOutput> implements SlotStrategy<TInput, TOutput> {\n private readonly config: SlotConfig<TInput, TOutput>;\n private readonly onSlotError: WorkerOptions['onSlotError'];\n private disposed = false;\n private pending: PendingTask<TOutput> | null = null;\n private taskId = 0;\n private worker: Worker | null = null;\n\n constructor(config: SlotConfig<TInput, TOutput>, onSlotError?: WorkerOptions['onSlotError']) {\n this.config = config;\n this.onSlotError = onSlotError;\n }\n\n prime(): Promise<void> {\n if (this.disposed) return Promise.resolve();\n\n try {\n this.ensureWorker();\n } catch {\n // Best-effort — errors surface on the first run() call.\n }\n\n return Promise.resolve();\n }\n\n run(input: TInput, transferables: Transferable[], timeout: number | undefined): Promise<TOutput> {\n return this.dispatch(input, transferables, timeout, false) as Promise<TOutput>;\n }\n\n runStream(input: TInput, transferables: Transferable[], timeout: number | undefined): AsyncIterable<TOutput> {\n const chunks: TOutput[] = [];\n let done = false;\n let error: unknown;\n const waiters: Array<() => void> = [];\n\n const emit = (chunk: TOutput) => {\n chunks.push(chunk);\n waiters.shift()?.();\n };\n\n const finish = (err?: unknown) => {\n done = true;\n error = err;\n\n for (const w of waiters.splice(0)) w();\n };\n\n // Dispatch the task in stream mode. The promise resolves when the worker signals done.\n // finishStream is stored on the PendingTask so cancel() can drain the waiters if the\n // consumer exits early (break/throw from for-await), preventing a permanently dangling Promise.\n // this.pending is set synchronously inside dispatch(), so this assignment is safe.\n this.dispatch(input, transferables, timeout, true, emit).then(() => finish(), finish);\n\n if (this.pending) this.pending.finishStream = finish;\n\n return {\n [Symbol.asyncIterator]() {\n let cursor = 0;\n\n return {\n async next(): Promise<IteratorResult<TOutput>> {\n while (cursor >= chunks.length && !done) {\n await new Promise<void>((resolve) => waiters.push(resolve));\n }\n\n if (cursor < chunks.length) {\n const value = chunks[cursor]!;\n\n // Null-out the consumed slot so GC can collect the value\n // without waiting for the entire stream to close.\n (chunks as (TOutput | null)[])[cursor] = null;\n cursor++;\n\n return { done: false, value };\n }\n\n if (error !== undefined) throw error;\n\n return { done: true, value: undefined as unknown as TOutput };\n },\n };\n },\n };\n }\n\n cancel(): void {\n const pending = this.pending;\n\n if (!pending) return;\n\n clearTimeout(pending.timer);\n clearTimeout(pending.heartbeatWatchdog);\n this.pending = null;\n // Terminate the worker: the streaming task may still be running and sending chunks.\n // A fresh worker is created on the next run() or runStream() call via ensureWorker().\n this.stopWorker();\n // Drain the stream finish closure so any pending .next() waiters resolve immediately\n // rather than leaking as permanently dangling Promises.\n pending.finishStream?.(new FamiliarTerminatedError('Stream was cancelled'));\n }\n\n terminate(): void {\n this.disposed = true;\n this.stopWorker();\n this.failPending(new FamiliarTerminatedError());\n }\n\n private dispatch(\n input: TInput,\n transferables: Transferable[],\n timeout: number | undefined,\n stream: boolean,\n emit?: (chunk: TOutput) => void,\n ): Promise<TOutput | void> {\n if (this.disposed) {\n return Promise.reject(new FamiliarTerminatedError());\n }\n\n let worker: Worker;\n\n try {\n worker = this.ensureWorker();\n } catch (error) {\n return Promise.reject(error);\n }\n\n // watchdogMs = heartbeatInterval * 2 (Nyquist margin: worker beats at interval, host allows 2× before firing).\n const watchdogMs =\n this.config.kind === 'inline' && this.config.heartbeatInterval != null\n ? this.config.heartbeatInterval * 2\n : undefined;\n\n return new Promise<TOutput | void>((resolve, reject) => {\n const id = this.taskId++;\n const pending: PendingTask<TOutput> = {\n emit,\n id,\n reject,\n resolve: resolve as (v: TOutput) => void,\n watchdogMs,\n };\n\n if (timeout !== undefined) {\n pending.timer = setTimeout(() => {\n this.restart(new FamiliarTimeoutError(timeout));\n }, timeout);\n unrefTimer(pending.timer);\n }\n\n if (watchdogMs !== undefined) {\n pending.heartbeatWatchdog = setTimeout(() => {\n this.restart(new FamiliarTimeoutError(watchdogMs));\n }, watchdogMs);\n unrefTimer(pending.heartbeatWatchdog);\n }\n\n this.pending = pending;\n\n try {\n worker.postMessage({ id, input, stream }, transferables);\n } catch (err) {\n this.failPending(new FamiliarRuntimeError(err instanceof Error ? err.message : String(err), { cause: err }));\n }\n });\n }\n\n private ensureWorker(): Worker {\n if (this.worker) return this.worker;\n\n if (typeof globalThis.Worker !== 'function') {\n throw new FamiliarRuntimeError('Worker API is unavailable in this runtime');\n }\n\n let worker: Worker;\n\n if (this.config.kind === 'module') {\n try {\n worker = new Worker(this.config.url, { type: 'module' });\n } catch (error) {\n throw new FamiliarRuntimeError('Failed to create Worker', { cause: error });\n }\n } else {\n try {\n const blob = new Blob(\n [buildWorkerScript(this.config.fn as TaskFn<unknown, unknown>, this.config.heartbeatInterval)],\n { type: 'application/javascript' },\n );\n const url = URL.createObjectURL(blob);\n\n try {\n worker = new Worker(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n } catch (error) {\n throw new FamiliarRuntimeError('Failed to create Worker', { cause: error });\n }\n }\n\n worker.onmessage = (event: MessageEvent<SlotMessage<TOutput>>) => {\n const pending = this.pending;\n\n if (!pending || event.data.id !== pending.id) return;\n\n // Handle heartbeat message — reset the watchdog timer.\n if ('heartbeat' in event.data) {\n if (pending.watchdogMs !== undefined) {\n clearTimeout(pending.heartbeatWatchdog);\n pending.heartbeatWatchdog = setTimeout(() => {\n this.restart(new FamiliarTimeoutError(pending.watchdogMs!));\n }, pending.watchdogMs);\n unrefTimer(pending.heartbeatWatchdog);\n }\n\n return;\n }\n\n if ('chunk' in event.data) {\n pending.emit?.(event.data.chunk);\n\n return;\n }\n\n clearTimeout(pending.timer);\n clearTimeout(pending.heartbeatWatchdog);\n this.pending = null;\n\n if ('error' in event.data) {\n const cause = event.data.error instanceof Error ? event.data.error : new Error(String(event.data.error));\n\n pending.reject(new FamiliarTaskError(cause.message, { cause }));\n } else {\n pending.resolve(event.data.result);\n }\n };\n\n worker.onerror = (event: ErrorEvent) => {\n const error = new FamiliarRuntimeError(event.message);\n\n // Stop and fail before calling the external callback so it sees a clean state.\n this.stopWorker();\n this.failPending(error);\n\n this.onSlotError?.(error, () => void this.prime());\n };\n\n this.worker = worker;\n\n return worker;\n }\n\n private failPending(reason: unknown): void {\n const pending = this.pending;\n\n if (!pending) return;\n\n clearTimeout(pending.timer);\n clearTimeout(pending.heartbeatWatchdog);\n this.pending = null;\n pending.reject(reason);\n }\n\n private restart(reason: unknown): void {\n this.stopWorker();\n this.failPending(reason);\n }\n\n private stopWorker(): void {\n if (!this.worker) return;\n\n this.worker.terminate();\n this.worker = null;\n }\n}\n\n// ─── createWorker ─────────────────────────────────────────────────────────────\n\n/**\n * Creates a pool of Web Workers that run `fn` in parallel.\n *\n * The task function is serialized via `.toString()` and runs in a separate global scope.\n * It cannot close over variables from the surrounding module.\n *\n * Use the optional `task()` helper to validate that the function is not bound or native.\n * For workers that need imports, see `createModuleWorker`.\n *\n * @example\n * // Plain arrow function — most common case:\n * const worker = createWorker((n: number) => n * 2);\n *\n * // With task() for validation:\n * const worker = createWorker(task((n: number) => n * 2));\n */\nexport function createWorker<TInput, TOutput>(\n fn: TaskFn<TInput, TOutput>,\n options?: WorkerOptions,\n): WorkerHandle<TInput, TOutput> {\n const { concurrency, heartbeatWindow, maxQueue, onFull, onSlotError, timeout } = resolveOptions(options);\n const heartbeatInterval = heartbeatWindow != null ? Math.floor(heartbeatWindow / 2) : undefined;\n\n const slots = Array.from(\n { length: concurrency },\n () => new Slot<TInput, TOutput>({ fn, heartbeatInterval, kind: 'inline' }, onSlotError),\n );\n\n return createPool(slots, {\n concurrency,\n defaultTimeout: timeout,\n maxQueue,\n onFull,\n });\n}\n\n// ─── createModuleWorker ───────────────────────────────────────────────────────\n\n/**\n * Creates a pool of module-type Web Workers loaded from a real URL.\n *\n * Unlike `createWorker`, the worker file is a regular module — it can import utilities,\n * use top-level await, and reference module scope.\n *\n * Use `handleMessages` from `@vielzeug/familiar/protocol` in the worker file to implement\n * the message protocol without boilerplate.\n *\n * **Protocol**: The worker module must handle the `{ id, input }` message format and reply\n * with `{ id, result }` or `{ id, error: { name, message, stack } }`. For streaming, it must\n * send one or more `{ id, chunk }` messages followed by `{ id, result: undefined }`.\n * For heartbeat support, send `{ id, heartbeat: true }` at regular intervals.\n *\n * @example\n * ```ts\n * // my-worker.ts — use handleMessages for zero boilerplate:\n * import { handleMessages } from '@vielzeug/familiar/protocol';\n * handleMessages(async (input: number) => input * 2);\n *\n * // main.ts\n * const pool = createModuleWorker<number, number>(\n * new URL('./my-worker.ts', import.meta.url),\n * { concurrency: 4 },\n * );\n * ```\n */\nexport function createModuleWorker<TInput, TOutput>(\n url: URL | string,\n options?: WorkerOptions,\n): WorkerHandle<TInput, TOutput> {\n const { concurrency, heartbeatWindow, maxQueue, onFull, onSlotError, timeout } = resolveOptions(options);\n\n if (heartbeatWindow !== undefined) {\n warn(\n '`heartbeatWindow` has no effect on module workers — the worker script must implement the heartbeat protocol manually.',\n );\n }\n\n const href = typeof url === 'string' ? url : url.href;\n\n const slots = Array.from(\n { length: concurrency },\n () => new Slot<TInput, TOutput>({ kind: 'module', url: href }, onSlotError),\n );\n\n return createPool(slots, {\n concurrency,\n defaultTimeout: timeout,\n maxQueue,\n onFull,\n });\n}\n"],"mappings":";;;;;AAuDA,SAAgB,EAAsB,GAAsD;CAC1F,IAAI,EAAG,SAAS,CAAC,CAAC,SAAS,eAAe,GACxC,MAAM,IAAI,EAA4B,oDAAoD;CAG5F,OAAO;AACT;AAKA,IAAM,IAAkB;AAExB,SAAS,EAAmB,GAA6C;CACvE,IAAI,MAAU,KAAA,GAAW,OAAO;CAEhC,IAAI,MAAU,QACZ,OAAO,KAAK,IAAI,GAAG,WAAW,WAAW,uBAAuB,CAAC;CAGnE,IAAI,CAAC,OAAO,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AAK,UAAU,MACf,EAAQ,OAAO,CAAM;CACvB;CAEA,QAAgB,GAAuB;EAErC,AADA,KAAK,WAAW,GAChB,KAAK,YAAY,CAAM;CACzB;CAEA,aAA2B;EACpB,AAGL,KAAK,YADL,KAAK,OAAO,UAAU,GACR;CAChB;AACF;AAoBA,SAAgB,EACd,GACA,GAC+B;CAC/B,IAAM,EAAE,gBAAa,oBAAiB,aAAU,WAAQ,gBAAa,eAAY,EAAe,CAAO,GACjG,IAAoB,KAAmB,OAAyC,KAAA,IAAlC,KAAK,MAAM,IAAkB,CAAC;CAOlF,OAAO,EALO,MAAM,KAClB,EAAE,QAAQ,EAAY,SAChB,IAAI,EAAsB;EAAE;EAAI;EAAmB,MAAM;CAAS,GAAG,CAAW,CAGtE,GAAO;EACvB;EACA,gBAAgB;EAChB;EACA;CACF,CAAC;AACH;AA+BA,SAAgB,EACd,GACA,GAC+B;CAC/B,IAAM,EAAE,gBAAa,oBAAiB,aAAU,WAAQ,gBAAa,eAAY,EAAe,CAAO;CAEvG,AAAI,MAAoB,KAAA,KACtB,EACE,uHACF;CAGF,IAAM,IAAO,OAAO,KAAQ,WAAW,IAAM,EAAI;CAOjD,OAAO,EALO,MAAM,KAClB,EAAE,QAAQ,EAAY,SAChB,IAAI,EAAsB;EAAE,MAAM;EAAU,KAAK;CAAK,GAAG,CAAW,CAG1D,GAAO;EACvB;EACA,gBAAgB;EAChB;EACA;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"worker.js","names":[],"sources":["../src/worker.ts"],"sourcesContent":["// Re-export all public types and classes so consumers only need one import.\nexport type {\n BatchOptions,\n GroupOptions,\n RunOptions,\n TaskFn,\n TaskGroup,\n WorkerHandle,\n WorkerOptions,\n WorkerStatus,\n} from './types';\nexport {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';\n\nimport type { SlotStrategy, TaskFn, WorkerHandle, WorkerOptions } from './types';\n\nimport { warn } from './_dev';\nimport { createPool } from './_pool';\nimport { unrefTimer } from './_timers';\nimport {\n FamiliarInvalidOptionsError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';\n\n// ─── task() — optional validation helper ─────────────────────────────────────\n\n/**\n * Optional helper that validates a function is safe to serialize for use in `createWorker`.\n *\n * `createWorker` accepts any `TaskFn` directly — this helper exists only to catch the common\n * mistake of passing a bound or native function whose body cannot be serialized.\n *\n * IMPORTANT: The function is serialized via `.toString()` and runs in an isolated Worker scope.\n * It **cannot** close over variables from the surrounding module — any outer reference resolves\n * to `undefined` inside the worker.\n *\n * @throws FamiliarInvalidOptionsError if the function is bound or native.\n *\n * @example\n * // Without task() — works fine for plain arrow functions:\n * const worker = createWorker((n: number) => n * 2);\n *\n * // With task() — catches the mistake of passing Math.sqrt directly:\n * const worker = createWorker(task((n: number) => Math.sqrt(n)));\n */\nexport function task<TInput, TOutput>(fn: TaskFn<TInput, TOutput>): TaskFn<TInput, TOutput> {\n if (fn.toString().includes('[native code]')) {\n throw new FamiliarInvalidOptionsError('Task function cannot be a bound or native function');\n }\n\n return fn;\n}\n\n// ─── Options resolution ───────────────────────────────────────────────────────\n\n/** Upper bound on `concurrency`: generous headroom over realistic hardware/IO limits while still catching obvious misconfiguration (e.g. a typo like `50000`). */\nconst MAX_CONCURRENCY = 512;\n\nfunction resolveConcurrency(value: WorkerOptions['concurrency']): number {\n if (value === undefined) return 1;\n\n if (value === 'auto') {\n return Math.max(1, globalThis.navigator?.hardwareConcurrency ?? 1);\n }\n\n if (!Number.isInteger(value) || value < 1 || value > MAX_CONCURRENCY) {\n throw new FamiliarInvalidOptionsError(`\\`concurrency\\` must be a positive integer ≤ ${MAX_CONCURRENCY} or \"auto\"`);\n }\n\n return value;\n}\n\nfunction resolveOptions(options: WorkerOptions = {}): {\n concurrency: number;\n heartbeatWindow: number | undefined;\n maxQueue: number | undefined;\n onFull: 'reject' | 'wait';\n onSlotError: WorkerOptions['onSlotError'];\n timeout: number | undefined;\n} {\n const concurrency = resolveConcurrency(options.concurrency);\n const { heartbeatWindow, maxQueue, onFull = 'reject', onSlotError, timeout } = options;\n\n if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) {\n throw new FamiliarInvalidOptionsError('`timeout` must be a finite number greater than 0');\n }\n\n if (maxQueue !== undefined && (!Number.isInteger(maxQueue) || maxQueue < 1)) {\n throw new FamiliarInvalidOptionsError('`maxQueue` must be a positive integer');\n }\n\n if (heartbeatWindow !== undefined && (!Number.isFinite(heartbeatWindow) || heartbeatWindow <= 0)) {\n throw new FamiliarInvalidOptionsError('`heartbeatWindow` must be a finite number greater than 0');\n }\n\n return { concurrency, heartbeatWindow, maxQueue, onFull, onSlotError, timeout };\n}\n\n// ─── Worker script builder ────────────────────────────────────────────────────\n\n/**\n * @security `fn.toString()` is injected verbatim into the blob script. Any code embedded in the\n * serialized function executes only inside the isolated Worker scope — no shared memory, no access\n * to the host page's globals. Risk is therefore low, but callers should only pass plain functions\n * that do not close over module scope.\n */\nfunction buildWorkerScript(fn: TaskFn<unknown, unknown>, heartbeatInterval: number | undefined): string {\n return `\nconst __fn = (${fn.toString()});\n\nself.onmessage = async function (event) {\n const { id, input, stream } = event.data;\n\n // Automatically send heartbeats at half the heartbeatWindow interval.\n let heartbeatTimer = null;\n ${heartbeatInterval != null ? `heartbeatTimer = setInterval(() => self.postMessage({ id, heartbeat: true }), ${heartbeatInterval});` : ''}\n\n try {\n if (stream) {\n const iterable = await __fn(input);\n for await (const chunk of iterable) {\n self.postMessage({ id, chunk });\n }\n self.postMessage({ id, result: undefined });\n } else {\n const result = await __fn(input);\n self.postMessage({ id, result });\n }\n } catch (error) {\n self.postMessage({ id, error });\n } finally {\n if (heartbeatTimer) clearInterval(heartbeatTimer);\n }\n}`.trim();\n}\n\n// ─── SlotConfig discriminated union ──────────────────────────────────────────\n\ntype SlotConfig<TInput, TOutput> =\n | { fn: TaskFn<TInput, TOutput>; heartbeatInterval: number | undefined; kind: 'inline' }\n | { kind: 'module'; url: string };\n\n// ─── PendingTask ─────────────────────────────────────────────────────────────\n\ntype SlotMessage<TOutput> =\n | { error: unknown; id: number }\n | { chunk: TOutput; id: number }\n | { heartbeat: true; id: number }\n | { id: number; result: TOutput };\n\ntype PendingTask<TOutput> = {\n /** Emits intermediate stream chunks. Undefined for non-streaming tasks. */\n emit?: (chunk: TOutput) => void;\n /** Called with an error when the streaming dispatch is cancelled mid-flight, so the finish closure drains its waiters. */\n finishStream?: (err: unknown) => void;\n /**\n * Single-shot timer that fires if no heartbeat is received within watchdogMs.\n * Reset (cleared + recreated) on every incoming heartbeat message.\n * Uses setTimeout because the watchdog is conceptually one-shot with manual reset,\n * not a recurring interval.\n */\n heartbeatWatchdog?: ReturnType<typeof setTimeout>;\n id: number;\n reject: (reason: unknown) => void;\n resolve: (value: TOutput) => void;\n timer?: ReturnType<typeof setTimeout>;\n /** Watchdog window in ms (= heartbeatWindow). Stored on PendingTask to reset the timer on each heartbeat. */\n watchdogMs?: number;\n};\n\n// ─── Slot — implements SlotStrategy ──────────────────────────────────────────\n\nclass Slot<TInput, TOutput> implements SlotStrategy<TInput, TOutput> {\n private readonly config: SlotConfig<TInput, TOutput>;\n private readonly onSlotError: WorkerOptions['onSlotError'];\n private disposed = false;\n private pending: PendingTask<TOutput> | null = null;\n private taskId = 0;\n private worker: Worker | null = null;\n\n constructor(config: SlotConfig<TInput, TOutput>, onSlotError?: WorkerOptions['onSlotError']) {\n this.config = config;\n this.onSlotError = onSlotError;\n }\n\n prime(): Promise<void> {\n if (this.disposed) return Promise.resolve();\n\n try {\n this.ensureWorker();\n } catch {\n // Best-effort — errors surface on the first run() call.\n }\n\n return Promise.resolve();\n }\n\n run(input: TInput, transferables: Transferable[], timeout: number | undefined): Promise<TOutput> {\n return this.dispatch(input, transferables, timeout, false) as Promise<TOutput>;\n }\n\n runStream(input: TInput, transferables: Transferable[], timeout: number | undefined): AsyncIterable<TOutput> {\n const chunks: TOutput[] = [];\n let done = false;\n let error: unknown;\n const waiters: Array<() => void> = [];\n\n const emit = (chunk: TOutput) => {\n chunks.push(chunk);\n waiters.shift()?.();\n };\n\n const finish = (err?: unknown) => {\n done = true;\n error = err;\n\n for (const w of waiters.splice(0)) w();\n };\n\n // Dispatch the task in stream mode. The promise resolves when the worker signals done.\n // finishStream is stored on the PendingTask so cancel() can drain the waiters if the\n // consumer exits early (break/throw from for-await), preventing a permanently dangling Promise.\n // this.pending is set synchronously inside dispatch(), so this assignment is safe.\n this.dispatch(input, transferables, timeout, true, emit).then(() => finish(), finish);\n\n if (this.pending) this.pending.finishStream = finish;\n\n return {\n [Symbol.asyncIterator]() {\n let cursor = 0;\n\n return {\n async next(): Promise<IteratorResult<TOutput>> {\n while (cursor >= chunks.length && !done) {\n await new Promise<void>((resolve) => waiters.push(resolve));\n }\n\n if (cursor < chunks.length) {\n const value = chunks[cursor]!;\n\n // Null-out the consumed slot so GC can collect the value\n // without waiting for the entire stream to close.\n (chunks as (TOutput | null)[])[cursor] = null;\n cursor++;\n\n return { done: false, value };\n }\n\n if (error !== undefined) throw error;\n\n return { done: true, value: undefined as unknown as TOutput };\n },\n };\n },\n };\n }\n\n cancel(): void {\n const pending = this.pending;\n\n if (!pending) return;\n\n clearTimeout(pending.timer);\n clearTimeout(pending.heartbeatWatchdog);\n this.pending = null;\n // Terminate the worker: the streaming task may still be running and sending chunks.\n // A fresh worker is created on the next run() or runStream() call via ensureWorker().\n this.stopWorker();\n // Drain the stream finish closure so any pending .next() waiters resolve immediately\n // rather than leaking as permanently dangling Promises.\n pending.finishStream?.(new FamiliarTerminatedError('Stream was cancelled'));\n }\n\n terminate(): void {\n this.disposed = true;\n this.stopWorker();\n this.failPending(new FamiliarTerminatedError());\n }\n\n private dispatch(\n input: TInput,\n transferables: Transferable[],\n timeout: number | undefined,\n stream: boolean,\n emit?: (chunk: TOutput) => void,\n ): Promise<TOutput | void> {\n if (this.disposed) {\n return Promise.reject(new FamiliarTerminatedError());\n }\n\n let worker: Worker;\n\n try {\n worker = this.ensureWorker();\n } catch (error) {\n return Promise.reject(error);\n }\n\n // watchdogMs = heartbeatInterval * 2 (Nyquist margin: worker beats at interval, host allows 2× before firing).\n const watchdogMs =\n this.config.kind === 'inline' && this.config.heartbeatInterval != null\n ? this.config.heartbeatInterval * 2\n : undefined;\n\n return new Promise<TOutput | void>((resolve, reject) => {\n const id = this.taskId++;\n const pending: PendingTask<TOutput> = {\n emit,\n id,\n reject,\n resolve: resolve as (v: TOutput) => void,\n watchdogMs,\n };\n\n if (timeout !== undefined) {\n pending.timer = setTimeout(() => {\n this.restart(new FamiliarTimeoutError(timeout));\n }, timeout);\n unrefTimer(pending.timer);\n }\n\n if (watchdogMs !== undefined) {\n pending.heartbeatWatchdog = setTimeout(() => {\n this.restart(new FamiliarTimeoutError(watchdogMs));\n }, watchdogMs);\n unrefTimer(pending.heartbeatWatchdog);\n }\n\n this.pending = pending;\n\n try {\n worker.postMessage({ id, input, stream }, transferables);\n } catch (err) {\n this.failPending(new FamiliarRuntimeError(err instanceof Error ? err.message : String(err), { cause: err }));\n }\n });\n }\n\n private ensureWorker(): Worker {\n if (this.worker) return this.worker;\n\n if (typeof globalThis.Worker !== 'function') {\n throw new FamiliarRuntimeError('Worker API is unavailable in this runtime');\n }\n\n let worker: Worker;\n\n if (this.config.kind === 'module') {\n try {\n worker = new Worker(this.config.url, { type: 'module' });\n } catch (error) {\n throw new FamiliarRuntimeError('Failed to create Worker', { cause: error });\n }\n } else {\n try {\n const blob = new Blob(\n [buildWorkerScript(this.config.fn as TaskFn<unknown, unknown>, this.config.heartbeatInterval)],\n { type: 'application/javascript' },\n );\n const url = URL.createObjectURL(blob);\n\n try {\n worker = new Worker(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n } catch (error) {\n throw new FamiliarRuntimeError('Failed to create Worker', { cause: error });\n }\n }\n\n worker.onmessage = (event: MessageEvent<SlotMessage<TOutput>>) => {\n const pending = this.pending;\n\n if (!pending || event.data.id !== pending.id) return;\n\n // Handle heartbeat message — reset the watchdog timer.\n if ('heartbeat' in event.data) {\n if (pending.watchdogMs !== undefined) {\n clearTimeout(pending.heartbeatWatchdog);\n pending.heartbeatWatchdog = setTimeout(() => {\n this.restart(new FamiliarTimeoutError(pending.watchdogMs!));\n }, pending.watchdogMs);\n unrefTimer(pending.heartbeatWatchdog);\n }\n\n return;\n }\n\n if ('chunk' in event.data) {\n pending.emit?.(event.data.chunk);\n\n return;\n }\n\n clearTimeout(pending.timer);\n clearTimeout(pending.heartbeatWatchdog);\n this.pending = null;\n\n if ('error' in event.data) {\n const cause = event.data.error instanceof Error ? event.data.error : new Error(String(event.data.error));\n\n pending.reject(new FamiliarTaskError(cause.message, { cause }));\n } else {\n pending.resolve(event.data.result);\n }\n };\n\n worker.onerror = (event: ErrorEvent) => {\n const error = new FamiliarRuntimeError(event.message);\n\n // Stop and fail before calling the external callback so it sees a clean state.\n this.stopWorker();\n this.failPending(error);\n\n this.onSlotError?.(error, () => void this.prime());\n };\n\n this.worker = worker;\n\n return worker;\n }\n\n private failPending(reason: unknown): void {\n const pending = this.pending;\n\n if (!pending) return;\n\n clearTimeout(pending.timer);\n clearTimeout(pending.heartbeatWatchdog);\n this.pending = null;\n pending.reject(reason);\n }\n\n private restart(reason: unknown): void {\n this.stopWorker();\n this.failPending(reason);\n }\n\n private stopWorker(): void {\n if (!this.worker) return;\n\n this.worker.terminate();\n this.worker = null;\n }\n}\n\n// ─── createWorker ─────────────────────────────────────────────────────────────\n\n/**\n * Creates a pool of Web Workers that run `fn` in parallel.\n *\n * The task function is serialized via `.toString()` and runs in a separate global scope.\n * It cannot close over variables from the surrounding module.\n *\n * Use the optional `task()` helper to validate that the function is not bound or native.\n * For workers that need imports, see `createModuleWorker`.\n *\n * @example\n * // Plain arrow function — most common case:\n * const worker = createWorker((n: number) => n * 2);\n *\n * // With task() for validation:\n * const worker = createWorker(task((n: number) => n * 2));\n */\nexport function createWorker<TInput, TOutput>(\n fn: TaskFn<TInput, TOutput>,\n options?: WorkerOptions,\n): WorkerHandle<TInput, TOutput> {\n const { concurrency, heartbeatWindow, maxQueue, onFull, onSlotError, timeout } = resolveOptions(options);\n const heartbeatInterval = heartbeatWindow != null ? Math.floor(heartbeatWindow / 2) : undefined;\n\n const slots = Array.from(\n { length: concurrency },\n () => new Slot<TInput, TOutput>({ fn, heartbeatInterval, kind: 'inline' }, onSlotError),\n );\n\n return createPool(slots, {\n concurrency,\n defaultTimeout: timeout,\n maxQueue,\n onFull,\n });\n}\n\n// ─── createModuleWorker ───────────────────────────────────────────────────────\n\n/**\n * Creates a pool of module-type Web Workers loaded from a real URL.\n *\n * Unlike `createWorker`, the worker file is a regular module — it can import utilities,\n * use top-level await, and reference module scope.\n *\n * Use `handleMessages` from `@vielzeug/familiar/protocol` in the worker file to implement\n * the message protocol without boilerplate.\n *\n * **Protocol**: The worker module must handle the `{ id, input }` message format and reply\n * with `{ id, result }` or `{ id, error: { name, message, stack } }`. For streaming, it must\n * send one or more `{ id, chunk }` messages followed by `{ id, result: undefined }`.\n * For heartbeat support, send `{ id, heartbeat: true }` at regular intervals.\n *\n * @example\n * ```ts\n * // my-worker.ts — use handleMessages for zero boilerplate:\n * import { handleMessages } from '@vielzeug/familiar/protocol';\n * handleMessages(async (input: number) => input * 2);\n *\n * // main.ts\n * const pool = createModuleWorker<number, number>(\n * new URL('./my-worker.ts', import.meta.url),\n * { concurrency: 4 },\n * );\n * ```\n */\nexport function createModuleWorker<TInput, TOutput>(\n url: URL | string,\n options?: WorkerOptions,\n): WorkerHandle<TInput, TOutput> {\n const { concurrency, heartbeatWindow, maxQueue, onFull, onSlotError, timeout } = resolveOptions(options);\n\n if (heartbeatWindow !== undefined) {\n warn(\n '`heartbeatWindow` has no effect on module workers — the worker script must implement the heartbeat protocol manually.',\n );\n }\n\n const href = typeof url === 'string' ? url : url.href;\n\n const slots = Array.from(\n { length: concurrency },\n () => new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CAC5E;CAEA,OAAO,EAAW,GAAO;EACvB;EACA,gBAAgB;EAChB;EACA;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vielzeug/familiar",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Typed Web Worker pool with task queuing, streaming, AbortSignal cancellation, and heartbeat",
5
5
  "type": "module",
6
6
  "files": [
@@ -11,19 +11,16 @@
11
11
  "types": "dist/index.d.ts",
12
12
  "exports": {
13
13
  ".": {
14
- "source": "./src/index.ts",
15
14
  "types": "./dist/index.d.ts",
16
15
  "import": "./dist/index.js",
17
16
  "require": "./dist/index.cjs"
18
17
  },
19
18
  "./protocol": {
20
- "source": "./src/protocol.ts",
21
19
  "types": "./dist/protocol.d.ts",
22
20
  "import": "./dist/protocol.js",
23
21
  "require": "./dist/protocol.cjs"
24
22
  },
25
23
  "./testing": {
26
- "source": "./src/testing/index.ts",
27
24
  "types": "./dist/testing/index.d.ts",
28
25
  "import": "./dist/testing.js",
29
26
  "require": "./dist/testing.cjs"
@@ -47,12 +44,22 @@
47
44
  "node": ">=22"
48
45
  },
49
46
  "dependencies": {
50
- "@vielzeug/arsenal": "1.1.2"
47
+ "@vielzeug/arsenal": "2.0.1"
51
48
  },
52
49
  "devDependencies": {
53
- "@types/node": "^26.1.0",
50
+ "@types/node": "^26.1.2",
54
51
  "typescript": "^6.0.3",
55
- "vite": "^8.1.3",
52
+ "vite": "^8.2.0",
56
53
  "vitest": "^4.1.10"
54
+ },
55
+ "typesVersions": {
56
+ "*": {
57
+ "protocol": [
58
+ "dist/protocol.d.ts"
59
+ ],
60
+ "testing": [
61
+ "dist/testing/index.d.ts"
62
+ ]
63
+ }
57
64
  }
58
65
  }