UNPKG

@xylabs/threads

Version:

Web workers & worker threads as simple as a function call

1 lines 94.6 kB
{"version":3,"sources":["../../../../../node_modules/.store/tiny-worker-npm-2.3.0-38c7100e1d/package/lib/index.js","../../../src/master/implementation.node.ts","../../../src/master/pool-browser.ts","../../../src/master/implementation.browser.ts","../../../src/master/pool-types.ts","../../../src/symbols.ts","../../../src/master/thread.ts","../../../src/master/spawn.ts","../../../src/serializers.ts","../../../src/common.ts","../../../src/promise.ts","../../../src/types/master.ts","../../../src/master/invocation-proxy.ts","../../../src/observable-promise.ts","../../../src/transferable.ts","../../../src/types/messages.ts","../../../src/master/index-node.ts"],"sourcesContent":["\"use strict\";\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar path = require(\"path\"),\n fork = require(\"child_process\").fork,\n worker = path.join(__dirname, \"worker.js\"),\n events = /^(error|message)$/,\n defaultPorts = { inspect: 9229, debug: 5858 };\nvar range = { min: 1, max: 300 };\n\nvar Worker = function () {\n\tfunction Worker(arg) {\n\t\tvar _this = this;\n\n\t\tvar args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n\t\tvar options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { cwd: process.cwd() };\n\n\t\t_classCallCheck(this, Worker);\n\n\t\tvar isfn = typeof arg === \"function\",\n\t\t input = isfn ? arg.toString() : arg;\n\n\t\tif (!options.cwd) {\n\t\t\toptions.cwd = process.cwd();\n\t\t}\n\n\t\t//get all debug related parameters\n\t\tvar debugVars = process.execArgv.filter(function (execArg) {\n\t\t\treturn (/(debug|inspect)/.test(execArg)\n\t\t\t);\n\t\t});\n\t\tif (debugVars.length > 0 && !options.noDebugRedirection) {\n\t\t\tif (!options.execArgv) {\n\t\t\t\t//if no execArgs are given copy all arguments\n\t\t\t\tdebugVars = Array.from(process.execArgv);\n\t\t\t\toptions.execArgv = [];\n\t\t\t}\n\n\t\t\tvar inspectIndex = debugVars.findIndex(function (debugArg) {\n\t\t\t\t//get index of inspect parameter\n\t\t\t\treturn (/^--inspect(-brk)?(=\\d+)?$/.test(debugArg)\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tvar debugIndex = debugVars.findIndex(function (debugArg) {\n\t\t\t\t//get index of debug parameter\n\t\t\t\treturn (/^--debug(-brk)?(=\\d+)?$/.test(debugArg)\n\t\t\t\t);\n\t\t\t});\n\n\t\t\tvar portIndex = inspectIndex >= 0 ? inspectIndex : debugIndex; //get index of port, inspect has higher priority\n\n\t\t\tif (portIndex >= 0) {\n\t\t\t\tvar match = /^--(debug|inspect)(?:-brk)?(?:=(\\d+))?$/.exec(debugVars[portIndex]); //get port\n\t\t\t\tvar port = defaultPorts[match[1]];\n\t\t\t\tif (match[2]) {\n\t\t\t\t\tport = parseInt(match[2]);\n\t\t\t\t}\n\t\t\t\tdebugVars[portIndex] = \"--\" + match[1] + \"=\" + (port + range.min + Math.floor(Math.random() * (range.max - range.min))); //new parameter\n\n\t\t\t\tif (debugIndex >= 0 && debugIndex !== portIndex) {\n\t\t\t\t\t//remove \"-brk\" from debug if there\n\t\t\t\t\tmatch = /^(--debug)(?:-brk)?(.*)/.exec(debugVars[debugIndex]);\n\t\t\t\t\tdebugVars[debugIndex] = match[1] + (match[2] ? match[2] : \"\");\n\t\t\t\t}\n\t\t\t}\n\t\t\toptions.execArgv = options.execArgv.concat(debugVars);\n\t\t}\n\n\t\tdelete options.noDebugRedirection;\n\n\t\tthis.child = fork(worker, args, options);\n\t\tthis.onerror = undefined;\n\t\tthis.onmessage = undefined;\n\n\t\tthis.child.on(\"error\", function (e) {\n\t\t\tif (_this.onerror) {\n\t\t\t\t_this.onerror.call(_this, e);\n\t\t\t}\n\t\t});\n\n\t\tthis.child.on(\"message\", function (msg) {\n\t\t\tvar message = JSON.parse(msg);\n\t\t\tvar error = void 0;\n\n\t\t\tif (!message.error && _this.onmessage) {\n\t\t\t\t_this.onmessage.call(_this, message);\n\t\t\t}\n\n\t\t\tif (message.error && _this.onerror) {\n\t\t\t\terror = new Error(message.error);\n\t\t\t\terror.stack = message.stack;\n\n\t\t\t\t_this.onerror.call(_this, error);\n\t\t\t}\n\t\t});\n\n\t\tthis.child.send({ input: input, isfn: isfn, cwd: options.cwd, esm: options.esm });\n\t}\n\n\t_createClass(Worker, [{\n\t\tkey: \"addEventListener\",\n\t\tvalue: function addEventListener(event, fn) {\n\t\t\tif (events.test(event)) {\n\t\t\t\tthis[\"on\" + event] = fn;\n\t\t\t}\n\t\t}\n\t}, {\n\t\tkey: \"postMessage\",\n\t\tvalue: function postMessage(msg) {\n\t\t\tthis.child.send(JSON.stringify({ data: msg }, null, 0));\n\t\t}\n\t}, {\n\t\tkey: \"terminate\",\n\t\tvalue: function terminate() {\n\t\t\tthis.child.kill(\"SIGINT\");\n\t\t}\n\t}], [{\n\t\tkey: \"setRange\",\n\t\tvalue: function setRange(min, max) {\n\t\t\tif (min >= max) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\trange.min = min;\n\t\t\trange.max = max;\n\n\t\t\treturn true;\n\t\t}\n\t}]);\n\n\treturn Worker;\n}();\n\nmodule.exports = Worker;\n","/* eslint-disable @typescript-eslint/no-require-imports */\n\n/* eslint-disable unicorn/prefer-add-event-listener */\n/* eslint-disable unicorn/prefer-event-target */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable unicorn/text-encoding-identifier-case */\n\nimport { EventEmitter } from 'node:events'\nimport { cpus } from 'node:os'\nimport path from 'node:path'\nimport { cwd } from 'node:process'\nimport { Worker as NativeWorker } from 'node:worker_threads'\n\nimport type {\n ImplementationExport, ThreadsWorkerOptions, WorkerImplementation,\n// eslint-disable-next-line import-x/no-internal-modules\n} from '../types/master.ts'\n\ndeclare const __non_webpack_require__: typeof require\n\ntype WorkerEventName = 'error' | 'message'\n\nexport const defaultPoolSize = cpus().length\n\nfunction resolveScriptPath(scriptPath: string, baseURL?: string | undefined) {\n const makeAbsolute = (filePath: string) => {\n return path.isAbsolute(filePath) ? filePath : path.join(baseURL ?? cwd(), filePath)\n }\n\n const absolutePath = makeAbsolute(scriptPath)\n return absolutePath\n}\n\nfunction initWorkerThreadsWorker(): ImplementationExport {\n let allWorkers: Array<NativeWorker> = []\n\n class Worker extends NativeWorker {\n private mappedEventListeners: WeakMap<EventListener, EventListener>\n\n constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource: boolean }) {\n const resolvedScriptPath = options && options.fromSource ? null : resolveScriptPath(scriptPath, (options ?? {})._baseURL)\n if (resolvedScriptPath) {\n super(resolvedScriptPath, options)\n } else {\n // `options.fromSource` is true\n const sourceCode = scriptPath\n super(sourceCode, { ...options, eval: true })\n }\n\n this.mappedEventListeners = new WeakMap()\n allWorkers.push(this)\n }\n\n addEventListener(eventName: string, rawListener: EventListener) {\n const listener = (message: any) => {\n rawListener({ data: message } as any)\n }\n this.mappedEventListeners.set(rawListener, listener)\n this.on(eventName, listener)\n }\n\n removeEventListener(eventName: string, rawListener: EventListener) {\n const listener = this.mappedEventListeners.get(rawListener) || rawListener\n this.off(eventName, listener)\n }\n }\n\n const terminateWorkersAndMaster = () => {\n // we should terminate all workers and then gracefully shutdown self process\n Promise.all(allWorkers.map(worker => worker.terminate())).then(\n () => process.exit(0),\n () => process.exit(1),\n )\n allWorkers = []\n }\n\n // Take care to not leave orphaned processes behind. See #147.\n process.on('SIGINT', () => terminateWorkersAndMaster())\n process.on('SIGTERM', () => terminateWorkersAndMaster())\n\n class BlobWorker extends Worker {\n constructor(blob: Uint8Array, options?: ThreadsWorkerOptions) {\n super(Buffer.from(blob).toString('utf-8'), { ...options, fromSource: true })\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation {\n return new Worker(source, { ...options, fromSource: true }) as any\n }\n }\n\n return {\n blob: BlobWorker as any,\n default: Worker as any,\n }\n}\n\nfunction initTinyWorker(): ImplementationExport {\n const TinyWorker = require('tiny-worker')\n\n let allWorkers: Array<typeof TinyWorker> = []\n\n class Worker extends TinyWorker {\n private emitter: EventEmitter\n\n constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource?: boolean }) {\n // Need to apply a work-around for Windows or it will choke upon the absolute path\n // (`Error [ERR_INVALID_PROTOCOL]: Protocol 'c:' not supported`)\n const resolvedScriptPath\n = options && options.fromSource\n ? null\n : process.platform === 'win32'\n ? `file:///${resolveScriptPath(scriptPath).replaceAll('\\\\', '/')}`\n : resolveScriptPath(scriptPath)\n\n if (resolvedScriptPath) {\n super(resolvedScriptPath, [], { esm: true })\n } else {\n // `options.fromSource` is true\n const sourceCode = scriptPath\n super(new Function(sourceCode), [], { esm: true })\n }\n\n allWorkers.push(this)\n\n this.emitter = new EventEmitter()\n this.onerror = (error: Error) => this.emitter.emit('error', error)\n this.onmessage = (message: MessageEvent) => this.emitter.emit('message', message)\n }\n\n addEventListener(eventName: WorkerEventName, listener: EventListener) {\n this.emitter.addListener(eventName, listener)\n }\n\n removeEventListener(eventName: WorkerEventName, listener: EventListener) {\n this.emitter.removeListener(eventName, listener)\n }\n\n terminate() {\n allWorkers = allWorkers.filter(worker => worker !== this)\n return super.terminate()\n }\n }\n\n const terminateWorkersAndMaster = () => {\n // we should terminate all workers and then gracefully shutdown self process\n Promise.all(allWorkers.map(worker => worker.terminate())).then(\n () => process.exit(0),\n () => process.exit(1),\n )\n allWorkers = []\n }\n\n // Take care to not leave orphaned processes behind\n // See <https://github.com/avoidwork/tiny-worker#faq>\n process.on('SIGINT', () => terminateWorkersAndMaster())\n process.on('SIGTERM', () => terminateWorkersAndMaster())\n\n class BlobWorker extends Worker {\n constructor(blob: Uint8Array, options?: ThreadsWorkerOptions) {\n super(Buffer.from(blob).toString('utf-8'), { ...options, fromSource: true })\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation {\n return new Worker(source, { ...options, fromSource: true }) as any\n }\n }\n\n return {\n blob: BlobWorker as any,\n default: Worker as any,\n }\n}\n\nlet implementation: ImplementationExport\nlet isTinyWorker: boolean\n\nfunction selectWorkerImplementation(): ImplementationExport {\n try {\n isTinyWorker = false\n return initWorkerThreadsWorker()\n } catch (ex) {\n console.error(ex)\n // tslint:disable-next-line no-console\n console.debug('Node worker_threads not available. Trying to fall back to tiny-worker polyfill...')\n isTinyWorker = true\n return initTinyWorker()\n }\n}\n\nexport function getWorkerImplementation(): ImplementationExport {\n if (!implementation) {\n implementation = selectWorkerImplementation()\n }\n return implementation\n}\n\nexport function isWorkerRuntime() {\n if (isTinyWorker) {\n return globalThis !== undefined && self['postMessage'] ? true : false\n } else {\n // Webpack hack\n const isMainThread\n = typeof __non_webpack_require__ === 'function'\n ? __non_webpack_require__('worker_threads').isMainThread\n : eval('require')('worker_threads').isMainThread\n return !isMainThread\n }\n}\n","/* eslint-disable import-x/export */\n/* eslint-disable unicorn/no-thenable */\n\n/* eslint-disable @typescript-eslint/member-ordering */\n/* eslint-disable unicorn/no-array-reduce */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-namespace */\n\n/// <reference lib=\"esnext\" />\n\nimport DebugLogger from 'debug'\nimport {\n multicast, Observable, Subject,\n} from 'observable-fns'\n\nimport { defaultPoolSize } from './implementation.browser.ts'\nimport type {\n PoolEvent, QueuedTask, TaskRunFunction, WorkerDescriptor,\n} from './pool-types.ts'\nimport { PoolEventType } from './pool-types.ts'\nimport { Thread } from './thread.ts'\n\nexport declare namespace Pool {\n type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType>\n type EventType = PoolEventType\n}\n\nlet nextPoolID = 1\n\nfunction createArray(size: number): number[] {\n const array: number[] = []\n for (let index = 0; index < size; index++) {\n array.push(index)\n }\n return array\n}\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction flatMap<In, Out>(array: In[], mapper: (element: In) => Out[]): Out[] {\n return array.reduce<Out[]>((flattened, element) => [...flattened, ...mapper(element)], [])\n}\n\nfunction slugify(text: string) {\n return text.replaceAll(/\\W/g, ' ').trim().replaceAll(/\\s+/g, '-')\n}\n\nfunction spawnWorkers<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, count: number): Array<WorkerDescriptor<ThreadType>> {\n return createArray(count).map(\n (): WorkerDescriptor<ThreadType> => ({\n init: spawnWorker(),\n runningTasks: [],\n }),\n )\n}\n\n/**\n * Thread pool managing a set of worker threads.\n * Use it to queue tasks that are run on those threads with limited\n * concurrency.\n */\nexport interface Pool<ThreadType extends Thread> {\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Promise will be rejected if any task fails.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n completed(allowResolvingImmediately?: boolean): Promise<any>\n\n /**\n * Returns a promise that resolves once the task queue is emptied.\n * Failing tasks will not cause the promise to be rejected.\n *\n * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty.\n */\n settled(allowResolvingImmediately?: boolean): Promise<Error[]>\n\n /**\n * Returns an observable that yields pool events.\n */\n events(): Observable<PoolEvent<ThreadType>>\n\n /**\n * Queue a task and return a promise that resolves once the task has been dequeued,\n * started and finished.\n *\n * @param task An async function that takes a thread instance and invokes it.\n */\n queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return>\n\n /**\n * Terminate all pool threads.\n *\n * @param force Set to `true` to kill the thread even if it cannot be stopped gracefully.\n */\n terminate(force?: boolean): Promise<void>\n}\n\ninterface PoolOptions {\n /** Maximum no. of tasks to run on one worker thread at a time. Defaults to one. */\n concurrency?: number\n\n /** Maximum no. of jobs to be queued for execution before throwing an error. */\n maxQueuedJobs?: number\n\n /** Gives that pool a name to be used for debug logging, letting you distinguish between log output of different pools. */\n name?: string\n\n /** No. of worker threads to spawn and to be managed by the pool. */\n size?: number\n}\n\nclass WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {\n static EventType = PoolEventType\n\n private readonly debug: DebugLogger.Debugger\n private readonly eventObservable: Observable<PoolEvent<ThreadType>>\n private readonly options: PoolOptions\n private readonly workers: Array<WorkerDescriptor<ThreadType>>\n\n private readonly eventSubject = new Subject<PoolEvent<ThreadType>>()\n private initErrors: Error[] = []\n private isClosing = false\n private nextTaskID = 1\n private taskQueue: Array<QueuedTask<ThreadType, any>> = []\n\n constructor(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n const options: PoolOptions = typeof optionsOrSize === 'number' ? { size: optionsOrSize } : optionsOrSize || {}\n\n const { size = defaultPoolSize } = options\n\n this.debug = DebugLogger(`threads:pool:${slugify(options.name || String(nextPoolID++))}`)\n this.options = options\n this.workers = spawnWorkers(spawnWorker, size)\n\n this.eventObservable = multicast(Observable.from(this.eventSubject))\n\n Promise.all(this.workers.map(worker => worker.init)).then(\n () =>\n this.eventSubject.next({\n size: this.workers.length,\n type: PoolEventType.initialized,\n }),\n (error) => {\n this.debug('Error while initializing pool worker:', error)\n this.eventSubject.error(error)\n this.initErrors.push(error)\n },\n )\n }\n\n private findIdlingWorker(): WorkerDescriptor<ThreadType> | undefined {\n const { concurrency = 1 } = this.options\n return this.workers.find(worker => worker.runningTasks.length < concurrency)\n }\n\n private async runPoolTask(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const workerID = this.workers.indexOf(worker) + 1\n\n this.debug(`Running task #${task.id} on worker #${workerID}...`)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskStart,\n workerID,\n })\n\n try {\n const returnValue = await task.run(await worker.init)\n\n this.debug(`Task #${task.id} completed successfully`)\n this.eventSubject.next({\n returnValue,\n taskID: task.id,\n type: PoolEventType.taskCompleted,\n workerID,\n })\n } catch (ex) {\n const error = ex as Error\n this.debug(`Task #${task.id} failed`)\n this.eventSubject.next({\n error,\n taskID: task.id,\n type: PoolEventType.taskFailed,\n workerID,\n })\n }\n }\n\n private run(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) {\n const runPromise = (async () => {\n const removeTaskFromWorkersRunningTasks = () => {\n worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise)\n }\n\n // Defer task execution by one tick to give handlers time to subscribe\n await delay(0)\n\n try {\n await this.runPoolTask(worker, task)\n } finally {\n removeTaskFromWorkersRunningTasks()\n\n if (!this.isClosing) {\n this.scheduleWork()\n }\n }\n })()\n\n worker.runningTasks.push(runPromise)\n }\n\n private scheduleWork() {\n this.debug('Attempt de-queueing a task in order to run it...')\n\n const availableWorker = this.findIdlingWorker()\n if (!availableWorker) return\n\n const nextTask = this.taskQueue.shift()\n if (!nextTask) {\n this.debug('Task queue is empty')\n this.eventSubject.next({ type: PoolEventType.taskQueueDrained })\n return\n }\n\n this.run(availableWorker, nextTask)\n }\n\n private taskCompletion(taskID: number) {\n return new Promise<any>((resolve, reject) => {\n const eventSubscription = this.events().subscribe((event) => {\n if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n resolve(event.returnValue)\n } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) {\n eventSubscription.unsubscribe()\n reject(event.error)\n } else if (event.type === PoolEventType.terminated) {\n eventSubscription.unsubscribe()\n reject(new Error('Pool has been terminated before task was run.'))\n }\n })\n })\n }\n\n async settled(allowResolvingImmediately: boolean = false): Promise<Error[]> {\n const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks)\n\n const taskFailures: Error[] = []\n\n const failureSubscription = this.eventObservable.subscribe((event) => {\n if (event.type === PoolEventType.taskFailed) {\n taskFailures.push(event.error)\n }\n })\n\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n if (allowResolvingImmediately && this.taskQueue.length === 0) {\n await Promise.allSettled(getCurrentlyRunningTasks())\n return taskFailures\n }\n\n await new Promise<void>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type === PoolEventType.taskQueueDrained) {\n subscription.unsubscribe()\n resolve(void 0)\n }\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n await Promise.allSettled(getCurrentlyRunningTasks())\n failureSubscription.unsubscribe()\n\n return taskFailures\n }\n\n async completed(allowResolvingImmediately: boolean = false) {\n const settlementPromise = this.settled(allowResolvingImmediately)\n\n const earlyExitPromise = new Promise<Error[]>((resolve, reject) => {\n const subscription = this.eventObservable.subscribe({\n error: reject,\n next(event) {\n if (event.type === PoolEventType.taskQueueDrained) {\n subscription.unsubscribe()\n resolve(settlementPromise)\n } else if (event.type === PoolEventType.taskFailed) {\n subscription.unsubscribe()\n reject(event.error)\n }\n }, // make a pool-wide error reject the completed() result promise\n })\n })\n\n const errors = await Promise.race([settlementPromise, earlyExitPromise])\n\n if (errors.length > 0) {\n throw errors[0]\n }\n }\n\n events() {\n return this.eventObservable\n }\n\n queue(taskFunction: TaskRunFunction<ThreadType, any>) {\n const { maxQueuedJobs = Number.POSITIVE_INFINITY } = this.options\n\n if (this.isClosing) {\n throw new Error('Cannot schedule pool tasks after terminate() has been called.')\n }\n if (this.initErrors.length > 0) {\n throw this.initErrors[0]\n }\n\n const taskID = this.nextTaskID++\n const taskCompletion = this.taskCompletion(taskID)\n\n taskCompletion.catch((error) => {\n // Prevent unhandled rejections here as we assume the user will use\n // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors\n this.debug(`Task #${taskID} errored:`, error)\n })\n\n const task: QueuedTask<ThreadType, any> = {\n cancel: () => {\n if (!this.taskQueue.includes(task)) return\n this.taskQueue = this.taskQueue.filter(someTask => someTask !== task)\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskCanceled,\n })\n },\n id: taskID,\n run: taskFunction,\n then: taskCompletion.then.bind(taskCompletion),\n }\n\n if (this.taskQueue.length >= maxQueuedJobs) {\n throw new Error(\n 'Maximum number of pool tasks queued. Refusing to queue another one.\\n'\n + 'This usually happens for one of two reasons: We are either at peak '\n + \"workload right now or some tasks just won't finish, thus blocking the pool.\",\n )\n }\n\n this.debug(`Queueing task #${task.id}...`)\n this.taskQueue.push(task)\n\n this.eventSubject.next({\n taskID: task.id,\n type: PoolEventType.taskQueued,\n })\n\n this.scheduleWork()\n return task\n }\n\n async terminate(force?: boolean) {\n this.isClosing = true\n if (!force) {\n await this.completed(true)\n }\n this.eventSubject.next({\n remainingQueue: [...this.taskQueue],\n type: PoolEventType.terminated,\n })\n this.eventSubject.complete()\n await Promise.all(this.workers.map(async worker => Thread.terminate(await worker.init)))\n }\n}\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nfunction PoolConstructor<ThreadType extends Thread>(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) {\n // The function exists only so we don't need to use `new` to create a pool (we still can, though).\n // If the Pool is a class or not is an implementation detail that should not concern the user.\n return new WorkerPool(spawnWorker, optionsOrSize)\n}\n\n;(PoolConstructor as any).EventType = PoolEventType\n\n/**\n * Thread pool constructor. Creates a new pool and spawns its worker threads.\n */\nexport const Pool = PoolConstructor as typeof PoolConstructor & { EventType: typeof PoolEventType }\n\nexport type { PoolEvent, QueuedTask } from './pool-types.ts'\nexport { PoolEventType } from './pool-types.ts'\nexport { Thread } from './thread.ts'\n","/* eslint-disable @stylistic/max-len */\n/* eslint-disable import-x/no-internal-modules */\n// tslint:disable max-classes-per-file\n\nimport type { ImplementationExport, ThreadsWorkerOptions } from '../types/master.ts'\nimport { getBundleURL } from './get-bundle-url.browser.ts'\n\nexport const defaultPoolSize = typeof navigator !== 'undefined' && navigator.hardwareConcurrency ? navigator.hardwareConcurrency : 4\n\nconst isAbsoluteURL = (value: string) => /^[A-Za-z][\\d+.A-Za-z\\-]*:/.test(value)\n\nfunction createSourceBlobURL(code: string): string {\n const blob = new Blob([code], { type: 'application/javascript' })\n return URL.createObjectURL(blob)\n}\n\nfunction selectWorkerImplementation(): ImplementationExport {\n if (typeof Worker === 'undefined') {\n // Might happen on Safari, for instance\n // The idea is to only fail if the constructor is actually used\n return class NoWebWorker {\n constructor() {\n throw new Error(\n \"No web worker implementation available. You might have tried to spawn a worker within a worker in a browser that doesn't support workers in workers.\",\n )\n }\n } as unknown as ImplementationExport\n }\n\n class WebWorker extends Worker {\n constructor(url: string | URL, options?: ThreadsWorkerOptions) {\n if (typeof url === 'string' && options && options._baseURL) {\n url = new URL(url, options._baseURL)\n } else if (typeof url === 'string' && !isAbsoluteURL(url) && /^file:\\/\\//i.test(getBundleURL())) {\n url = new URL(url, getBundleURL().replace(/\\/[^/]+$/, '/'))\n if (options?.CORSWorkaround ?? true) {\n url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`)\n }\n }\n if (\n typeof url === 'string'\n && isAbsoluteURL(url) // Create source code blob loading JS file via `importScripts()`\n // to circumvent worker CORS restrictions\n && (options?.CORSWorkaround ?? true)\n ) {\n url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`)\n }\n super(url, options)\n }\n }\n\n class BlobWorker extends WebWorker {\n constructor(blob: Blob, options?: ThreadsWorkerOptions) {\n const url = globalThis.URL.createObjectURL(blob)\n super(url, options)\n }\n\n static fromText(source: string, options?: ThreadsWorkerOptions): WebWorker {\n const blob = new globalThis.Blob([source], { type: 'text/javascript' })\n return new BlobWorker(blob, options)\n }\n }\n\n return {\n blob: BlobWorker,\n default: WebWorker,\n }\n}\n\nlet implementation: ImplementationExport\n\nexport function getWorkerImplementation(): ImplementationExport {\n if (!implementation) {\n implementation = selectWorkerImplementation()\n }\n return implementation\n}\n\nexport function isWorkerRuntime() {\n const isWindowContext = typeof globalThis !== 'undefined' && typeof Window !== 'undefined' && globalThis instanceof Window\n return typeof globalThis !== 'undefined' && self['postMessage'] && !isWindowContext ? true : false\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nimport type { Thread } from './thread.ts'\n\n/** Pool event type. Specifies the type of each `PoolEvent`. */\nexport enum PoolEventType {\n initialized = 'initialized',\n taskCanceled = 'taskCanceled',\n taskCompleted = 'taskCompleted',\n taskFailed = 'taskFailed',\n taskQueued = 'taskQueued',\n taskQueueDrained = 'taskQueueDrained',\n taskStart = 'taskStart',\n terminated = 'terminated',\n}\n\nexport type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>\n\n/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */\nexport type PoolEvent<ThreadType extends Thread> =\n | {\n type: PoolEventType.initialized\n size: number\n }\n | {\n type: PoolEventType.taskQueued\n taskID: number\n }\n | {\n type: PoolEventType.taskQueueDrained\n }\n | {\n type: PoolEventType.taskStart\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskCompleted\n returnValue: any\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskFailed\n error: Error\n taskID: number\n workerID: number\n }\n | {\n type: PoolEventType.taskCanceled\n taskID: number\n }\n | {\n type: PoolEventType.terminated\n remainingQueue: Array<QueuedTask<ThreadType, any>>\n }\n\nexport interface WorkerDescriptor<ThreadType extends Thread> {\n init: Promise<ThreadType>\n runningTasks: Array<Promise<any>>\n}\n\n/**\n * Task that has been `pool.queued()`-ed.\n */\nexport interface QueuedTask<ThreadType extends Thread, Return> {\n /** @private */\n id: number\n\n /** @private */\n run: TaskRunFunction<ThreadType, Return>\n\n /**\n * Queued tasks can be cancelled until the pool starts running them on a worker thread.\n */\n cancel(): void\n\n /**\n * `QueuedTask` is thenable, so you can `await` it.\n * Resolves when the task has successfully been executed. Rejects if the task fails.\n */\n then: Promise<Return>['then']\n}\n","export const $errors = Symbol('thread.errors')\nexport const $events = Symbol('thread.events')\nexport const $terminate = Symbol('thread.terminate')\nexport const $transferable = Symbol('thread.transferable')\nexport const $worker = Symbol('thread.worker')\n","/* eslint-disable import-x/no-internal-modules */\nimport type { Observable } from 'observable-fns'\n\nimport {\n $errors, $events, $terminate,\n} from '../symbols.ts'\nimport type { Thread as ThreadType, WorkerEvent } from '../types/master.ts'\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\nexport type Thread = ThreadType\n\n/** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */\nexport const Thread = {\n /** Return an observable that can be used to subscribe to all errors happening in the thread. */\n errors<ThreadT extends ThreadType>(thread: ThreadT): Observable<Error> {\n return thread[$errors] || fail('Error observable not found. Make sure to pass a thread instance as returned by the spawn() promise.')\n },\n /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */\n events<ThreadT extends ThreadType>(thread: ThreadT): Observable<WorkerEvent> {\n return thread[$events] || fail('Events observable not found. Make sure to pass a thread instance as returned by the spawn() promise.')\n },\n /** Terminate a thread. Remember to terminate every thread when you are done using it. */\n terminate<ThreadT extends ThreadType>(thread: ThreadT) {\n return thread[$terminate]()\n },\n}\n","/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-floating-promises */\nimport DebugLogger from 'debug'\nimport { Observable } from 'observable-fns'\n\nimport { deserialize } from '../common.ts'\nimport { createPromiseWithResolver } from '../promise.ts'\nimport {\n $errors, $events, $terminate, $worker,\n} from '../symbols.ts'\nimport type {\n FunctionThread,\n ModuleThread,\n PrivateThreadProps,\n StripAsync,\n Worker as WorkerType,\n WorkerEvent,\n WorkerInternalErrorEvent,\n WorkerMessageEvent,\n WorkerTerminationEvent,\n} from '../types/master.ts'\nimport { WorkerEventType } from '../types/master.ts'\nimport type { WorkerInitMessage, WorkerUncaughtErrorMessage } from '../types/messages.ts'\nimport type { WorkerFunction, WorkerModule } from '../types/worker.ts'\nimport { createProxyFunction, createProxyModule } from './invocation-proxy.ts'\n\ntype ArbitraryWorkerInterface = WorkerFunction & WorkerModule<string> & { somekeythatisneverusedinproductioncode123: 'magicmarker123' }\ntype ArbitraryThreadType = FunctionThread<any, any> & ModuleThread<any>\n\nexport type ExposedToThreadType<Exposed extends WorkerFunction | WorkerModule<any>> =\n Exposed extends ArbitraryWorkerInterface ? ArbitraryThreadType\n : Exposed extends WorkerFunction ? FunctionThread<Parameters<Exposed>, StripAsync<ReturnType<Exposed>>>\n : Exposed extends WorkerModule<any> ? ModuleThread<Exposed>\n : never\n\nconst debugMessages = DebugLogger('threads:master:messages')\nconst debugSpawn = DebugLogger('threads:master:spawn')\nconst debugThreadUtils = DebugLogger('threads:master:thread-utils')\n\nconst isInitMessage = (data: any): data is WorkerInitMessage => data && data.type === ('init' as const)\nconst isUncaughtErrorMessage = (data: any): data is WorkerUncaughtErrorMessage => data && data.type === ('uncaughtError' as const)\n\nconst initMessageTimeout\n = typeof process !== 'undefined' && process.env !== undefined && process.env.THREADS_WORKER_INIT_TIMEOUT\n ? Number.parseInt(process.env.THREADS_WORKER_INIT_TIMEOUT, 10)\n : 10_000\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutInMs: number, errorMessage: string): Promise<T> {\n let timeoutHandle: any\n\n const timeout = new Promise<never>((resolve, reject) => {\n timeoutHandle = setTimeout(() => reject(new Error(errorMessage)), timeoutInMs)\n })\n const result = await Promise.race([promise, timeout])\n\n clearTimeout(timeoutHandle)\n return result\n}\n\nfunction receiveInitMessage(worker: WorkerType): Promise<WorkerInitMessage> {\n return new Promise((resolve, reject) => {\n const messageHandler = ((event: MessageEvent) => {\n debugMessages('Message from worker before finishing initialization:', event.data)\n if (isInitMessage(event.data)) {\n worker.removeEventListener('message', messageHandler)\n resolve(event.data)\n } else if (isUncaughtErrorMessage(event.data)) {\n worker.removeEventListener('message', messageHandler)\n reject(deserialize(event.data.error))\n }\n }) as EventListener\n worker.addEventListener('message', messageHandler)\n })\n}\n\nfunction createEventObservable(worker: WorkerType, workerTermination: Promise<any>): Observable<WorkerEvent> {\n return new Observable<WorkerEvent>((observer) => {\n const messageHandler = ((messageEvent: MessageEvent) => {\n const workerEvent: WorkerMessageEvent<any> = {\n data: messageEvent.data,\n type: WorkerEventType.message,\n }\n observer.next(workerEvent)\n }) as EventListener\n const rejectionHandler = ((errorEvent: PromiseRejectionEvent) => {\n debugThreadUtils('Unhandled promise rejection event in thread:', errorEvent)\n const workerEvent: WorkerInternalErrorEvent = {\n error: new Error(errorEvent.reason),\n type: WorkerEventType.internalError,\n }\n observer.next(workerEvent)\n }) as EventListener\n worker.addEventListener('message', messageHandler)\n worker.addEventListener('unhandledrejection', rejectionHandler)\n\n workerTermination.then(() => {\n const terminationEvent: WorkerTerminationEvent = { type: WorkerEventType.termination }\n worker.removeEventListener('message', messageHandler)\n worker.removeEventListener('unhandledrejection', rejectionHandler)\n observer.next(terminationEvent)\n observer.complete()\n })\n })\n}\n\nfunction createTerminator(worker: WorkerType): { terminate: () => Promise<void>; termination: Promise<void> } {\n const [termination, resolver] = createPromiseWithResolver<void>()\n const terminate = async () => {\n debugThreadUtils('Terminating worker')\n // Newer versions of worker_threads workers return a promise\n await worker.terminate()\n resolver()\n }\n return { terminate, termination }\n}\n\nfunction setPrivateThreadProps<T>(\n raw: T,\n worker: WorkerType,\n workerEvents: Observable<WorkerEvent>,\n terminate: () => Promise<void>,\n): T & PrivateThreadProps {\n const workerErrors = workerEvents\n .filter(event => event.type === WorkerEventType.internalError)\n .map(errorEvent => (errorEvent as WorkerInternalErrorEvent).error)\n\n return Object.assign(raw as any, {\n [$errors]: workerErrors,\n [$events]: workerEvents,\n [$terminate]: terminate,\n [$worker]: worker,\n })\n}\n\n/**\n * Spawn a new thread. Takes a fresh worker instance, wraps it in a thin\n * abstraction layer to provide the transparent API and verifies that\n * the worker has initialized successfully.\n *\n * @param worker Instance of `Worker`. Either a web worker, `worker_threads` worker or `tiny-worker` worker.\n * @param [options]\n * @param [options.timeout] Init message timeout. Default: 10000 or set by environment variable.\n */\nexport async function spawn<Exposed extends WorkerFunction | WorkerModule<any> = ArbitraryWorkerInterface>(\n worker: WorkerType,\n options?: { timeout?: number },\n): Promise<ExposedToThreadType<Exposed>> {\n debugSpawn('Initializing new thread')\n\n const timeout = options && options.timeout ? options.timeout : initMessageTimeout\n const initMessage = await withTimeout(\n receiveInitMessage(worker),\n timeout,\n `Timeout: Did not receive an init message from worker after ${timeout}ms. Make sure the worker calls expose().`,\n )\n const exposed = initMessage.exposed\n\n const { termination, terminate } = createTerminator(worker)\n const events = createEventObservable(worker, termination)\n\n if (exposed.type === 'function') {\n const proxy = createProxyFunction(worker)\n return setPrivateThreadProps(proxy, worker, events, terminate) as ExposedToThreadType<Exposed>\n } else if (exposed.type === 'module') {\n const proxy = createProxyModule(worker, exposed.methods)\n return setPrivateThreadProps(proxy, worker, events, terminate) as ExposedToThreadType<Exposed>\n } else {\n const type = (exposed as WorkerInitMessage['exposed']).type\n throw new Error(`Worker init message states unexpected type of expose(): ${type}`)\n }\n}\n","/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { SerializedError } from './types/messages.ts'\n\nexport interface Serializer<Msg = JsonSerializable, Input = any> {\n deserialize(message: Msg): Input\n serialize(input: Input): Msg\n}\n\nexport interface SerializerImplementation<Msg = JsonSerializable, Input = any> {\n deserialize(message: Msg, defaultDeserialize: (msg: Msg) => Input): Input\n serialize(input: Input, defaultSerialize: (inp: Input) => Msg): Msg\n}\n\nexport function extendSerializer<MessageType, InputType = any>(\n extend: Serializer<MessageType, InputType>,\n implementation: SerializerImplementation<MessageType, InputType>,\n): Serializer<MessageType, InputType> {\n const fallbackDeserializer = extend.deserialize.bind(extend)\n const fallbackSerializer = extend.serialize.bind(extend)\n\n return {\n deserialize(message: MessageType): InputType {\n return implementation.deserialize(message, fallbackDeserializer)\n },\n\n serialize(input: InputType): MessageType {\n return implementation.serialize(input, fallbackSerializer)\n },\n }\n}\n\ntype JsonSerializablePrimitive = string | number | boolean | null\n\ntype JsonSerializableObject = {\n [key: string]: JsonSerializablePrimitive | JsonSerializablePrimitive[] | JsonSerializableObject | JsonSerializableObject[] | undefined\n}\n\nexport type JsonSerializable = JsonSerializablePrimitive | JsonSerializablePrimitive[] | JsonSerializableObject | JsonSerializableObject[]\n\nconst DefaultErrorSerializer: Serializer<SerializedError, Error> = {\n deserialize(message: SerializedError): Error {\n return Object.assign(new Error(message.message), {\n name: message.name,\n stack: message.stack,\n })\n },\n serialize(error: Error): SerializedError {\n return {\n __error_marker: '$$error',\n message: error.message,\n name: error.name,\n stack: error.stack,\n }\n },\n}\n\nconst isSerializedError = (thing: any): thing is SerializedError =>\n thing && typeof thing === 'object' && '__error_marker' in thing && thing.__error_marker === '$$error'\n\nexport const DefaultSerializer: Serializer<JsonSerializable> = {\n deserialize(message: JsonSerializable): any {\n return isSerializedError(message) ? DefaultErrorSerializer.deserialize(message) : message\n },\n serialize(input: any): JsonSerializable {\n return input instanceof Error ? (DefaultErrorSerializer.serialize(input) as any as JsonSerializable) : input\n },\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n JsonSerializable, Serializer, SerializerImplementation,\n} from './serializers.ts'\nimport { DefaultSerializer, extendSerializer } from './serializers.ts'\n\ndeclare global {\n var registeredSerializer: Serializer<JsonSerializable>\n}\n\nglobalThis.registeredSerializer = globalThis.registeredSerializer ?? DefaultSerializer\n\nexport function registerSerializer(serializer: SerializerImplementation<JsonSerializable>) {\n globalThis.registeredSerializer = extendSerializer(globalThis.registeredSerializer, serializer)\n}\n\nexport function deserialize(message: JsonSerializable): any {\n return globalThis.registeredSerializer.deserialize(message)\n}\n\nexport function serialize(input: any): JsonSerializable {\n return globalThis.registeredSerializer.serialize(input)\n}\n","// eslint-disable-next-line unicorn/no-useless-undefined\nconst doNothing = () => undefined\n\n/**\n * Creates a new promise and exposes its resolver function.\n * Use with care!\n */\nexport function createPromiseWithResolver<T>(): [Promise<T>, (result: T) => void] {\n let alreadyResolved = false\n let resolvedTo: T\n let resolver: (value: T | PromiseLike<T>) => void = doNothing\n\n const promise = new Promise<T>((resolve) => {\n if (alreadyResolved) {\n resolve(resolvedTo)\n } else {\n resolver = resolve\n }\n })\n const exposedResolver = (value: T) => {\n alreadyResolved = true\n resolvedTo = value\n resolver(resolvedTo)\n }\n return [promise, exposedResolver]\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/// <reference lib=\"dom\" />\n// tslint:disable max-classes-per-file\n\n// Cannot use `compilerOptions.esModuleInterop` and default import syntax\n// See <https://github.com/microsoft/TypeScript/issues/28009>\nimport type { Observable } from 'observable-fns'\n\nimport type { ObservablePromise } from '../observable-promise.ts'\nimport type {\n $errors, $events, $terminate, $worker,\n} from '../symbols.ts'\nimport type { TransferDescriptor } from '../transferable.ts'\n\ninterface ObservableLikeSubscription {\n unsubscribe(): any\n}\ninterface ObservableLike<T> {\n subscribe(onNext: (value: T) => any, onError?: (error: any) => any, onComplete?: () => any): ObservableLikeSubscription\n subscribe(listeners: { complete?(): any; error?(error: any): any; next?(value: T): any }): ObservableLikeSubscription\n}\n\nexport type StripAsync<Type> =\n Type extends Promise<infer PromiseBaseType> ? PromiseBaseType\n : Type extends ObservableLike<infer ObservableBaseType> ? ObservableBaseType\n : Type\n\ntype StripTransfer<Type> = Type extends TransferDescriptor<infer BaseType> ? BaseType : Type\n\nexport type ModuleMethods = { [methodName: string]: (...args: any) => any }\n\ntype ProxyableArgs<Args extends any[]> =\n Args extends [arg0: infer Arg0, ...rest: infer RestArgs] ? [Arg0 extends Transferable ? Arg0 | TransferDescriptor<Arg0> : Arg0, ...RestArgs] : Args\n\nexport type ProxyableFunction<Args extends any[], ReturnType> =\n Args extends [] ? () => ObservablePromise<StripTransfer<StripAsync<ReturnType>>>\n : (...args: ProxyableArgs<Args>) => ObservablePromise<StripTransfer<StripAsync<ReturnType>>>\n\nexport type ModuleProxy<Methods extends ModuleMethods> = {\n [method in keyof Methods]: ProxyableFunction<Parameters<Methods[method]>, ReturnType<Methods[method]>>\n}\n\nexport interface PrivateThreadProps {\n [$errors]: Observable<Error>\n [$events]: Observable<WorkerEvent>\n [$terminate]: () => Promise<void>\n [$worker]: Worker\n}\n\nexport type FunctionThread<Args extends any[] = any[], ReturnType = any> = ProxyableFunction<Args, ReturnType> & PrivateThreadProps\nexport type ModuleThread<Methods extends ModuleMethods = any> = ModuleProxy<Methods> & PrivateThreadProps\n\n// We have those extra interfaces to keep the general non-specific `Thread` type\n// as an interface, so it's displayed concisely in any TypeScript compiler output.\ninterface AnyFunctionThread extends PrivateThreadProps {\n (...args: any[]): ObservablePromise<any>\n}\n\n// tslint:disable-next-line no-empty-interface\ninterface AnyModuleThread extends PrivateThreadProps {\n // Not specifying an index signature here as that would make `ModuleThread` incompatible\n}\n\n/** Worker thread. Either a `FunctionThread` or a `ModuleThread`. */\nexport type Thread = AnyFunctionThread | AnyModuleThread\n\nexport type TransferList = Transferable[]\n\n/** Worker instance. Either a web worker or a node.js Worker provided by `worker_threads` or `tiny-worker`. */\nexport interface Worker extends EventTarget {\n postMessage(value: any, transferList?: TransferList): void\n /** In nodejs 10+ return type is Promise while with tiny-worker and in browser return type is void */\n terminate(callback?: (error?: Error, exitCode?: number) => void): void | Promise<number>\n}\nexport interface ThreadsWorkerOptions extends WorkerOptions {\n /** Whether to apply CORS protection workaround. Defaults to true. */\n CORSWorkaround?: boolean\n /** Prefix for the path passed to the Worker constructor. Web worker only. */\n _baseURL?: string\n /** Resource limits passed on to Node worker_threads */\n resourceLimits?: {\n /** The size of a pre-allocated memory range used for generated code. */\n codeRangeSizeMb?: number\n /** The maximum size of the main heap in MB. */\n maxOldGenerationSizeMb?: number\n /** The maximum size of a heap space for recently created objects. */\n maxYoungGenerationSizeMb?: number\n }\n /** Data passed on to node.js worker_threads. */\n workerData?: any\n}\n\n/** Worker implementation. Either web worker or a node.js Worker class. */\nexport declare class WorkerImplementation extends EventTarget implements Worker {\n constructor(path: string, options?: ThreadsWorkerOptions)\n postMessage(value: any, transferList?: TransferList): void\n terminate(): void | Promise<number>\n}\n\n/** Class to spawn workers from a blob or source string. */\nexport declare class BlobWorker extends WorkerImplementation {\n constructor(blob: Blob, options?: ThreadsWorkerOptions)\n static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation\n}\n\nexport interface ImplementationExport {\n blob: typeof BlobWorker\n default: typeof WorkerImplementation\n}\n\n/** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */\nexport enum WorkerEventType {\n internalError = 'internalError',\n message = 'message',\n termination = 'termination',\n}\n\nexport interface WorkerInternalErrorEvent {\n error: Error\n type: WorkerEventType.internalError\n}\n\nexport interface WorkerMessageEvent<Data> {\n data: Data\n type: WorkerEventType.message\n}\n\nexport interface WorkerTerminationEvent {\n type: WorkerEventType.termination\n}\n\nexport type WorkerEvent = WorkerInternalErrorEvent | WorkerMessageEvent<any> | WorkerTerminationEvent\n","/// <reference lib=\"webworker\" />\n\n/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/*\n * This source file contains the code for proxying calls in the master thread to calls in the workers\n * by `.postMessage()`-ing.\n *\n * Keep in mind that this code can make or break the program's performance! Need to optimize more…\n */\n\nimport DebugLogger from 'debug'\nimport { multicast, Observable } from 'observable-fns'\n\nimport { deserialize, serialize } from '../common.ts'\nimport { ObservablePromise } from '../observable-promise.ts'\nimport { isTransferDescriptor } from '../transferable.ts'\nimport type {\n ModuleMethods, ModuleProxy, ProxyableFunction, Worker as WorkerType,\n} from '../types/master.ts'\nimport type {\n MasterJobCancelMessage,\n MasterJobRunMessage,\n WorkerJobErrorMessage,\n WorkerJobResultMessage,\n WorkerJobStartMessage,\n} from '../types/messages.