@vielzeug/familiar 1.0.2

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.
Files changed (66) hide show
  1. package/README.md +78 -0
  2. package/dist/_dev.cjs +2 -0
  3. package/dist/_dev.cjs.map +1 -0
  4. package/dist/_dev.d.ts +2 -0
  5. package/dist/_dev.d.ts.map +1 -0
  6. package/dist/_dev.js +9 -0
  7. package/dist/_dev.js.map +1 -0
  8. package/dist/_pool.cjs +2 -0
  9. package/dist/_pool.cjs.map +1 -0
  10. package/dist/_pool.d.ts +19 -0
  11. package/dist/_pool.d.ts.map +1 -0
  12. package/dist/_pool.js +262 -0
  13. package/dist/_pool.js.map +1 -0
  14. package/dist/_queue.cjs +2 -0
  15. package/dist/_queue.cjs.map +1 -0
  16. package/dist/_queue.d.ts +55 -0
  17. package/dist/_queue.d.ts.map +1 -0
  18. package/dist/_queue.js +52 -0
  19. package/dist/_queue.js.map +1 -0
  20. package/dist/_timers.cjs +2 -0
  21. package/dist/_timers.cjs.map +1 -0
  22. package/dist/_timers.d.ts +9 -0
  23. package/dist/_timers.d.ts.map +1 -0
  24. package/dist/_timers.js +8 -0
  25. package/dist/_timers.js.map +1 -0
  26. package/dist/errors.cjs +2 -0
  27. package/dist/errors.cjs.map +1 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.js +27 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/familiar.cjs +28 -0
  33. package/dist/familiar.cjs.map +1 -0
  34. package/dist/familiar.iife.js +28 -0
  35. package/dist/familiar.iife.js.map +1 -0
  36. package/dist/familiar.js +28 -0
  37. package/dist/familiar.js.map +1 -0
  38. package/dist/index.cjs +1 -0
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +3 -0
  42. package/dist/protocol.cjs +2 -0
  43. package/dist/protocol.cjs.map +1 -0
  44. package/dist/protocol.d.ts +45 -0
  45. package/dist/protocol.d.ts.map +1 -0
  46. package/dist/protocol.js +53 -0
  47. package/dist/protocol.js.map +1 -0
  48. package/dist/testing/index.d.ts +2 -0
  49. package/dist/testing/index.d.ts.map +1 -0
  50. package/dist/testing/testing.cjs +2 -0
  51. package/dist/testing/testing.cjs.map +1 -0
  52. package/dist/testing/testing.d.ts +27 -0
  53. package/dist/testing/testing.d.ts.map +1 -0
  54. package/dist/testing/testing.js +58 -0
  55. package/dist/testing/testing.js.map +1 -0
  56. package/dist/testing.cjs +1 -0
  57. package/dist/testing.js +3 -0
  58. package/dist/types.d.ts +147 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/worker.cjs +28 -0
  61. package/dist/worker.cjs.map +1 -0
  62. package/dist/worker.d.ts +69 -0
  63. package/dist/worker.d.ts.map +1 -0
  64. package/dist/worker.js +229 -0
  65. package/dist/worker.js.map +1 -0
  66. package/package.json +55 -0
