@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 @@
1
+ {"version":3,"file":"familiar.js","names":[],"sources":["../src/errors.ts","../src/_dev.ts","../src/_queue.ts","../src/_timers.ts","../src/_pool.ts","../src/worker.ts"],"sourcesContent":["/** Base class for all familiar errors. Use `instanceof FamiliarError` to catch any familiar-originated error. */\nexport class FamiliarError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is FamiliarError {\n return err instanceof FamiliarError;\n }\n}\n\n/** Thrown when invalid options are passed to `createWorker` or `createModuleWorker`. */\nexport class FamiliarInvalidOptionsError extends FamiliarError {}\n\n/** Thrown when run() is called and the queue is full (`onFull='reject'`). */\nexport class FamiliarQueueFullError extends FamiliarError {\n /** The configured `maxQueue` value. */\n readonly maxQueue: number;\n\n constructor(maxQueue: number) {\n super(`Queue is full (maxQueue=${maxQueue})`);\n this.maxQueue = maxQueue;\n }\n}\n\n/** Thrown when the task function throws. The original error is available as `.cause`. */\nexport class FamiliarTaskError extends FamiliarError {}\n\n/** Thrown when a task or operation is rejected because the worker was terminated. */\nexport class FamiliarTerminatedError extends FamiliarError {\n constructor(message = 'Worker was terminated') {\n super(message);\n }\n}\n\n/** Thrown when a task exceeds its timeout or `drain()` times out. */\nexport class FamiliarTimeoutError extends FamiliarError {\n /** The configured timeout in milliseconds. */\n readonly timeoutMs: number;\n\n constructor(timeoutMs: number) {\n super(`Task timed out after ${timeoutMs}ms`);\n this.timeoutMs = timeoutMs;\n }\n}\n\n/** Thrown when the Worker API is unavailable or an unhandled error occurs in the worker thread. */\nexport class FamiliarRuntimeError extends FamiliarError {}\n","const isDev = !(globalThis as { __FAMILIAR_PROD__?: boolean }).__FAMILIAR_PROD__;\n\n/** @internal */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/familiar] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n","/**\n * Internal priority-queue for @vielzeug/familiar.\n * Not part of the public API surface.\n *\n * Uses a binary max-heap ordered by priority (higher value = runs first), with\n * insertion-sequence tiebreaking to ensure FIFO ordering within the same priority.\n * Cancelled items are marked lazily and silently skipped by shift().\n *\n * Complexity:\n * enqueue O(log n)\n * shift O(log n) amortised (lazy cancellation may scan multiple cancelled tops)\n * remove O(n) scan + O(1) mark — adequate for typical queue depths\n */\n\nexport type QueueItem<TInput, TOutput> = {\n /** Marked true by remove(); the next shift() discards the item silently. */\n cancelled?: boolean;\n cleanupAbort?: () => void;\n input: TInput;\n /** Scheduling priority. Higher value = runs first. Default: 0. */\n priority: number;\n reject: (reason: unknown) => void;\n resolve: (value: TOutput) => void;\n signal?: AbortSignal;\n timeout?: number;\n transferables: Transferable[];\n};\n\n/**\n * Internal heap node: wraps a QueueItem with an insertion sequence for FIFO tiebreaking.\n * Using a wrapper instead of mutating QueueItem keeps queue items free of internal\n * scheduling metadata (_seq).\n */\ntype HeapEntry<TInput, TOutput> = { readonly _seq: number; readonly item: QueueItem<TInput, TOutput> };\n\nexport class TaskQueue<TInput, TOutput> {\n private readonly heap: HeapEntry<TInput, TOutput>[] = [];\n /** Accurate count of live (non-cancelled) items. */\n private liveCount = 0;\n private seq = 0;\n\n /** Number of live (non-cancelled) items. Always accurate. */\n get size(): number {\n return this.liveCount;\n }\n\n /**\n * Enqueue item. Returns false (without modifying state) when maxQueue is set and\n * liveCount has already reached it; returns true on success.\n */\n enqueue(item: QueueItem<TInput, TOutput>, maxQueue: number | undefined): boolean {\n if (maxQueue !== undefined && this.liveCount >= maxQueue) return false;\n\n this.heap.push({ _seq: this.seq++, item });\n this.siftUp(this.heap.length - 1);\n this.liveCount++;\n\n return true;\n }\n\n /**\n * Dequeue the highest-priority live item. Silently discards cancelled tombstones.\n * Returns undefined only when there are no live items left.\n */\n shift(): QueueItem<TInput, TOutput> | undefined {\n while (this.heap.length > 0) {\n const { item } = this.extractTop();\n\n if (!item.cancelled) {\n this.liveCount--;\n\n return item;\n }\n // Cancelled: liveCount was already decremented in remove(). Just discard and continue.\n }\n\n return undefined;\n }\n\n /**\n * Mark item as cancelled (O(n) scan). The heap slot is reclaimed lazily by the next shift().\n * Returns true when found and marked, false when the item is not in the queue.\n */\n remove(item: QueueItem<TInput, TOutput>): boolean {\n if (item.cancelled) return false;\n\n for (let i = 0; i < this.heap.length; i++) {\n if (this.heap[i]!.item === item) {\n item.cancelled = true;\n this.liveCount--;\n\n return true;\n }\n }\n\n return false;\n }\n\n // ─── Heap internals ────────────────────────────────────────────────────────\n\n private extractTop(): HeapEntry<TInput, TOutput> {\n const top = this.heap[0]!;\n const last = this.heap.pop()!;\n\n if (this.heap.length > 0) {\n this.heap[0] = last;\n this.siftDown(0);\n }\n\n return top;\n }\n\n /** Returns true when entry a should be dispatched before entry b. */\n private higher(a: HeapEntry<TInput, TOutput>, b: HeapEntry<TInput, TOutput>): boolean {\n if (a.item.priority !== b.item.priority) return a.item.priority > b.item.priority;\n\n return a._seq < b._seq; // earlier insertion wins for equal priority (FIFO)\n }\n\n private siftUp(i: number): void {\n while (i > 0) {\n const parent = (i - 1) >> 1;\n\n if (this.higher(this.heap[i]!, this.heap[parent]!)) {\n [this.heap[i], this.heap[parent]] = [this.heap[parent]!, this.heap[i]!];\n i = parent;\n } else {\n break;\n }\n }\n }\n\n private siftDown(i: number): void {\n const n = this.heap.length;\n\n for (;;) {\n let top = i;\n const left = 2 * i + 1;\n const right = 2 * i + 2;\n\n if (left < n && this.higher(this.heap[left]!, this.heap[top]!)) top = left;\n\n if (right < n && this.higher(this.heap[right]!, this.heap[top]!)) top = right;\n\n if (top === i) break;\n\n [this.heap[i], this.heap[top]] = [this.heap[top]!, this.heap[i]!];\n i = top;\n }\n }\n}\n","/**\n * Node compatibility helper: `unref()`s a timer so a pending per-task timeout/watchdog does not\n * keep a Node event loop (e.g. a Worker polyfill) alive. Browsers return a plain number from\n * `setTimeout`/`setInterval`, so this is a no-op there.\n *\n * Not part of the public API surface.\n */\nexport function unrefTimer(timer: ReturnType<typeof setTimeout> | ReturnType<typeof setInterval>): void {\n if (typeof timer === 'object' && timer !== null && 'unref' in timer) {\n (timer as { unref(): void }).unref();\n }\n}\n","/**\n * Shared pool orchestration engine used by both the real worker implementation and the test\n * double. Handles queue management, iterative drain loop, abort handling, lifecycle (drain /\n * dispose), metrics, batch streaming, task groups, and backpressure.\n *\n * Callers provide a SlotStrategy array — each slot encapsulates run/runStream/prime/terminate.\n * The pool does not care whether slots use a Web Worker or run in-process.\n *\n * Not part of the public API surface.\n */\n\nimport { abortError } from '@vielzeug/arsenal';\n\nimport type {\n BatchOptions,\n GroupOptions,\n RunOptions,\n SlotStrategy,\n TaskGroup,\n WorkerHandle,\n WorkerStatus,\n} from './types';\n\nimport { type QueueItem, TaskQueue } from './_queue';\nimport { unrefTimer } from './_timers';\nimport { FamiliarQueueFullError, FamiliarRuntimeError, FamiliarTerminatedError, FamiliarTimeoutError } from './errors';\n\nexport type PoolOptions = {\n concurrency: number;\n defaultTimeout: number | undefined;\n maxQueue: number | undefined;\n onFull: 'reject' | 'wait';\n};\n\nexport function createPool<TInput, TOutput>(\n slots: SlotStrategy<TInput, TOutput>[],\n options: PoolOptions,\n): WorkerHandle<TInput, TOutput> {\n const { concurrency, defaultTimeout, maxQueue, onFull } = options;\n const freeSlots = [...slots];\n const queue = new TaskQueue<TInput, TOutput>();\n const disposeController = new AbortController();\n const idleResolvers: Array<() => void> = [];\n /** Waiters blocked on run() because the queue is full (onFull='wait' mode). */\n const fullWaiters: Array<() => void> = [];\n\n let activeCount = 0;\n let drainPromise: Promise<void> | undefined;\n let completedCount = 0;\n let failedCount = 0;\n let groupActiveCount = 0;\n let terminated = false;\n\n // ─── Idle tracking ────────────────────────────────────────────────────────────\n\n function isIdle(): boolean {\n return activeCount === 0 && queue.size === 0;\n }\n\n function notifyIdle(): void {\n if (!isIdle() || idleResolvers.length === 0) return;\n\n const resolvers = idleResolvers.splice(0);\n\n for (const resolve of resolvers) resolve();\n }\n\n function waitForIdle(timeoutMs?: number): Promise<void> {\n if (isIdle()) return Promise.resolve();\n\n return new Promise<void>((resolve, reject) => {\n idleResolvers.push(resolve);\n\n if (timeoutMs !== undefined) {\n const timer = setTimeout(() => {\n const idx = idleResolvers.indexOf(resolve);\n\n if (idx !== -1) idleResolvers.splice(idx, 1);\n\n reject(new FamiliarTimeoutError(timeoutMs));\n }, timeoutMs);\n\n unrefTimer(timer);\n }\n });\n }\n\n // ─── Full-queue backpressure (onFull='wait') ──────────────────────────────────\n\n function releaseOneFullWaiter(): void {\n const waiter = fullWaiters.shift();\n\n if (waiter) waiter();\n }\n\n // ─── Drain loop (iterative) ───────────────────────────────────────────────────\n\n let draining = false;\n\n function drainLoop(): void {\n if (terminated || draining) return;\n\n draining = true;\n\n while (!terminated && freeSlots.length > 0 && queue.size > 0) {\n const item = nextItem();\n\n if (!item) break;\n\n const slot = freeSlots.pop()!;\n\n item.cleanupAbort?.();\n activeCount += 1;\n releaseOneFullWaiter();\n\n const taskTimeout = item.timeout ?? defaultTimeout;\n\n slot.run(item.input, item.transferables, taskTimeout).then(\n (result) => {\n freeSlots.push(slot);\n activeCount -= 1;\n completedCount += 1;\n item.resolve(result);\n drainLoop();\n\n if (isIdle()) notifyIdle();\n },\n (error: unknown) => {\n freeSlots.push(slot);\n activeCount -= 1;\n\n if (!(error instanceof FamiliarTerminatedError)) failedCount += 1;\n\n item.reject(error);\n drainLoop();\n\n if (isIdle()) notifyIdle();\n },\n );\n }\n\n draining = false;\n }\n\n // ─── Queue helpers ────────────────────────────────────────────────────────────\n\n function nextItem(): QueueItem<TInput, TOutput> | undefined {\n while (queue.size > 0) {\n const item = queue.shift();\n\n if (!item) break;\n\n if (item.signal?.aborted) {\n item.cleanupAbort?.();\n item.reject(abortError(item.signal));\n continue;\n }\n\n return item;\n }\n\n // All remaining items were aborted and rejected above — the pool may now be idle.\n // Notify any drain() waiter so it does not hang.\n notifyIdle();\n\n return undefined;\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────────\n\n function dispose(): void {\n if (terminated) return;\n\n terminated = true;\n disposeController.abort();\n\n for (const slot of slots) slot.terminate();\n\n while (queue.size > 0) {\n const item = queue.shift();\n\n if (!item) break;\n\n item.cleanupAbort?.();\n item.reject(new FamiliarTerminatedError());\n }\n\n const resolvers = idleResolvers.splice(0);\n\n for (const resolve of resolvers) resolve();\n\n for (const waiter of fullWaiters.splice(0)) waiter();\n }\n\n function drain(timeoutMs?: number): Promise<void> {\n if (terminated) return Promise.resolve();\n\n if (drainPromise) return drainPromise;\n\n drainPromise = waitForIdle(timeoutMs).then(dispose, (err) => {\n dispose();\n throw err;\n });\n\n return drainPromise;\n }\n\n // ─── run() ───────────────────────────────────────────────────────────────────\n\n async function run(input: TInput, runOptions: RunOptions = {}): Promise<TOutput> {\n const { priority = 0, signal, timeout, transferables = [] } = runOptions;\n\n if (terminated) {\n throw new FamiliarTerminatedError();\n }\n\n if (drainPromise) {\n throw new FamiliarTerminatedError('Worker is draining');\n }\n\n if (signal?.aborted) {\n throw abortError(signal);\n }\n\n if (onFull === 'wait' && maxQueue !== undefined) {\n while (!terminated && !drainPromise && queue.size >= maxQueue) {\n await new Promise<void>((resolve) => fullWaiters.push(resolve));\n }\n\n if (terminated) throw new FamiliarTerminatedError();\n\n if (drainPromise) throw new FamiliarTerminatedError('Worker is draining');\n }\n\n let resolve!: (value: TOutput) => void;\n let reject!: (reason: unknown) => void;\n\n const promise = new Promise<TOutput>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n const item: QueueItem<TInput, TOutput> = {\n input,\n priority,\n reject,\n resolve,\n signal,\n timeout,\n transferables,\n };\n\n if (!queue.enqueue(item, onFull === 'wait' ? undefined : maxQueue)) {\n // maxQueue is guaranteed defined here: enqueue() only returns false when maxQueue is set.\n throw new FamiliarQueueFullError(maxQueue as number);\n }\n\n if (signal) {\n const onAbort = () => {\n if (!queue.remove(item)) return;\n\n item.cleanupAbort?.();\n reject(abortError(signal));\n notifyIdle();\n };\n\n item.cleanupAbort = () => {\n signal.removeEventListener('abort', onAbort);\n item.cleanupAbort = undefined;\n };\n\n signal.addEventListener('abort', onAbort, { once: true });\n }\n\n drainLoop();\n\n return promise;\n }\n\n // ─── runStream() ─────────────────────────────────────────────────────────────\n\n function runStream(input: TInput, options: Omit<RunOptions, 'signal'> = {}): AsyncIterable<TOutput> {\n if (terminated) {\n throw new FamiliarRuntimeError('Worker was terminated');\n }\n\n const slot = freeSlots.pop();\n\n if (!slot) {\n throw new FamiliarRuntimeError(\n `runStream() requires a free worker slot; all ${slots.length} slot${slots.length === 1 ? '' : 's'} are busy`,\n );\n }\n\n const { timeout, transferables = [] } = options;\n const iter = slot.runStream(input, transferables, timeout);\n\n return {\n [Symbol.asyncIterator]() {\n const inner = iter[Symbol.asyncIterator]();\n let released = false;\n\n const releaseSlot = () => {\n if (!released) {\n released = true;\n freeSlots.push(slot);\n }\n };\n\n return {\n async next() {\n const result = await inner.next();\n\n if (result.done) releaseSlot();\n\n return result;\n },\n\n async return(value?: unknown) {\n slot.cancel();\n releaseSlot();\n\n return inner.return?.(value) ?? { done: true as const, value };\n },\n\n async throw(error?: unknown) {\n slot.cancel();\n releaseSlot();\n\n if (inner.throw) return inner.throw(error);\n\n throw error;\n },\n };\n },\n };\n }\n\n // ─── batch() ─────────────────────────────────────────────────────────────────\n\n async function* batch(inputs: TInput[], batchOptions: BatchOptions = {}): AsyncIterable<TOutput> {\n if (inputs.length === 0) return;\n\n const { ordered = true, ...runOpts } = batchOptions;\n const ac = new AbortController();\n\n try {\n if (ordered) {\n const promises = inputs.map((input) => run(input, { ...runOpts, signal: ac.signal }));\n\n for (const p of promises) {\n yield await p;\n }\n } else {\n // As-completed: yield results in the order tasks finish, not submission order.\n // A single-slot notification channel wakes the consumer when the next result is ready.\n // Submission is windowed to `concurrency` outstanding (in-flight or buffered-but-unread)\n // tasks at a time — releasing capacity for one more submission each time the consumer\n // reads a result — so a slow consumer can't let an entire large batch settle in memory.\n type Completion = { error: unknown } | { value: TOutput };\n\n const completions: Completion[] = [];\n let notifier: (() => void) | null = null;\n let nextIndex = 0;\n const windowSize = Math.max(1, concurrency);\n\n function submitNext(): void {\n if (nextIndex >= inputs.length) return;\n\n const input = inputs[nextIndex++]!;\n\n run(input, { ...runOpts, signal: ac.signal }).then(\n (value) => {\n completions.push({ value });\n notifier?.();\n notifier = null;\n },\n (error: unknown) => {\n completions.push({ error });\n notifier?.();\n notifier = null;\n },\n );\n }\n\n for (let i = 0; i < windowSize && i < inputs.length; i++) submitNext();\n\n for (let i = 0; i < inputs.length; i++) {\n while (completions.length === 0) {\n await new Promise<void>((resolve) => {\n notifier = resolve;\n });\n }\n\n const next = completions.shift()!;\n\n if ('error' in next) throw next.error;\n\n yield next.value;\n\n // Only release capacity for another submission once the consumer has actually resumed\n // past this yield (i.e. did not break/return early) — submitting here unconditionally\n // would over-submit by one task on every early exit.\n submitNext();\n }\n }\n } finally {\n // Abort remaining in-flight tasks on any exit path (normal, consumer break, or error).\n ac.abort();\n }\n }\n\n // ─── group() ─────────────────────────────────────────────────────────────────\n\n function group(name?: string, options: GroupOptions = {}): TaskGroup<TInput, TOutput> {\n const ac = new AbortController();\n\n if (options.signal) {\n const sig = options.signal;\n\n if (sig.aborted) {\n ac.abort(sig.reason);\n } else {\n sig.addEventListener('abort', () => ac.abort(sig.reason), { once: true });\n }\n }\n\n groupActiveCount += 1;\n\n let submittedCount = 0;\n let settledCount = 0;\n let groupClosed = false;\n const pendingPromises: Promise<TOutput>[] = [];\n\n function decrementGroupIfDone(): void {\n if (!groupClosed && submittedCount > 0 && submittedCount === settledCount) {\n groupClosed = true;\n groupActiveCount -= 1;\n }\n }\n\n return {\n abort(reason?: unknown): void {\n ac.abort(reason);\n },\n\n drain(): Promise<PromiseSettledResult<TOutput>[]> {\n const snapshot = pendingPromises.splice(0);\n\n if (!groupClosed) {\n groupClosed = true;\n groupActiveCount -= 1;\n }\n\n return Promise.allSettled(snapshot);\n },\n\n get name() {\n return name;\n },\n\n get pending() {\n return submittedCount - settledCount;\n },\n\n run(input: TInput, runOpts: Omit<RunOptions, 'signal'> = {}): Promise<TOutput> {\n submittedCount += 1;\n\n const p = run(input, { ...runOpts, signal: ac.signal });\n\n pendingPromises.push(p);\n p.then(\n () => {\n settledCount += 1;\n decrementGroupIfDone();\n },\n () => {\n settledCount += 1;\n decrementGroupIfDone();\n },\n );\n\n return p;\n },\n\n get size() {\n return submittedCount;\n },\n };\n }\n\n // ─── Status ──────────────────────────────────────────────────────────────────\n\n function getStatus(): WorkerStatus {\n if (terminated) return 'terminated';\n\n return activeCount > 0 || queue.size > 0 ? 'running' : 'idle';\n }\n\n return {\n get active(): number {\n return activeCount;\n },\n batch,\n get completed(): number {\n return completedCount;\n },\n get concurrency(): number {\n return concurrency;\n },\n get disposalSignal(): AbortSignal {\n return disposeController.signal;\n },\n dispose,\n get disposed(): boolean {\n return terminated;\n },\n drain,\n get failed(): number {\n return failedCount;\n },\n group,\n get groupCount(): number {\n return groupActiveCount;\n },\n prime(): Promise<void> {\n return Promise.all(slots.map((s) => s.prime())).then(() => {});\n },\n get queued(): number {\n return queue.size;\n },\n run,\n runStream,\n get status(): WorkerStatus {\n return getStatus();\n },\n [Symbol.asyncDispose]: () => drain(),\n [Symbol.dispose]: dispose,\n };\n}\n","// 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":"+CACA,IAAa,EAAb,MAAa,UAAsB,KAAM,CACvC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAAoC,CAC5C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAAiD,CAAc,CAAC,EAGnD,EAAb,cAA4C,CAAc,CAExD,SAEA,YAAY,EAAkB,CAC5B,MAAM,2BAA2B,EAAS,EAAE,EAC5C,KAAK,SAAW,CAClB,CACF,EAGa,EAAb,cAAuC,CAAc,CAAC,EAGzC,EAAb,cAA6C,CAAc,CACzD,YAAY,EAAU,wBAAyB,CAC7C,MAAM,CAAO,CACf,CACF,EAGa,EAAb,cAA0C,CAAc,CAEtD,UAEA,YAAY,EAAmB,CAC7B,MAAM,wBAAwB,EAAU,GAAG,EAC3C,KAAK,UAAY,CACnB,CACF,EAGa,EAAb,cAA0C,CAAc,CAAC,ECjDnD,EAAQ,CAA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ports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./worker.cjs");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=t.createModuleWorker,exports.createWorker=t.createWorker,exports.task=t.task;
@@ -0,0 +1,2 @@
1
+ export * from './worker';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
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 { createModuleWorker as s, createWorker as c, task as l } from "./worker.js";
3
+ export { e as FamiliarError, t as FamiliarInvalidOptionsError, n as FamiliarQueueFullError, r as FamiliarRuntimeError, i as FamiliarTaskError, a as FamiliarTerminatedError, o as FamiliarTimeoutError, s as createModuleWorker, c as createWorker, l as task };
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=2;function t(e){let t=e instanceof Error?e:Error(String(e));return{message:t.message,name:t.name,stack:t.stack}}function n(e){self.onmessage=async n=>{let{id:r,input:i}=n.data;try{let t=await e(i);self.postMessage({id:r,result:t})}catch(e){self.postMessage({error:t(e),id:r})}}}function r(e){let n=self;n.onmessage=async r=>{let{id:i,input:a}=r.data;try{let t=await e(a);for await(let e of t)n.postMessage({chunk:e,id:i});n.postMessage({id:i,result:void 0})}catch(e){n.postMessage({error:t(e),id:i})}}}exports.PROTOCOL_VERSION=e,exports.handleMessages=n,exports.handleStreamMessages=r;
2
+ //# sourceMappingURL=protocol.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.cjs","names":[],"sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Host↔worker message protocol helpers for module worker files.\n *\n * Import this sub-path in module worker files to implement the protocol\n * without manual boilerplate.\n *\n * @example\n * // my-worker.ts\n * import { handleMessages } from '@vielzeug/familiar/protocol';\n * handleMessages(async (input: number) => input * 2);\n */\n\n/**\n * Current host↔worker message protocol version.\n * Increment when the protocol changes in a breaking way.\n * The host does not validate this value at runtime — it is a debugging convention only.\n * @internal\n */\nexport const PROTOCOL_VERSION = 2 as const;\n\ntype ProtocolMessage<TInput> = { id: number; input: TInput };\n\ntype ErrorPayload = { message: string; name: string; stack?: string };\n\nfunction serializeError(e: unknown): ErrorPayload {\n const err = e instanceof Error ? e : new Error(String(e));\n\n return { message: err.message, name: err.name, stack: err.stack };\n}\n\n/**\n * Sets up the `self.onmessage` handler for a module worker.\n * Handles the `{ id, input }` → `{ id, result }` / `{ id, error }` protocol automatically.\n *\n * Errors from `fn` are caught and forwarded as structured `{ id, error }` messages so the\n * host can reconstruct them as `FamiliarTaskError`. Non-Error throws are wrapped in an Error.\n *\n * @example\n * // my-worker.ts\n * import { handleMessages } from '@vielzeug/familiar/protocol';\n *\n * handleMessages(async (input: { a: number; b: number }) => input.a + input.b);\n */\nexport function handleMessages<TInput, TOutput>(fn: (input: TInput) => TOutput | Promise<TOutput>): void {\n (self as unknown as { onmessage: (event: MessageEvent<ProtocolMessage<TInput>>) => void }).onmessage = async (\n event,\n ) => {\n const { id, input } = event.data;\n\n try {\n const result = await fn(input);\n\n (self as unknown as { postMessage: (data: unknown) => void }).postMessage({ id, result });\n } catch (e) {\n (self as unknown as { postMessage: (data: unknown) => void }).postMessage({ error: serializeError(e), id });\n }\n };\n}\n\ntype StreamProtocolMessage<TInput> = { id: number; input: TInput; stream: true };\n\n/**\n * Sets up the `self.onmessage` handler for a streaming module worker.\n * The task function must return an `AsyncIterable<TOutput>`; each yielded value is forwarded\n * as a `{ id, chunk }` message, followed by `{ id, result: undefined }` on completion.\n *\n * Mirrors the inline blob worker streaming protocol so `runStream()` works with module workers.\n * Errors are forwarded as `{ id, error }` messages.\n *\n * @example\n * // my-streaming-worker.ts\n * import { handleStreamMessages } from '@vielzeug/familiar/protocol';\n *\n * handleStreamMessages(async function* (n: number) {\n * for (let i = 0; i < n; i++) {\n * yield i;\n * }\n * });\n */\nexport function handleStreamMessages<TInput, TOutput>(\n fn: (input: TInput) => AsyncIterable<TOutput> | Promise<AsyncIterable<TOutput>>,\n): void {\n const _self = self as unknown as {\n onmessage: (event: MessageEvent<StreamProtocolMessage<TInput>>) => void;\n postMessage: (data: unknown) => void;\n };\n\n _self.onmessage = async (event) => {\n const { id, input } = event.data;\n\n try {\n const iterable = await fn(input);\n\n for await (const chunk of iterable) {\n _self.postMessage({ chunk, id });\n }\n\n _self.postMessage({ id, result: undefined });\n } catch (e) {\n _self.postMessage({ error: serializeError(e), id });\n }\n };\n}\n"],"mappings":"mEAkBA,IAAa,EAAmB,EAMhC,SAAS,EAAe,EAA0B,CAChD,IAAM,EAAM,aAAa,MAAQ,EAAQ,MAAM,OAAO,CAAC,CAAC,EAExD,MAAO,CAAE,QAAS,EAAI,QAAS,KAAM,EAAI,KAAM,MAAO,EAAI,KAAM,CAClE,CAeA,SAAgB,EAAgC,EAAyD,CACvG,KAA2F,UAAY,KACrG,IACG,CACH,GAAM,CAAE,KAAI,SAAU,EAAM,KAE5B,GAAI,CACF,IAAM,EAAS,MAAM,EAAG,CAAK,EAE7B,KAA8D,YAAY,CAAE,KAAI,QAAO,CAAC,CAC1F,OAAS,EAAG,CACV,KAA8D,YAAY,CAAE,MAAO,EAAe,CAAC,EAAG,IAAG,CAAC,CAC5G,CACF,CACF,CAsBA,SAAgB,EACd,EACM,CACN,IAAM,EAAQ,KAKd,EAAM,UAAY,KAAO,IAAU,CACjC,GAAM,CAAE,KAAI,SAAU,EAAM,KAE5B,GAAI,CACF,IAAM,EAAW,MAAM,EAAG,CAAK,EAE/B,UAAW,IAAM,KAAS,EACxB,EAAM,YAAY,CAAE,QAAO,IAAG,CAAC,EAGjC,EAAM,YAAY,CAAE,KAAI,OAAQ,IAAA,EAAU,CAAC,CAC7C,OAAS,EAAG,CACV,EAAM,YAAY,CAAE,MAAO,EAAe,CAAC,EAAG,IAAG,CAAC,CACpD,CACF,CACF"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Host↔worker message protocol helpers for module worker files.
3
+ *
4
+ * Import this sub-path in module worker files to implement the protocol
5
+ * without manual boilerplate.
6
+ *
7
+ * @example
8
+ * // my-worker.ts
9
+ * import { handleMessages } from '@vielzeug/familiar/protocol';
10
+ * handleMessages(async (input: number) => input * 2);
11
+ */
12
+ /**
13
+ * Sets up the `self.onmessage` handler for a module worker.
14
+ * Handles the `{ id, input }` → `{ id, result }` / `{ id, error }` protocol automatically.
15
+ *
16
+ * Errors from `fn` are caught and forwarded as structured `{ id, error }` messages so the
17
+ * host can reconstruct them as `FamiliarTaskError`. Non-Error throws are wrapped in an Error.
18
+ *
19
+ * @example
20
+ * // my-worker.ts
21
+ * import { handleMessages } from '@vielzeug/familiar/protocol';
22
+ *
23
+ * handleMessages(async (input: { a: number; b: number }) => input.a + input.b);
24
+ */
25
+ export declare function handleMessages<TInput, TOutput>(fn: (input: TInput) => TOutput | Promise<TOutput>): void;
26
+ /**
27
+ * Sets up the `self.onmessage` handler for a streaming module worker.
28
+ * The task function must return an `AsyncIterable<TOutput>`; each yielded value is forwarded
29
+ * as a `{ id, chunk }` message, followed by `{ id, result: undefined }` on completion.
30
+ *
31
+ * Mirrors the inline blob worker streaming protocol so `runStream()` works with module workers.
32
+ * Errors are forwarded as `{ id, error }` messages.
33
+ *
34
+ * @example
35
+ * // my-streaming-worker.ts
36
+ * import { handleStreamMessages } from '@vielzeug/familiar/protocol';
37
+ *
38
+ * handleStreamMessages(async function* (n: number) {
39
+ * for (let i = 0; i < n; i++) {
40
+ * yield i;
41
+ * }
42
+ * });
43
+ */
44
+ export declare function handleStreamMessages<TInput, TOutput>(fn: (input: TInput) => AsyncIterable<TOutput> | Promise<AsyncIterable<TOutput>>): void;
45
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAoBH;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAcvG;AAID;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,EAClD,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,aAAa,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,GAC9E,IAAI,CAqBN"}
@@ -0,0 +1,53 @@
1
+ //#region src/protocol.ts
2
+ var e = 2;
3
+ function t(e) {
4
+ let t = e instanceof Error ? e : Error(String(e));
5
+ return {
6
+ message: t.message,
7
+ name: t.name,
8
+ stack: t.stack
9
+ };
10
+ }
11
+ function n(e) {
12
+ self.onmessage = async (n) => {
13
+ let { id: r, input: i } = n.data;
14
+ try {
15
+ let t = await e(i);
16
+ self.postMessage({
17
+ id: r,
18
+ result: t
19
+ });
20
+ } catch (e) {
21
+ self.postMessage({
22
+ error: t(e),
23
+ id: r
24
+ });
25
+ }
26
+ };
27
+ }
28
+ function r(e) {
29
+ let n = self;
30
+ n.onmessage = async (r) => {
31
+ let { id: i, input: a } = r.data;
32
+ try {
33
+ let t = await e(a);
34
+ for await (let e of t) n.postMessage({
35
+ chunk: e,
36
+ id: i
37
+ });
38
+ n.postMessage({
39
+ id: i,
40
+ result: void 0
41
+ });
42
+ } catch (e) {
43
+ n.postMessage({
44
+ error: t(e),
45
+ id: i
46
+ });
47
+ }
48
+ };
49
+ }
50
+ //#endregion
51
+ export { e as PROTOCOL_VERSION, n as handleMessages, r as handleStreamMessages };
52
+
53
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","names":[],"sources":["../src/protocol.ts"],"sourcesContent":["/**\n * Host↔worker message protocol helpers for module worker files.\n *\n * Import this sub-path in module worker files to implement the protocol\n * without manual boilerplate.\n *\n * @example\n * // my-worker.ts\n * import { handleMessages } from '@vielzeug/familiar/protocol';\n * handleMessages(async (input: number) => input * 2);\n */\n\n/**\n * Current host↔worker message protocol version.\n * Increment when the protocol changes in a breaking way.\n * The host does not validate this value at runtime — it is a debugging convention only.\n * @internal\n */\nexport const PROTOCOL_VERSION = 2 as const;\n\ntype ProtocolMessage<TInput> = { id: number; input: TInput };\n\ntype ErrorPayload = { message: string; name: string; stack?: string };\n\nfunction serializeError(e: unknown): ErrorPayload {\n const err = e instanceof Error ? e : new Error(String(e));\n\n return { message: err.message, name: err.name, stack: err.stack };\n}\n\n/**\n * Sets up the `self.onmessage` handler for a module worker.\n * Handles the `{ id, input }` → `{ id, result }` / `{ id, error }` protocol automatically.\n *\n * Errors from `fn` are caught and forwarded as structured `{ id, error }` messages so the\n * host can reconstruct them as `FamiliarTaskError`. Non-Error throws are wrapped in an Error.\n *\n * @example\n * // my-worker.ts\n * import { handleMessages } from '@vielzeug/familiar/protocol';\n *\n * handleMessages(async (input: { a: number; b: number }) => input.a + input.b);\n */\nexport function handleMessages<TInput, TOutput>(fn: (input: TInput) => TOutput | Promise<TOutput>): void {\n (self as unknown as { onmessage: (event: MessageEvent<ProtocolMessage<TInput>>) => void }).onmessage = async (\n event,\n ) => {\n const { id, input } = event.data;\n\n try {\n const result = await fn(input);\n\n (self as unknown as { postMessage: (data: unknown) => void }).postMessage({ id, result });\n } catch (e) {\n (self as unknown as { postMessage: (data: unknown) => void }).postMessage({ error: serializeError(e), id });\n }\n };\n}\n\ntype StreamProtocolMessage<TInput> = { id: number; input: TInput; stream: true };\n\n/**\n * Sets up the `self.onmessage` handler for a streaming module worker.\n * The task function must return an `AsyncIterable<TOutput>`; each yielded value is forwarded\n * as a `{ id, chunk }` message, followed by `{ id, result: undefined }` on completion.\n *\n * Mirrors the inline blob worker streaming protocol so `runStream()` works with module workers.\n * Errors are forwarded as `{ id, error }` messages.\n *\n * @example\n * // my-streaming-worker.ts\n * import { handleStreamMessages } from '@vielzeug/familiar/protocol';\n *\n * handleStreamMessages(async function* (n: number) {\n * for (let i = 0; i < n; i++) {\n * yield i;\n * }\n * });\n */\nexport function handleStreamMessages<TInput, TOutput>(\n fn: (input: TInput) => AsyncIterable<TOutput> | Promise<AsyncIterable<TOutput>>,\n): void {\n const _self = self as unknown as {\n onmessage: (event: MessageEvent<StreamProtocolMessage<TInput>>) => void;\n postMessage: (data: unknown) => void;\n };\n\n _self.onmessage = async (event) => {\n const { id, input } = event.data;\n\n try {\n const iterable = await fn(input);\n\n for await (const chunk of iterable) {\n _self.postMessage({ chunk, id });\n }\n\n _self.postMessage({ id, result: undefined });\n } catch (e) {\n _self.postMessage({ error: serializeError(e), id });\n }\n };\n}\n"],"mappings":";AAkBA,IAAa,IAAmB;AAMhC,SAAS,EAAe,GAA0B;CAChD,IAAM,IAAM,aAAa,QAAQ,IAAQ,MAAM,OAAO,CAAC,CAAC;CAExD,OAAO;EAAE,SAAS,EAAI;EAAS,MAAM,EAAI;EAAM,OAAO,EAAI;CAAM;AAClE;AAeA,SAAgB,EAAgC,GAAyD;CACvG,KAA2F,YAAY,OACrG,MACG;EACH,IAAM,EAAE,OAAI,aAAU,EAAM;EAE5B,IAAI;GACF,IAAM,IAAS,MAAM,EAAG,CAAK;GAE7B,KAA8D,YAAY;IAAE;IAAI;GAAO,CAAC;EAC1F,SAAS,GAAG;GACV,KAA8D,YAAY;IAAE,OAAO,EAAe,CAAC;IAAG;GAAG,CAAC;EAC5G;CACF;AACF;AAsBA,SAAgB,EACd,GACM;CACN,IAAM,IAAQ;CAKd,EAAM,YAAY,OAAO,MAAU;EACjC,IAAM,EAAE,OAAI,aAAU,EAAM;EAE5B,IAAI;GACF,IAAM,IAAW,MAAM,EAAG,CAAK;GAE/B,WAAW,IAAM,KAAS,GACxB,EAAM,YAAY;IAAE;IAAO;GAAG,CAAC;GAGjC,EAAM,YAAY;IAAE;IAAI,QAAQ,KAAA;GAAU,CAAC;EAC7C,SAAS,GAAG;GACV,EAAM,YAAY;IAAE,OAAO,EAAe,CAAC;IAAG;GAAG,CAAC;EACpD;CACF;AACF"}
@@ -0,0 +1,2 @@
1
+ export * from './testing';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC"}
@@ -0,0 +1,2 @@
1
+ const e=require("../errors.cjs"),t=require("../_pool.cjs");function n(n,r={}){let{concurrency:i=1,errorWrapping:a=!1,maxQueue:o,onFull:s=`reject`}=r;if(!Number.isInteger(i)||i<1)throw new e.FamiliarInvalidOptionsError("`concurrency` must be a positive integer");if(o!==void 0&&(!Number.isInteger(o)||o<1))throw new e.FamiliarInvalidOptionsError("`maxQueue` must be a positive integer");let c=[];function l(){let t=!1;return{cancel(){},prime(){return Promise.resolve()},async run(r,i,o){if(t)return Promise.reject(new e.FamiliarTerminatedError);try{let e=await n(r);return c.push({input:r,output:e}),e}catch(t){if(!a)throw t;let n=t instanceof Error?t:Error(String(t));throw new e.FamiliarTaskError(n.message,{cause:n})}},runStream(t,n,r){return{[Symbol.asyncIterator](){return{next(){return Promise.reject(new e.FamiliarRuntimeError(`runStream() is not supported by createTestWorker`))}}}}},terminate(){t=!0}}}let u=t.createPool(Array.from({length:i},l),{concurrency:i,defaultTimeout:void 0,maxQueue:o,onFull:s});return Object.defineProperty(u,"calls",{enumerable:!0,get(){return c}}),u}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.createTestWorker=n;
2
+ //# sourceMappingURL=testing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.cjs","names":[],"sources":["../../src/testing/testing.ts"],"sourcesContent":["import type { SlotStrategy, WorkerHandle, WorkerStatus } from '../types';\n\nimport { createPool } from '../_pool';\nimport {\n FamiliarInvalidOptionsError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n} from '../errors';\n\nexport type TestWorkerOptions = {\n /**\n * Number of concurrent in-process execution slots. Default: 1 for deterministic test ordering.\n * Increase only when testing concurrency-specific behavior.\n */\n concurrency?: number;\n /**\n * When true, errors from fn are wrapped in FamiliarTaskError/FamiliarRuntimeError, mirroring\n * real worker behavior. Default: false (errors propagate unwrapped for better test DX).\n */\n errorWrapping?: boolean;\n maxQueue?: number;\n /** 'wait' suspends run() callers when the queue is full instead of rejecting. */\n onFull?: 'reject' | 'wait';\n};\n\nexport type TestWorkerHandle<TInput, TOutput> = WorkerHandle<TInput, TOutput> & {\n /** Recorded { input, output } pairs for every successful run(), in call order. */\n readonly calls: ReadonlyArray<{ input: TInput; output: TOutput }>;\n};\n\nexport function createTestWorker<TInput, TOutput>(\n fn: (input: TInput) => TOutput | Promise<TOutput>,\n options: TestWorkerOptions = {},\n): TestWorkerHandle<TInput, TOutput> {\n const { concurrency = 1, errorWrapping = false, maxQueue, onFull = 'reject' } = options;\n\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new FamiliarInvalidOptionsError('`concurrency` must be a positive integer');\n }\n\n if (maxQueue !== undefined && (!Number.isInteger(maxQueue) || maxQueue < 1)) {\n throw new FamiliarInvalidOptionsError('`maxQueue` must be a positive integer');\n }\n\n const calls: { input: TInput; output: TOutput }[] = [];\n\n /**\n * In-process SlotStrategy. Errors propagate unwrapped by default (better test DX:\n * vitest AssertionErrors surface directly). Set errorWrapping: true to mirror real worker\n * behavior (useful when testing code that checks `error instanceof FamiliarError`).\n */\n function makeSlot(): SlotStrategy<TInput, TOutput> {\n let terminated = false;\n\n return {\n cancel(): void {\n // No-op: in-process tasks cannot be cancelled mid-flight.\n },\n\n prime(): Promise<void> {\n return Promise.resolve();\n },\n\n async run(input: TInput, _transferables: Transferable[], _timeout: number | undefined): Promise<TOutput> {\n if (terminated) return Promise.reject(new FamiliarTerminatedError());\n\n try {\n const output = await fn(input);\n\n calls.push({ input, output });\n\n return output;\n } catch (e) {\n if (!errorWrapping) throw e;\n\n const err = e instanceof Error ? e : new Error(String(e));\n\n throw new FamiliarTaskError(err.message, { cause: err });\n }\n },\n\n runStream(_input: TInput, _transferables: Transferable[], _timeout: number | undefined): AsyncIterable<TOutput> {\n return {\n [Symbol.asyncIterator]() {\n return {\n next(): Promise<IteratorResult<TOutput>> {\n return Promise.reject(new FamiliarRuntimeError('runStream() is not supported by createTestWorker'));\n },\n };\n },\n };\n },\n\n terminate(): void {\n terminated = true;\n },\n };\n }\n\n const slots = Array.from({ length: concurrency }, makeSlot);\n\n const pool = createPool(slots, {\n concurrency,\n defaultTimeout: undefined,\n maxQueue,\n onFull,\n });\n\n // Use Object.defineProperty so the `calls` getter is a true accessor descriptor.\n Object.defineProperty(pool, 'calls', {\n enumerable: true,\n get(): ReadonlyArray<{ input: TInput; output: TOutput }> {\n return calls;\n },\n });\n\n return pool as unknown as TestWorkerHandle<TInput, TOutput>;\n}\n\n// Re-export types consumed by test files so they don't need to import from two places.\nexport type { WorkerHandle, WorkerStatus };\nexport {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n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AChB,WACA,QACF,CAAC,EAUD,OAPA,OAAO,eAAe,EAAM,QAAS,CACnC,WAAY,GACZ,KAAyD,CACvD,OAAO,CACT,CACF,CAAC,EAEM,CACT"}
@@ -0,0 +1,27 @@
1
+ import type { WorkerHandle, WorkerStatus } from '../types';
2
+ export type TestWorkerOptions = {
3
+ /**
4
+ * Number of concurrent in-process execution slots. Default: 1 for deterministic test ordering.
5
+ * Increase only when testing concurrency-specific behavior.
6
+ */
7
+ concurrency?: number;
8
+ /**
9
+ * When true, errors from fn are wrapped in FamiliarTaskError/FamiliarRuntimeError, mirroring
10
+ * real worker behavior. Default: false (errors propagate unwrapped for better test DX).
11
+ */
12
+ errorWrapping?: boolean;
13
+ maxQueue?: number;
14
+ /** 'wait' suspends run() callers when the queue is full instead of rejecting. */
15
+ onFull?: 'reject' | 'wait';
16
+ };
17
+ export type TestWorkerHandle<TInput, TOutput> = WorkerHandle<TInput, TOutput> & {
18
+ /** Recorded { input, output } pairs for every successful run(), in call order. */
19
+ readonly calls: ReadonlyArray<{
20
+ input: TInput;
21
+ output: TOutput;
22
+ }>;
23
+ };
24
+ export declare function createTestWorker<TInput, TOutput>(fn: (input: TInput) => TOutput | Promise<TOutput>, options?: TestWorkerOptions): TestWorkerHandle<TInput, TOutput>;
25
+ export type { WorkerHandle, WorkerStatus };
26
+ export { FamiliarError, FamiliarInvalidOptionsError, FamiliarQueueFullError, FamiliarRuntimeError, FamiliarTaskError, FamiliarTerminatedError, FamiliarTimeoutError, } from '../errors';
27
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../src/testing/testing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,YAAY,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAUzE,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iFAAiF;IACjF,MAAM,CAAC,EAAE,QAAQ,GAAG,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,gBAAgB,CAAC,MAAM,EAAE,OAAO,IAAI,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;IAC9E,kFAAkF;IAClF,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CACnE,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,EAC9C,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,EACjD,OAAO,GAAE,iBAAsB,GAC9B,gBAAgB,CAAC,MAAM,EAAE,OAAO,CAAC,CAoFnC;AAGD,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,CAAC;AAC3C,OAAO,EACL,aAAa,EACb,2BAA2B,EAC3B,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,WAAW,CAAC"}
@@ -0,0 +1,58 @@
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 { createPool as s } from "../_pool.js";
3
+ //#region src/testing/testing.ts
4
+ function c(e, n = {}) {
5
+ let { concurrency: o = 1, errorWrapping: c = !1, maxQueue: l, onFull: u = "reject" } = n;
6
+ if (!Number.isInteger(o) || o < 1) throw new t("`concurrency` must be a positive integer");
7
+ if (l !== void 0 && (!Number.isInteger(l) || l < 1)) throw new t("`maxQueue` must be a positive integer");
8
+ let d = [];
9
+ function f() {
10
+ let t = !1;
11
+ return {
12
+ cancel() {},
13
+ prime() {
14
+ return Promise.resolve();
15
+ },
16
+ async run(n, r, o) {
17
+ if (t) return Promise.reject(new a());
18
+ try {
19
+ let t = await e(n);
20
+ return d.push({
21
+ input: n,
22
+ output: t
23
+ }), t;
24
+ } catch (e) {
25
+ if (!c) throw e;
26
+ let t = e instanceof Error ? e : Error(String(e));
27
+ throw new i(t.message, { cause: t });
28
+ }
29
+ },
30
+ runStream(e, t, n) {
31
+ return { [Symbol.asyncIterator]() {
32
+ return { next() {
33
+ return Promise.reject(new r("runStream() is not supported by createTestWorker"));
34
+ } };
35
+ } };
36
+ },
37
+ terminate() {
38
+ t = !0;
39
+ }
40
+ };
41
+ }
42
+ let p = s(Array.from({ length: o }, f), {
43
+ concurrency: o,
44
+ defaultTimeout: void 0,
45
+ maxQueue: l,
46
+ onFull: u
47
+ });
48
+ return Object.defineProperty(p, "calls", {
49
+ enumerable: !0,
50
+ get() {
51
+ return d;
52
+ }
53
+ }), p;
54
+ }
55
+ //#endregion
56
+ export { e as FamiliarError, t as FamiliarInvalidOptionsError, n as FamiliarQueueFullError, r as FamiliarRuntimeError, i as FamiliarTaskError, a as FamiliarTerminatedError, o as FamiliarTimeoutError, c as createTestWorker };
57
+
58
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../../src/testing/testing.ts"],"sourcesContent":["import type { SlotStrategy, WorkerHandle, WorkerStatus } from '../types';\n\nimport { createPool } from '../_pool';\nimport {\n FamiliarInvalidOptionsError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n} from '../errors';\n\nexport type TestWorkerOptions = {\n /**\n * Number of concurrent in-process execution slots. Default: 1 for deterministic test ordering.\n * Increase only when testing concurrency-specific behavior.\n */\n concurrency?: number;\n /**\n * When true, errors from fn are wrapped in FamiliarTaskError/FamiliarRuntimeError, mirroring\n * real worker behavior. Default: false (errors propagate unwrapped for better test DX).\n */\n errorWrapping?: boolean;\n maxQueue?: number;\n /** 'wait' suspends run() callers when the queue is full instead of rejecting. */\n onFull?: 'reject' | 'wait';\n};\n\nexport type TestWorkerHandle<TInput, TOutput> = WorkerHandle<TInput, TOutput> & {\n /** Recorded { input, output } pairs for every successful run(), in call order. */\n readonly calls: ReadonlyArray<{ input: TInput; output: TOutput }>;\n};\n\nexport function createTestWorker<TInput, TOutput>(\n fn: (input: TInput) => TOutput | Promise<TOutput>,\n options: TestWorkerOptions = {},\n): TestWorkerHandle<TInput, TOutput> {\n const { concurrency = 1, errorWrapping = false, maxQueue, onFull = 'reject' } = options;\n\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new FamiliarInvalidOptionsError('`concurrency` must be a positive integer');\n }\n\n if (maxQueue !== undefined && (!Number.isInteger(maxQueue) || maxQueue < 1)) {\n throw new FamiliarInvalidOptionsError('`maxQueue` must be a positive integer');\n }\n\n const calls: { input: TInput; output: TOutput }[] = [];\n\n /**\n * In-process SlotStrategy. Errors propagate unwrapped by default (better test DX:\n * vitest AssertionErrors surface directly). Set errorWrapping: true to mirror real worker\n * behavior (useful when testing code that checks `error instanceof FamiliarError`).\n */\n function makeSlot(): SlotStrategy<TInput, TOutput> {\n let terminated = false;\n\n return {\n cancel(): void {\n // No-op: in-process tasks cannot be cancelled mid-flight.\n },\n\n prime(): Promise<void> {\n return Promise.resolve();\n },\n\n async run(input: TInput, _transferables: Transferable[], _timeout: number | undefined): Promise<TOutput> {\n if (terminated) return Promise.reject(new FamiliarTerminatedError());\n\n try {\n const output = await fn(input);\n\n calls.push({ input, output });\n\n return output;\n } catch (e) {\n if (!errorWrapping) throw e;\n\n const err = e instanceof Error ? e : new Error(String(e));\n\n throw new FamiliarTaskError(err.message, { cause: err });\n }\n },\n\n runStream(_input: TInput, _transferables: Transferable[], _timeout: number | undefined): AsyncIterable<TOutput> {\n return {\n [Symbol.asyncIterator]() {\n return {\n next(): Promise<IteratorResult<TOutput>> {\n return Promise.reject(new FamiliarRuntimeError('runStream() is not supported by createTestWorker'));\n },\n };\n },\n };\n },\n\n terminate(): void {\n terminated = true;\n },\n };\n }\n\n const slots = Array.from({ length: concurrency }, makeSlot);\n\n const pool = createPool(slots, {\n concurrency,\n defaultTimeout: undefined,\n maxQueue,\n onFull,\n });\n\n // Use Object.defineProperty so the `calls` getter is a true accessor descriptor.\n Object.defineProperty(pool, 'calls', {\n enumerable: true,\n get(): ReadonlyArray<{ input: TInput; output: TOutput }> {\n return calls;\n },\n });\n\n return pool as unknown as TestWorkerHandle<TInput, TOutput>;\n}\n\n// Re-export types consumed by test files so they don't need to import from two places.\nexport type { WorkerHandle, WorkerStatus };\nexport {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from '../errors';\n"],"mappings":";;;AA+BA,SAAgB,EACd,GACA,IAA6B,CAAC,GACK;CACnC,IAAM,EAAE,iBAAc,GAAG,mBAAgB,IAAO,aAAU,YAAS,aAAa;CAEhF,IAAI,CAAC,OAAO,UAAU,CAAW,KAAK,IAAc,GAClD,MAAM,IAAI,EAA4B,0CAA0C;CAGlF,IAAI,MAAa,KAAA,MAAc,CAAC,OAAO,UAAU,CAAQ,KAAK,IAAW,IACvE,MAAM,IAAI,EAA4B,uCAAuC;CAG/E,IAAM,IAA8C,CAAC;CAOrD,SAAS,IAA0C;EACjD,IAAI,IAAa;EAEjB,OAAO;GACL,SAAe,CAEf;GAEA,QAAuB;IACrB,OAAO,QAAQ,QAAQ;GACzB;GAEA,MAAM,IAAI,GAAe,GAAgC,GAAgD;IACvG,IAAI,GAAY,OAAO,QAAQ,OAAO,IAAI,EAAwB,CAAC;IAEnE,IAAI;KACF,IAAM,IAAS,MAAM,EAAG,CAAK;KAI7B,OAFA,EAAM,KAAK;MAAE;MAAO;KAAO,CAAC,GAErB;IACT,SAAS,GAAG;KACV,IAAI,CAAC,GAAe,MAAM;KAE1B,IAAM,IAAM,aAAa,QAAQ,IAAQ,MAAM,OAAO,CAAC,CAAC;KAExD,MAAM,IAAI,EAAkB,EAAI,SAAS,EAAE,OAAO,EAAI,CAAC;IACzD;GACF;GAEA,UAAU,GAAgB,GAAgC,GAAsD;IAC9G,OAAO,EACL,CAAC,OAAO,iBAAiB;KACvB,OAAO,EACL,OAAyC;MACvC,OAAO,QAAQ,OAAO,IAAI,EAAqB,kDAAkD,CAAC;KACpG,EACF;IACF,EACF;GACF;GAEA,YAAkB;IAChB,IAAa;GACf;EACF;CACF;CAIA,IAAM,IAAO,EAFC,MAAM,KAAK,EAAE,QAAQ,EAAY,GAAG,CAE1B,GAAO;EAC7B;EACA,gBAAgB,KAAA;EAChB;EACA;CACF,CAAC;CAUD,OAPA,OAAO,eAAe,GAAM,SAAS;EACnC,YAAY;EACZ,MAAyD;GACvD,OAAO;EACT;CACF,CAAC,GAEM;AACT"}
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./testing/testing.cjs");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.createTestWorker=t.createTestWorker;
@@ -0,0 +1,3 @@
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 { createTestWorker as s } from "./testing/testing.js";
3
+ export { e as FamiliarError, t as FamiliarInvalidOptionsError, n as FamiliarQueueFullError, r as FamiliarRuntimeError, i as FamiliarTaskError, a as FamiliarTerminatedError, o as FamiliarTimeoutError, s as createTestWorker };
@@ -0,0 +1,147 @@
1
+ import type { FamiliarRuntimeError } from './errors';
2
+ export type TaskFn<TInput, TOutput> = (input: TInput) => TOutput | Promise<TOutput>;
3
+ export type WorkerStatus = 'idle' | 'running' | 'terminated';
4
+ /**
5
+ * Execution abstraction consumed by `createPool`.
6
+ * Implementors: `Slot` (real worker) and in-process executor (test double).
7
+ */
8
+ export type SlotStrategy<TInput, TOutput> = {
9
+ /**
10
+ * Cancel the current in-flight task and stop the underlying worker without marking the slot as
11
+ * permanently disposed. The slot can be reused immediately — a fresh worker will be created on
12
+ * the next run() or runStream() call. Used for streaming early consumer exit (break/throw).
13
+ */
14
+ cancel(): void;
15
+ prime(): Promise<void>;
16
+ run(input: TInput, transferables: Transferable[], timeout: number | undefined): Promise<TOutput>;
17
+ runStream(input: TInput, transferables: Transferable[], timeout: number | undefined): AsyncIterable<TOutput>;
18
+ terminate(): void;
19
+ };
20
+ export type RunOptions = {
21
+ /**
22
+ * Task scheduling priority. Higher values run before lower values when tasks queue up.
23
+ * Within the same priority, tasks run FIFO. Default: 0.
24
+ */
25
+ priority?: number;
26
+ /** AbortSignal to cancel a queued task. Note: in-flight tasks cannot be cancelled. */
27
+ signal?: AbortSignal;
28
+ /** Per-run timeout in milliseconds. Overrides the pool-level timeout for this task only. */
29
+ timeout?: number;
30
+ /** Transferable objects to move to the worker thread (avoids structured-clone copy). */
31
+ transferables?: Transferable[];
32
+ };
33
+ export type BatchOptions = Omit<RunOptions, 'signal'> & {
34
+ /**
35
+ * When false, results are yielded as each task completes (out-of-submission order, maximum
36
+ * throughput). Default: true (results are yielded in submission order).
37
+ */
38
+ ordered?: boolean;
39
+ };
40
+ export type WorkerOptions = {
41
+ /** Number of concurrent worker slots. Default: 1. Pass 'auto' to use navigator.hardwareConcurrency. */
42
+ concurrency?: number | 'auto';
43
+ /**
44
+ * Watchdog window in milliseconds applied to every task in the pool.
45
+ * If the worker does not send a heartbeat message within this window, the task is
46
+ * killed with FamiliarTimeoutError. Useful for long-running CPU tasks that must stay responsive.
47
+ * For inline workers the heartbeat is sent automatically at heartbeatWindow / 2 intervals.
48
+ * Module workers must implement the heartbeat protocol manually.
49
+ */
50
+ heartbeatWindow?: number;
51
+ /** Maximum queued tasks. When onFull='reject', exceeding this limit rejects with FamiliarQueueFullError. Default: unlimited. */
52
+ maxQueue?: number;
53
+ /**
54
+ * When 'wait', run() suspends the caller when the queue is full instead of rejecting.
55
+ * Useful for large producer→consumer pipelines to apply natural backpressure. Default: 'reject'.
56
+ */
57
+ onFull?: 'reject' | 'wait';
58
+ /**
59
+ * Called when a Worker slot encounters an unhandled runtime error (worker.onerror).
60
+ * The slot stops automatically; call restart() to pre-warm the replacement Worker.
61
+ * If omitted, errors are handled silently and the slot restarts on the next run() call.
62
+ */
63
+ onSlotError?: (error: FamiliarRuntimeError, restart: () => void) => void;
64
+ /** Default task timeout in milliseconds. Can be overridden per-run via RunOptions. Default: none. */
65
+ timeout?: number;
66
+ };
67
+ /**
68
+ * Full handle returned by `createWorker` and `createModuleWorker`.
69
+ * All capabilities are on one flat interface — no need to cross-reference mixin types.
70
+ */
71
+ export interface WorkerHandle<TInput, TOutput> {
72
+ /** Graceful drain — delegates to `drain()`. Enables `await using` declarations. */
73
+ [Symbol.asyncDispose](): Promise<void>;
74
+ /** Immediate terminate — delegates to `dispose()`. Enables `using` declarations. */
75
+ [Symbol.dispose](): void;
76
+ /** Number of slots currently executing a task. */
77
+ readonly active: number;
78
+ /**
79
+ * Run all inputs through the pool and yield results.
80
+ * By default yields in submission order. Pass ordered: false to yield as-completed.
81
+ */
82
+ batch(inputs: TInput[], options?: BatchOptions): AsyncIterable<TOutput>;
83
+ /** Number of successfully completed tasks since creation. */
84
+ readonly completed: number;
85
+ /** Number of worker slots. */
86
+ readonly concurrency: number;
87
+ /** `AbortSignal` aborted when the pool is terminated (via `dispose()` or `drain()` settling). */
88
+ readonly disposalSignal: AbortSignal;
89
+ /** Terminate immediately, rejecting all in-flight and queued tasks. */
90
+ dispose(): void;
91
+ /** `true` after `dispose()` has been called or `drain()` has settled. */
92
+ readonly disposed: boolean;
93
+ /** Gracefully drain queued/in-flight tasks then terminate workers. Rejects if timeoutMs elapses. */
94
+ drain(timeoutMs?: number): Promise<void>;
95
+ /** Number of tasks that failed with a task / timeout / worker error (excludes aborts and terminations). */
96
+ readonly failed: number;
97
+ /** Create a task group. All tasks share an AbortController and can be drained together. */
98
+ group(name?: string, options?: GroupOptions): TaskGroup<TInput, TOutput>;
99
+ /** Number of active groups (created but not yet fully drained or aborted). */
100
+ readonly groupCount: number;
101
+ /** Pre-initialize all worker slots to reduce first-task latency. */
102
+ prime(): Promise<void>;
103
+ /** Number of queued tasks waiting to run (excludes cancelled/aborted items). */
104
+ readonly queued: number;
105
+ /** Execute the task. Tasks are queued when all slots are busy. */
106
+ run(input: TInput, options?: RunOptions): Promise<TOutput>;
107
+ /**
108
+ * Run a streaming task and yield partial results as they arrive.
109
+ * The worker function must return an async iterable; each yielded value is forwarded as a chunk.
110
+ *
111
+ * Unlike run(), streaming tasks cannot be queued — they require an immediately available slot.
112
+ * Throws FamiliarRuntimeError synchronously if all slots are busy.
113
+ * Note: `signal` is not supported for streaming tasks (cannot be queued); use `break` to stop early.
114
+ */
115
+ runStream(input: TInput, options?: Omit<RunOptions, 'signal'>): AsyncIterable<TOutput>;
116
+ /** Current lifecycle state of the pool. */
117
+ readonly status: WorkerStatus;
118
+ }
119
+ export type GroupOptions = {
120
+ /**
121
+ * When this signal is aborted, the group is aborted automatically.
122
+ * Composable with `WorkerHandle.disposalSignal` to tie the group lifetime to the pool.
123
+ */
124
+ signal?: AbortSignal;
125
+ };
126
+ export type TaskGroup<TInput, TOutput> = {
127
+ /** Cancel all pending tasks in this group. In-flight tasks run to natural completion. */
128
+ abort(reason?: unknown): void;
129
+ /**
130
+ * Wait for all tasks submitted so far to settle.
131
+ * Returns settled results — both fulfilled values and rejection reasons.
132
+ * Tasks added after drain() starts are not included in this call.
133
+ */
134
+ drain(): Promise<PromiseSettledResult<TOutput>[]>;
135
+ /** Optional name provided when the group was created. */
136
+ readonly name: string | undefined;
137
+ /** Number of tasks not yet settled (decrements as tasks complete). */
138
+ readonly pending: number;
139
+ /**
140
+ * Submit a task to the pool, associating it with this group.
141
+ * Throws `FamiliarTerminatedError` synchronously if the pool has been disposed or is closing.
142
+ */
143
+ run(input: TInput, options?: Omit<RunOptions, 'signal'>): Promise<TOutput>;
144
+ /** Total number of tasks ever submitted to this group (never decrements). */
145
+ readonly size: number;
146
+ };
147
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAIrD,MAAM,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAEpF,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,YAAY,CAAC;AAI7D;;;GAGG;AACH,MAAM,MAAM,YAAY,CAAC,MAAM,EAAE,OAAO,IAAI;IAC1C;;;;OAIG;IACH,MAAM,IAAI,IAAI,CAAC;IACf,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACjG,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7G,SAAS,IAAI,IAAI,CAAC;CACnB,CAAC;AAIF,MAAM,MAAM,UAAU,GAAG;IACvB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACt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