@@ -0,0 +1,28 @@
1
+ const e=require("./errors.cjs"),t=require("./_dev.cjs"),n=require("./_timers.cjs"),r=require("./_pool.cjs");function i(t){if(t.toString().includes(`[native code]`))throw new e.FamiliarInvalidOptionsError(`Task function cannot be a bound or native function`);return t}var a=512;function o(t){if(t===void 0)return 1;if(t===`auto`)return Math.max(1,globalThis.navigator?.hardwareConcurrency??1);if(!Number.isInteger(t)||t<1||t>a)throw new e.FamiliarInvalidOptionsError(`\`concurrency\` must be a positive integer ≤ ${a} or "auto"`);return t}function s(t={}){let n=o(t.concurrency),{heartbeatWindow:r,maxQueue:i,onFull:a=`reject`,onSlotError:s,timeout:c}=t;if(c!==void 0&&(!Number.isFinite(c)||c<=0))throw new e.FamiliarInvalidOptionsError("`timeout` must be a finite number greater than 0");if(i!==void 0&&(!Number.isInteger(i)||i<1))throw new e.FamiliarInvalidOptionsError("`maxQueue` must be a positive integer");if(r!==void 0&&(!Number.isFinite(r)||r<=0))throw new e.FamiliarInvalidOptionsError("`heartbeatWindow` must be a finite number greater than 0");return{concurrency:n,heartbeatWindow:r,maxQueue:i,onFull:a,onSlotError:s,timeout:c}}function c(e,t){return`
2
+ const __fn = (${e.toString()});
3
+
4
+ self.onmessage = async function (event) {
5
+ const { id, input, stream } = event.data;
6
+
7
+ // Automatically send heartbeats at half the heartbeatWindow interval.
8
+ let heartbeatTimer = null;
9
+ ${t==null?``:`heartbeatTimer = setInterval(() => self.postMessage({ id, heartbeat: true }), ${t});`}
10
+
11
+ try {
12
+ if (stream) {
13
+ const iterable = await __fn(input);
14
+ for await (const chunk of iterable) {
15
+ self.postMessage({ id, chunk });
16
+ }
17
+ self.postMessage({ id, result: undefined });
18
+ } else {
19
+ const result = await __fn(input);
20
+ self.postMessage({ id, result });
21
+ }
22
+ } catch (error) {
23
+ self.postMessage({ id, error });
24
+ } finally {
25
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
26
+ }
27
+ }`.trim()}var l=class{config;onSlotError;disposed=!1;pending=null;taskId=0;worker=null;constructor(e,t){this.config=e,this.onSlotError=t}prime(){if(this.disposed)return Promise.resolve();try{this.ensureWorker()}catch{}return Promise.resolve()}run(e,t,n){return this.dispatch(e,t,n,!1)}runStream(e,t,n){let r=[],i=!1,a,o=[],s=e=>{r.push(e),o.shift()?.()},c=e=>{i=!0,a=e;for(let e of o.splice(0))e()};return this.dispatch(e,t,n,!0,s).then(()=>c(),c),this.pending&&(this.pending.finishStream=c),{[Symbol.asyncIterator](){let e=0;return{async next(){for(;e>=r.length&&!i;)await new Promise(e=>o.push(e));if(e<r.length){let t=r[e];return r[e]=null,e++,{done:!1,value:t}}if(a!==void 0)throw a;return{done:!0,value:void 0}}}}}}cancel(){let t=this.pending;t&&(clearTimeout(t.timer),clearTimeout(t.heartbeatWatchdog),this.pending=null,this.stopWorker(),t.finishStream?.(new e.FamiliarTerminatedError(`Stream was cancelled`)))}terminate(){this.disposed=!0,this.stopWorker(),this.failPending(new e.FamiliarTerminatedError)}dispatch(t,r,i,a,o){if(this.disposed)return Promise.reject(new e.FamiliarTerminatedError);let s;try{s=this.ensureWorker()}catch(e){return Promise.reject(e)}let c=this.config.kind===`inline`&&this.config.heartbeatInterval!=null?this.config.heartbeatInterval*2:void 0;return new Promise((l,u)=>{let d=this.taskId++,f={emit:o,id:d,reject:u,resolve:l,watchdogMs:c};i!==void 0&&(f.timer=setTimeout(()=>{this.restart(new e.FamiliarTimeoutError(i))},i),n.unrefTimer(f.timer)),c!==void 0&&(f.heartbeatWatchdog=setTimeout(()=>{this.restart(new e.FamiliarTimeoutError(c))},c),n.unrefTimer(f.heartbeatWatchdog)),this.pending=f;try{s.postMessage({id:d,input:t,stream:a},r)}catch(t){this.failPending(new e.FamiliarRuntimeError(t instanceof Error?t.message:String(t),{cause:t}))}})}ensureWorker(){if(this.worker)return this.worker;if(typeof globalThis.Worker!=`function`)throw new e.FamiliarRuntimeError(`Worker API is unavailable in this runtime`);let t;if(this.config.kind===`module`)try{t=new Worker(this.config.url,{type:`module`})}catch(t){throw new e.FamiliarRuntimeError(`Failed to create Worker`,{cause:t})}else try{let e=new Blob([c(this.config.fn,this.config.heartbeatInterval)],{type:`application/javascript`}),n=URL.createObjectURL(e);try{t=new Worker(n)}finally{URL.revokeObjectURL(n)}}catch(t){throw new e.FamiliarRuntimeError(`Failed to create Worker`,{cause:t})}return t.onmessage=t=>{let r=this.pending;if(!(!r||t.data.id!==r.id)){if(`heartbeat`in t.data){r.watchdogMs!==void 0&&(clearTimeout(r.heartbeatWatchdog),r.heartbeatWatchdog=setTimeout(()=>{this.restart(new e.FamiliarTimeoutError(r.watchdogMs))},r.watchdogMs),n.unrefTimer(r.heartbeatWatchdog));return}if(`chunk`in t.data){r.emit?.(t.data.chunk);return}if(clearTimeout(r.timer),clearTimeout(r.heartbeatWatchdog),this.pending=null,`error`in t.data){let n=t.data.error instanceof Error?t.data.error:Error(String(t.data.error));r.reject(new e.FamiliarTaskError(n.message,{cause:n}))}else r.resolve(t.data.result)}},t.onerror=t=>{let n=new e.FamiliarRuntimeError(t.message);this.stopWorker(),this.failPending(n),this.onSlotError?.(n,()=>void this.prime())},this.worker=t,t}failPending(e){let t=this.pending;t&&(clearTimeout(t.timer),clearTimeout(t.heartbeatWatchdog),this.pending=null,t.reject(e))}restart(e){this.stopWorker(),this.failPending(e)}stopWorker(){this.worker&&=(this.worker.terminate(),null)}};function u(e,t){let{concurrency:n,heartbeatWindow:i,maxQueue:a,onFull:o,onSlotError:c,timeout:u}=s(t),d=i==null?void 0:Math.floor(i/2);return r.createPool(Array.from({length:n},()=>new l({fn:e,heartbeatInterval:d,kind:`inline`},c)),{concurrency:n,defaultTimeout:u,maxQueue:a,onFull:o})}function d(e,n){let{concurrency:i,heartbeatWindow:a,maxQueue:o,onFull:c,onSlotError:u,timeout:d}=s(n);a!==void 0&&t.warn("`heartbeatWindow` has no effect on module workers — the worker script must implement the heartbeat protocol manually.");let f=typeof e==`string`?e:e.href;return r.createPool(Array.from({length:i},()=>new l({kind:`module`,url:f},u)),{concurrency:i,defaultTimeout:d,maxQueue:o,onFull:c})}exports.FamiliarError=e.FamiliarError,exports.FamiliarInvalidOptionsError=e.FamiliarInvalidOptionsError,exports.FamiliarQueueFullError=e.FamiliarQueueFullError,exports.FamiliarRuntimeError=e.FamiliarRuntimeError,exports.FamiliarTaskError=e.FamiliarTaskError,exports.FamiliarTerminatedError=e.FamiliarTerminatedError,exports.FamiliarTimeoutError=e.FamiliarTimeoutError,exports.createModuleWorker=d,exports.createWorker=u,exports.task=i;
28
+ //# sourceMappingURL=worker.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.cjs","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":"4GAuDA,SAAgB,EAAsB,EAAsD,CAC1F,GAAI,EAAG,SAAS,CAAC,CAAC,SAAS,eAAe,EACxC,MAAM,IAAI,EAAA,4BAA4B,oDAAoD,EAG5F,OAAO,CACT,CAKA,IAAM,EAAkB,IAExB,SAAS,EAAmB,EAA6C,CACvE,GAAI,IAAU,IAAA,GAAW,MAAO,GAEhC,GAAI,IAAU,OACZ,OAAO,KAAK,IAAI,EAAG,WAAW,WAAW,qBAAuB,CAAC,EAGnE,GAAI,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,GAAK,EAAQ,EACnD,MAAM,IAAI,EAAA,4BAA4B,gDAAgD,EAAgB,WAAW,EAGnH,OAAO,CACT,CAEA,SAAS,EAAe,EAAyB,CAAC,EAOhD,CACA,IAAM,EAAc,EAAmB,EAAQ,WAAW,EACpD,CAAE,kBAAiB,WAAU,SAAS,SAAU,cAAa,WAAY,EAE/E,GAAI,IAAY,IAAA,KAAc,CAAC,OAAO,SAAS,CAAO,GAAK,GAAW,GACpE,MAAM,IAAI,EAAA,4BAA4B,kDAAkD,EAG1F,GAAI,IAAa,IAAA,KAAc,CAAC,OAAO,UAAU,CAAQ,GAAK,EAAW,GACvE,MAAM,IAAI,EAAA,4BAA4B,uCAAuC,EAG/E,GAAI,IAAoB,IAAA,KAAc,CAAC,OAAO,SAAS,CAAe,GAAK,GAAmB,GAC5F,MAAM,IAAI,EAAA,4BAA4B,0DAA0D,EAGlG,MAAO,CAAE,cAAa,kBAAiB,WAAU,SAAQ,cAAa,SAAQ,CAChF,CAUA,SAAS,EAAkB,EAA8B,EAA+C,CACtG,MAAO;gBACO,EAAG,SAAS,EAAE;;;;;;;IAO1B,GAAqB,KAAgH,GAAzG,iFAAiF,E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F,IAAM,EAAO,OAAO,GAAQ,SAAW,EAAM,EAAI,KAOjD,OAAO,EAAA,WALO,MAAM,KAClB,CAAE,OAAQ,CAAY,MAChB,IAAI,EAAsB,CAAE,KAAM,SAAU,IAAK,CAAK,EAAG,CAAW,CAG1D,EAAO,CACvB,cACA,eAAgB,EAChB,WACA,QACF,CAAC,CACH"}
@@ -0,0 +1,69 @@
1
+ export type { BatchOptions, GroupOptions, RunOptions, TaskFn, TaskGroup, WorkerHandle, WorkerOptions, WorkerStatus, } from './types';
2
+ export { FamiliarError, FamiliarInvalidOptionsError, FamiliarQueueFullError, FamiliarRuntimeError, FamiliarTaskError, FamiliarTerminatedError, FamiliarTimeoutError, } from './errors';
3
+ import type { TaskFn, WorkerHandle, WorkerOptions } from './types';
4
+ /**
5
+ * Optional helper that validates a function is safe to serialize for use in `createWorker`.
6
+ *
7
+ * `createWorker` accepts any `TaskFn` directly — this helper exists only to catch the common
8
+ * mistake of passing a bound or native function whose body cannot be serialized.
9
+ *
10
+ * IMPORTANT: The function is serialized via `.toString()` and runs in an isolated Worker scope.
11
+ * It **cannot** close over variables from the surrounding module — any outer reference resolves
12
+ * to `undefined` inside the worker.
13
+ *
14
+ * @throws FamiliarInvalidOptionsError if the function is bound or native.
15
+ *
16
+ * @example
17
+ * // Without task() — works fine for plain arrow functions:
18
+ * const worker = createWorker((n: number) => n * 2);
19
+ *
20
+ * // With task() — catches the mistake of passing Math.sqrt directly:
21
+ * const worker = createWorker(task((n: number) => Math.sqrt(n)));
22
+ */
23
+ export declare function task<TInput, TOutput>(fn: TaskFn<TInput, TOutput>): TaskFn<TInput, TOutput>;
24
+ /**
25
+ * Creates a pool of Web Workers that run `fn` in parallel.
26
+ *
27
+ * The task function is serialized via `.toString()` and runs in a separate global scope.
28
+ * It cannot close over variables from the surrounding module.
29
+ *
30
+ * Use the optional `task()` helper to validate that the function is not bound or native.
31
+ * For workers that need imports, see `createModuleWorker`.
32
+ *
33
+ * @example
34
+ * // Plain arrow function — most common case:
35
+ * const worker = createWorker((n: number) => n * 2);
36
+ *
37
+ * // With task() for validation:
38
+ * const worker = createWorker(task((n: number) => n * 2));
39
+ */
40
+ export declare function createWorker<TInput, TOutput>(fn: TaskFn<TInput, TOutput>, options?: WorkerOptions): WorkerHandle<TInput, TOutput>;
41
+ /**
42
+ * Creates a pool of module-type Web Workers loaded from a real URL.
43
+ *
44
+ * Unlike `createWorker`, the worker file is a regular module — it can import utilities,
45
+ * use top-level await, and reference module scope.
46
+ *
47
+ * Use `handleMessages` from `@vielzeug/familiar/protocol` in the worker file to implement
48
+ * the message protocol without boilerplate.
49
+ *
50
+ * **Protocol**: The worker module must handle the `{ id, input }` message format and reply
51
+ * with `{ id, result }` or `{ id, error: { name, message, stack } }`. For streaming, it must
52
+ * send one or more `{ id, chunk }` messages followed by `{ id, result: undefined }`.
53
+ * For heartbeat support, send `{ id, heartbeat: true }` at regular intervals.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * // my-worker.ts — use handleMessages for zero boilerplate:
58
+ * import { handleMessages } from '@vielzeug/familiar/protocol';
59
+ * handleMessages(async (input: number) => input * 2);
60
+ *
61
+ * // main.ts
62
+ * const pool = createModuleWorker<number, number>(
63
+ * new URL('./my-worker.ts', import.meta.url),
64
+ * { concurrency: 4 },
65
+ * );
66
+ * ```
67
+ */
68
+ export declare function createModuleWorker<TInput, TOutput>(url: URL | string, options?: WorkerOptions): WorkerHandle<TInput, TOutput>;
69
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AACA,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,MAAM,EACN,SAAS,EACT,YAAY,EACZ,aAAa,EACb,YAAY,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,aAAa,EACb,2BAA2B,EAC3B,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAgB,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAejF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAM1F;AA8YD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,OAAO,EAC1C,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC3B,OAAO,CAAC,EAAE,aAAa,GACtB,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAe/B;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,OAAO,EAChD,GAAG,EAAE,GAAG,GAAG,MAAM,EACjB,OAAO,CAAC,EAAE,aAAa,GACtB,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAsB/B"}
package/dist/worker.js ADDED
@@ -0,0 +1,229 @@
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";
5
+ //#region src/worker.ts
6
+ function u(e) {
7
+ if (e.toString().includes("[native code]")) throw new t("Task function cannot be a bound or native function");
8
+ return e;
9
+ }
10
+ var d = 512;
11
+ function f(e) {
12
+ if (e === void 0) return 1;
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"`);
15
+ return e;
16
+ }
17
+ function p(e = {}) {
18
+ let n = f(e.concurrency), { heartbeatWindow: r, maxQueue: i, onFull: a = "reject", onSlotError: o, timeout: s } = e;
19
+ if (s !== void 0 && (!Number.isFinite(s) || s <= 0)) throw new t("`timeout` must be a finite number greater than 0");
20
+ if (i !== void 0 && (!Number.isInteger(i) || i < 1)) throw new t("`maxQueue` must be a positive integer");
21
+ if (r !== void 0 && (!Number.isFinite(r) || r <= 0)) throw new t("`heartbeatWindow` must be a finite number greater than 0");
22
+ return {
23
+ concurrency: n,
24
+ heartbeatWindow: r,
25
+ maxQueue: i,
26
+ onFull: a,
27
+ onSlotError: o,
28
+ timeout: s
29
+ };
30
+ }
31
+ function m(e, t) {
32
+ return `
33
+ const __fn = (${e.toString()});
34
+
35
+ self.onmessage = async function (event) {
36
+ const { id, input, stream } = event.data;
37
+
38
+ // Automatically send heartbeats at half the heartbeatWindow interval.
39
+ let heartbeatTimer = null;
40
+ ${t == null ? "" : `heartbeatTimer = setInterval(() => self.postMessage({ id, heartbeat: true }), ${t});`}
41
+
42
+ try {
43
+ if (stream) {
44
+ const iterable = await __fn(input);
45
+ for await (const chunk of iterable) {
46
+ self.postMessage({ id, chunk });
47
+ }
48
+ self.postMessage({ id, result: undefined });
49
+ } else {
50
+ const result = await __fn(input);
51
+ self.postMessage({ id, result });
52
+ }
53
+ } catch (error) {
54
+ self.postMessage({ id, error });
55
+ } finally {
56
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
57
+ }
58
+ }`.trim();
59
+ }
60
+ var h = class {
61
+ config;
62
+ onSlotError;
63
+ disposed = !1;
64
+ pending = null;
65
+ taskId = 0;
66
+ worker = null;
67
+ constructor(e, t) {
68
+ this.config = e, this.onSlotError = t;
69
+ }
70
+ prime() {
71
+ if (this.disposed) return Promise.resolve();
72
+ try {
73
+ this.ensureWorker();
74
+ } catch {}
75
+ return Promise.resolve();
76
+ }
77
+ run(e, t, n) {
78
+ return this.dispatch(e, t, n, !1);
79
+ }
80
+ runStream(e, t, n) {
81
+ let r = [], i = !1, a, o = [], s = (e) => {
82
+ r.push(e), o.shift()?.();
83
+ }, c = (e) => {
84
+ i = !0, a = e;
85
+ for (let e of o.splice(0)) e();
86
+ };
87
+ return this.dispatch(e, t, n, !0, s).then(() => c(), c), this.pending && (this.pending.finishStream = c), { [Symbol.asyncIterator]() {
88
+ let e = 0;
89
+ return { async next() {
90
+ for (; e >= r.length && !i;) await new Promise((e) => o.push(e));
91
+ if (e < r.length) {
92
+ let t = r[e];
93
+ return r[e] = null, e++, {
94
+ done: !1,
95
+ value: t
96
+ };
97
+ }
98
+ if (a !== void 0) throw a;
99
+ return {
100
+ done: !0,
101
+ value: void 0
102
+ };
103
+ } };
104
+ } };
105
+ }
106
+ cancel() {
107
+ let e = this.pending;
108
+ e && (clearTimeout(e.timer), clearTimeout(e.heartbeatWatchdog), this.pending = null, this.stopWorker(), e.finishStream?.(new a("Stream was cancelled")));
109
+ }
110
+ terminate() {
111
+ this.disposed = !0, this.stopWorker(), this.failPending(new a());
112
+ }
113
+ dispatch(e, t, n, i, s) {
114
+ if (this.disposed) return Promise.reject(new a());
115
+ let l;
116
+ try {
117
+ l = this.ensureWorker();
118
+ } catch (e) {
119
+ return Promise.reject(e);
120
+ }
121
+ let u = this.config.kind === "inline" && this.config.heartbeatInterval != null ? this.config.heartbeatInterval * 2 : void 0;
122
+ return new Promise((a, d) => {
123
+ let f = this.taskId++, p = {
124
+ emit: s,
125
+ id: f,
126
+ reject: d,
127
+ resolve: a,
128
+ watchdogMs: u
129
+ };
130
+ n !== void 0 && (p.timer = setTimeout(() => {
131
+ this.restart(new o(n));
132
+ }, n), c(p.timer)), u !== void 0 && (p.heartbeatWatchdog = setTimeout(() => {
133
+ this.restart(new o(u));
134
+ }, u), c(p.heartbeatWatchdog)), this.pending = p;
135
+ try {
136
+ l.postMessage({
137
+ id: f,
138
+ input: e,
139
+ stream: i
140
+ }, t);
141
+ } catch (e) {
142
+ this.failPending(new r(e instanceof Error ? e.message : String(e), { cause: e }));
143
+ }
144
+ });
145
+ }
146
+ ensureWorker() {
147
+ if (this.worker) return this.worker;
148
+ if (typeof globalThis.Worker != "function") throw new r("Worker API is unavailable in this runtime");
149
+ let e;
150
+ if (this.config.kind === "module") try {
151
+ e = new Worker(this.config.url, { type: "module" });
152
+ } catch (e) {
153
+ throw new r("Failed to create Worker", { cause: e });
154
+ }
155
+ else try {
156
+ let t = new Blob([m(this.config.fn, this.config.heartbeatInterval)], { type: "application/javascript" }), n = URL.createObjectURL(t);
157
+ try {
158
+ e = new Worker(n);
159
+ } finally {
160
+ URL.revokeObjectURL(n);
161
+ }
162
+ } catch (e) {
163
+ throw new r("Failed to create Worker", { cause: e });
164
+ }
165
+ return e.onmessage = (e) => {
166
+ let t = this.pending;
167
+ if (!(!t || e.data.id !== t.id)) {
168
+ if ("heartbeat" in e.data) {
169
+ t.watchdogMs !== void 0 && (clearTimeout(t.heartbeatWatchdog), t.heartbeatWatchdog = setTimeout(() => {
170
+ this.restart(new o(t.watchdogMs));
171
+ }, t.watchdogMs), c(t.heartbeatWatchdog));
172
+ return;
173
+ }
174
+ if ("chunk" in e.data) {
175
+ t.emit?.(e.data.chunk);
176
+ return;
177
+ }
178
+ if (clearTimeout(t.timer), clearTimeout(t.heartbeatWatchdog), this.pending = null, "error" in e.data) {
179
+ let n = e.data.error instanceof Error ? e.data.error : Error(String(e.data.error));
180
+ t.reject(new i(n.message, { cause: n }));
181
+ } else t.resolve(e.data.result);
182
+ }
183
+ }, e.onerror = (e) => {
184
+ let t = new r(e.message);
185
+ this.stopWorker(), this.failPending(t), this.onSlotError?.(t, () => void this.prime());
186
+ }, this.worker = e, e;
187
+ }
188
+ failPending(e) {
189
+ let t = this.pending;
190
+ t && (clearTimeout(t.timer), clearTimeout(t.heartbeatWatchdog), this.pending = null, t.reject(e));
191
+ }
192
+ restart(e) {
193
+ this.stopWorker(), this.failPending(e);
194
+ }
195
+ stopWorker() {
196
+ this.worker &&= (this.worker.terminate(), null);
197
+ }
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({
202
+ fn: e,
203
+ heartbeatInterval: c,
204
+ kind: "inline"
205
+ }, o)), {
206
+ concurrency: n,
207
+ defaultTimeout: s,
208
+ maxQueue: i,
209
+ onFull: a
210
+ });
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({
217
+ kind: "module",
218
+ url: u
219
+ }, o)), {
220
+ concurrency: n,
221
+ defaultTimeout: c,
222
+ maxQueue: i,
223
+ onFull: a
224
+ });
225
+ }
226
+ //#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 };
228
+
229
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +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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B;EAChB;EACA;CACF,CAAC;AACH"}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@vielzeug/familiar",
3
+ "version": "1.0.2",
4
+ "description": "Typed Web Worker pool with task queuing, streaming, AbortSignal cancellation, and heartbeat",
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "main": "./dist/index.cjs",
10
+ "module": "./dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "source": "./src/index.ts",
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.cjs"
18
+ },
19
+ "./protocol": {
20
+ "source": "./src/protocol.ts",
21
+ "types": "./dist/protocol.d.ts",
22
+ "import": "./dist/protocol.js",
23
+ "require": "./dist/protocol.cjs"
24
+ },
25
+ "./testing": {
26
+ "source": "./src/testing/index.ts",
27
+ "types": "./dist/testing/index.d.ts",
28
+ "import": "./dist/testing.js",
29
+ "require": "./dist/testing.cjs"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "vite build && pnpm run build:bundle && pnpm run build:types",
34
+ "build:types": "tsc -p tsconfig.declarations.json",
35
+ "fix": "eslint --fix src",
36
+ "lint": "eslint src",
37
+ "prepublishOnly": "pnpm run build",
38
+ "preview": "vite preview",
39
+ "test": "vitest",
40
+ "build:bundle": "vite build --config vite.bundle.config.ts"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public",
44
+ "registry": "https://registry.npmjs.org/"
45
+ },
46
+ "dependencies": {
47
+ "@vielzeug/arsenal": "workspace:*"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^26.1.0",
51
+ "typescript": "~6.0.3",
52
+ "vite": "^8.1.3",
53
+ "vitest": "^4.1.9"
54
+ }
55
+ }