@ariestools/threads 8.2.0 → 8.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/browser/index-browser.mjs +75 -35
- package/dist/browser/index-browser.mjs.map +4 -4
- package/dist/browser/master/index-browser.mjs +75 -35
- package/dist/browser/master/index-browser.mjs.map +4 -4
- package/dist/browser/master/pool-browser.d.ts +10 -1
- package/dist/browser/master/pool-browser.d.ts.map +1 -1
- package/dist/browser/master/pool-browser.mjs +34 -26
- package/dist/browser/master/pool-browser.mjs.map +3 -3
- package/dist/browser/master/pool-node.d.ts +10 -1
- package/dist/browser/master/pool-node.d.ts.map +1 -1
- package/dist/browser/master/pool-types.d.ts +21 -26
- package/dist/browser/master/pool-types.d.ts.map +1 -1
- package/dist/browser/types/master.d.ts +11 -11
- package/dist/browser/types/master.d.ts.map +1 -1
- package/dist/browser/types/messages.d.ts +23 -25
- package/dist/browser/types/messages.d.ts.map +1 -1
- package/dist/browser/worker/worker.browser.mjs +29 -8
- package/dist/browser/worker/worker.browser.mjs.map +3 -3
- package/dist/neutral/master/pool-browser.d.ts +10 -1
- package/dist/neutral/master/pool-browser.d.ts.map +1 -1
- package/dist/neutral/master/pool-node.d.ts +10 -1
- package/dist/neutral/master/pool-node.d.ts.map +1 -1
- package/dist/neutral/master/pool-types.d.ts +21 -26
- package/dist/neutral/master/pool-types.d.ts.map +1 -1
- package/dist/neutral/master/spawn.mjs +41 -9
- package/dist/neutral/master/spawn.mjs.map +4 -4
- package/dist/neutral/types/master.d.ts +11 -11
- package/dist/neutral/types/master.d.ts.map +1 -1
- package/dist/neutral/types/messages.d.ts +23 -25
- package/dist/neutral/types/messages.d.ts.map +1 -1
- package/dist/neutral/types/messages.mjs +19 -13
- package/dist/neutral/types/messages.mjs.map +3 -3
- package/dist/node/index-node.mjs +75 -35
- package/dist/node/index-node.mjs.map +4 -4
- package/dist/node/master/index-node.mjs +75 -35
- package/dist/node/master/index-node.mjs.map +4 -4
- package/dist/node/master/pool-browser.d.ts +10 -1
- package/dist/node/master/pool-browser.d.ts.map +1 -1
- package/dist/node/master/pool-node.d.ts +10 -1
- package/dist/node/master/pool-node.d.ts.map +1 -1
- package/dist/node/master/pool-node.mjs +34 -26
- package/dist/node/master/pool-node.mjs.map +3 -3
- package/dist/node/master/pool-types.d.ts +21 -26
- package/dist/node/master/pool-types.d.ts.map +1 -1
- package/dist/node/types/master.d.ts +11 -11
- package/dist/node/types/master.d.ts.map +1 -1
- package/dist/node/types/messages.d.ts +23 -25
- package/dist/node/types/messages.d.ts.map +1 -1
- package/dist/node/worker/worker.node.mjs +29 -8
- package/dist/node/worker/worker.node.mjs.map +3 -3
- package/package.json +8 -8
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/serializers.ts", "../../../src/common.ts", "../../../src/isObservable.ts", "../../../src/symbols.ts", "../../../src/transferable.ts", "../../../src/worker/expose.ts", "../../../src/worker/worker.browser.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { SerializedError } from './types/messages.ts'\n\n/** A serializer that can convert between a message format and an input type. */\nexport interface Serializer<Msg = JsonSerializable, Input = any> {\n /** Restore an input value from its message representation. */\n deserialize(message: Msg): Input\n /** Convert an input value to its message representation. */\n serialize(input: Input): Msg\n}\n\n/** A serializer implementation that receives a fallback (default) serializer for chaining. */\nexport interface SerializerImplementation<Msg = JsonSerializable, Input = any> {\n /** Restore a value, delegating unsupported messages to the fallback. */\n deserialize(message: Msg, defaultDeserialize: (msg: Msg) => Input): Input\n /** Serialize a value, delegating unsupported inputs to the fallback. */\n serialize(input: Input, defaultSerialize: (inp: Input) => Msg): Msg\n}\n\n/**\n * Extend a base serializer with an additional serializer implementation, creating a chain.\n * @param extend - The base serializer to extend.\n * @param implementation - The new serializer implementation that wraps the base.\n * @returns A new serializer combining both behaviors.\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 => implementation.deserialize(message, fallbackDeserializer),\n\n serialize: (input: InputType): MessageType => implementation.serialize(input, fallbackSerializer),\n }\n}\n\ntype JsonSerializablePrimitive = string | number | boolean | null\n\ntype JsonSerializableObject = {\n [key: string]: JsonSerializablePrimitive | JsonSerializablePrimitive[] | JsonSerializableObject | JsonSerializableObject[] | undefined\n}\n\n/** A JSON-compatible value that can be serialized for worker message passing. */\nexport type JsonSerializable = JsonSerializablePrimitive | JsonSerializablePrimitive[] | JsonSerializableObject | JsonSerializableObject[]\n\nconst DefaultErrorSerializer: Serializer<SerializedError, Error> = {\n deserialize: (message: SerializedError): Error => {\n const error = Object.create(Error.prototype) as Error\n error.message = message.message\n error.name = message.name\n error.stack = message.stack\n return error\n },\n serialize: (error: Error): SerializedError => ({\n __error_marker: '$$error',\n message: error.message,\n name: error.name,\n stack: error.stack,\n }),\n}\n\nconst isSerializedError = (thing: any): thing is SerializedError =>\n thing != null && typeof thing === 'object' && '__error_marker' in thing && thing.__error_marker === '$$error'\n\n/** Default serializer that handles Error instances and passes other values through. */\nexport const DefaultSerializer: Serializer<JsonSerializable> = {\n deserialize: (message: JsonSerializable): any => isSerializedError(message) ? DefaultErrorSerializer.deserialize(message) : message,\n serialize: (input: any): JsonSerializable => input instanceof Error ? (DefaultErrorSerializer.serialize(input) as any as JsonSerializable) : input,\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\n/**\n * Register a custom serializer to extend the default serialization behavior for worker messages.\n * @param serializer - The serializer implementation to register.\n */\n/** Register a custom serializer to extend the default serialization behavior for worker messages.\n * @param serializer - The serializer implementation to register.\n */\nexport function registerSerializer(serializer: SerializerImplementation<JsonSerializable>) {\n globalThis.registeredSerializer = extendSerializer(globalThis.registeredSerializer, serializer)\n}\n\n/**\n * Deserialize a message using the registered serializer.\n * @param message - The serialized message to deserialize.\n * @returns The deserialized value.\n */\nexport function deserialize(message: JsonSerializable): unknown {\n return globalThis.registeredSerializer.deserialize(message)\n}\n\n/**\n * Serialize an input value using the registered serializer.\n * @param input - The value to serialize.\n * @returns The serialized message.\n */\n/** Serialize an input value using the registered serializer.\n * @param input - The value to serialize.\n * @returns The serialized message.\n */\nexport function serialize(input: any): JsonSerializable {\n return globalThis.registeredSerializer.serialize(input)\n}\n", "// eslint-disable-next-line @typescript-eslint/no-explicit-any\n/** Determine whether a value implements one of the supported observable protocols. */\nexport const isSomeObservable = (value: any): boolean => {\n if (value == null) {\n return false\n }\n\n if (typeof Symbol.observable === 'symbol' && typeof value[Symbol.observable] === 'function') {\n return value === value[Symbol.observable]()\n }\n\n if (typeof value['@@observable'] === 'function') {\n return value === value['@@observable']()\n }\n\n return false\n}\n", "/** Symbol key for accessing a thread's error observable. */\nexport const $errors = Symbol('thread.errors')\n/** Symbol key for accessing a thread's event observable. */\nexport const $events = Symbol('thread.events')\n/** Symbol key for accessing a thread's terminate function. */\nexport const $terminate = Symbol('thread.terminate')\n/** Symbol key for marking an object as a transferable descriptor. */\nexport const $transferable = Symbol('thread.transferable')\n/** Symbol key for accessing the underlying worker instance of a thread. */\nexport const $worker = Symbol('thread.worker')\n", "/// <reference lib=\"webworker\" />\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { $transferable } from './symbols.ts'\n\n/** Descriptor wrapping a value with its associated transferable objects for zero-copy messaging. */\nexport interface TransferDescriptor<T = any> {\n /** Marker identifying the object as a transfer descriptor. */\n [$transferable]: true\n /** Payload sent to the receiving thread. */\n send: T\n /** Objects whose ownership is transferred with the payload. */\n transferables: Transferable[]\n}\n\nfunction isTransferable(thing: any): thing is Transferable {\n if (thing == null || typeof thing !== 'object') return false\n // Don't check too thoroughly, since the list of transferable things in JS might grow over time\n return true\n}\n\n/**\n * Check whether a value is a `TransferDescriptor` created by `Transfer()`.\n * @param thing - The value to check.\n * @returns True if the value is a transfer descriptor.\n */\nexport function isTransferDescriptor(thing: any): thing is TransferDescriptor {\n return thing != null && typeof thing === 'object' && Reflect.get(thing, $transferable) === true\n}\n\n/**\n * Mark a transferable object as such, so it will no be serialized and\n * deserialized on messaging with the main thread, but to transfer\n * ownership of it to the receiving thread.\n *\n * Only works with array buffers, message ports and few more special\n * types of objects, but it's much faster than serializing and\n * deserializing them.\n *\n * Note:\n * The transferable object cannot be accessed by this thread again\n * unless the receiving thread transfers it back again!\n *\n * @see <https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast>\n */\nexport function Transfer(transferable: Transferable): TransferDescriptor\n\n/**\n * Mark transferable objects within an arbitrary object or array as\n * being a transferable object. They will then not be serialized\n * and deserialized on messaging with the main thread, but ownership\n * of them will be tranferred to the receiving thread.\n *\n * Only array buffers, message ports and few more special types of\n * objects can be transferred, but it's much faster than serializing and\n * deserializing them.\n *\n * Note:\n * The transferable object cannot be accessed by this thread again\n * unless the receiving thread transfers it back again!\n *\n * @param payload Value sent to the receiving thread.\n * @param transferables Array buffers, message ports, or similar objects transferred with the payload.\n * @see <https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast>\n */\nexport function Transfer<T>(payload: T, transferables: Transferable[]): TransferDescriptor\n\n/** Create a transfer descriptor for a payload and its transferable objects. */\nexport function Transfer<T>(payload: T, transferables?: Transferable[]): TransferDescriptor {\n console.log('Transfer')\n if (!transferables) {\n if (!isTransferable(payload)) throw new Error('Not transferable')\n transferables = [payload]\n }\n\n const descriptor = {\n send: payload,\n transferables,\n } as TransferDescriptor\n\n Object.defineProperty(descriptor, $transferable, { value: true })\n return descriptor\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-floating-promises */\n\nimport type { Observable, Subscription } from 'observable-fns'\n\nimport { deserialize, serialize } from '../common.ts'\nimport { isSomeObservable } from '../isObservable.ts'\nimport type { TransferDescriptor } from '../transferable.ts'\nimport { isTransferDescriptor } from '../transferable.ts'\nimport type {\n MasterJobCancelMessage,\n MasterJobRunMessage,\n SerializedError,\n WorkerInitMessage,\n WorkerJobErrorMessage,\n WorkerJobResultMessage,\n WorkerJobStartMessage,\n WorkerUncaughtErrorMessage,\n} from '../types/messages.ts'\nimport {\n MasterMessageType,\n WorkerMessageType,\n} from '../types/messages.ts'\nimport type {\n AbstractedWorkerAPI, WorkerFunction, WorkerModule,\n} from '../types/worker.ts'\nimport type { WorkerGlobalScope } from './WorkerGlobalScope.ts'\n\nconst isErrorEvent = (value: Event): value is ErrorEvent => value !== undefined && (value as ErrorEvent).error !== undefined\n\ninterface ProcessGlobal {\n process?: ProcessLike\n}\n\ninterface ProcessLike {\n on(eventName: 'uncaughtException', listener: (error: Error) => void): unknown\n on(eventName: 'unhandledRejection', listener: (error: unknown) => void): unknown\n}\n\n/**\n * Create an `expose()` function bound to a specific worker API implementation and global scope.\n * @param implementation - The abstracted worker API for communicating with the master thread.\n * @param self - The worker's global scope for subscribing to error events.\n * @returns The `expose()` function that workers call to register their API.\n */\nexport function createExpose(implementation: AbstractedWorkerAPI, self: WorkerGlobalScope) {\n let exposeCalled = false\n\n const activeSubscriptions = new Map<number, Subscription<any>>()\n\n const isMasterJobCancelMessage = (thing: any): thing is MasterJobCancelMessage => thing?.type === MasterMessageType.cancel\n const isMasterJobRunMessage = (thing: any): thing is MasterJobRunMessage => thing?.type === MasterMessageType.run\n\n /**\n * There are issues with `is-observable` not recognizing zen-observable's instances.\n * We are using `observable-fns`, but it's based on zen-observable, too.\n */\n const isObservable = (thing: any): thing is Observable<any> => isSomeObservable(thing) || isZenObservable(thing)\n\n function isZenObservable(thing: any): thing is Observable<any> {\n return thing != null && typeof thing === 'object' && typeof thing.subscribe === 'function'\n }\n\n function deconstructTransfer(thing: any) {\n return isTransferDescriptor(thing) ? { payload: thing.send, transferables: thing.transferables } : { payload: thing, transferables: undefined }\n }\n\n function postFunctionInitMessage() {\n const initMessage: WorkerInitMessage = {\n exposed: { type: 'function' },\n type: WorkerMessageType.init,\n }\n implementation.postMessageToMaster(initMessage)\n }\n\n function postModuleInitMessage(methodNames: string[]) {\n const initMessage: WorkerInitMessage = {\n exposed: {\n methods: methodNames,\n type: 'module',\n },\n type: WorkerMessageType.init,\n }\n implementation.postMessageToMaster(initMessage)\n }\n\n function postJobErrorMessage(uid: number, rawError: Error | TransferDescriptor<Error>) {\n const { payload: error, transferables } = deconstructTransfer(rawError)\n const errorMessage: WorkerJobErrorMessage = {\n error: serialize(error) as any as SerializedError,\n type: WorkerMessageType.error,\n uid,\n }\n implementation.postMessageToMaster(errorMessage, transferables)\n }\n\n function postJobResultMessage(uid: number, completed: boolean, resultValue?: any) {\n const { payload, transferables } = deconstructTransfer(resultValue)\n const resultMessage: WorkerJobResultMessage = {\n complete: completed ? true : undefined,\n payload,\n type: WorkerMessageType.result,\n uid,\n }\n implementation.postMessageToMaster(resultMessage, transferables)\n }\n\n function postJobStartMessage(uid: number, resultType: WorkerJobStartMessage['resultType']) {\n const startMessage: WorkerJobStartMessage = {\n resultType,\n type: WorkerMessageType.running,\n uid,\n }\n implementation.postMessageToMaster(startMessage)\n }\n\n function postUncaughtErrorMessage(error: Error) {\n try {\n const errorMessage: WorkerUncaughtErrorMessage = {\n error: serialize(error) as any as SerializedError,\n type: WorkerMessageType.uncaughtError,\n }\n implementation.postMessageToMaster(errorMessage)\n } catch (subError) {\n console.error(\n 'Not reporting uncaught error back to master thread as it occured while reporting an uncaught error already.\\nLatest error:',\n subError,\n '\\nOriginal error:',\n error,\n )\n }\n }\n\n async function runFunction(jobUID: number, fn: WorkerFunction, args: any[]) {\n let syncResult: any\n\n try {\n syncResult = fn(...args)\n } catch (ex) {\n const error = ex as Error\n return postJobErrorMessage(jobUID, error)\n }\n\n const resultType = isObservable(syncResult) ? 'observable' : 'promise'\n postJobStartMessage(jobUID, resultType)\n\n if (isObservable(syncResult)) {\n const subscription = syncResult.subscribe(\n value => postJobResultMessage(jobUID, false, serialize(value)),\n (error) => {\n postJobErrorMessage(jobUID, serialize(error) as any)\n activeSubscriptions.delete(jobUID)\n },\n () => {\n postJobResultMessage(jobUID, true)\n activeSubscriptions.delete(jobUID)\n },\n )\n activeSubscriptions.set(jobUID, subscription)\n } else {\n try {\n const result = await syncResult\n postJobResultMessage(jobUID, true, serialize(result))\n } catch (error) {\n postJobErrorMessage(jobUID, serialize(error) as any)\n }\n }\n }\n\n /**\n * Expose a function or a module (an object whose values are functions)\n * to the main thread. Must be called exactly once in every worker thread\n * to signal its API to the main thread.\n *\n * @param exposed Function or object whose values are functions\n */\n const expose = (exposed: WorkerFunction | WorkerModule<any>) => {\n if (!implementation.isWorkerRuntime()) {\n throw new Error('expose() called in the master thread.')\n }\n if (exposeCalled) {\n throw new Error('expose() called more than once. This is not possible. Pass an object to expose() if you want to expose multiple functions.')\n }\n exposeCalled = true\n\n if (typeof exposed === 'function') {\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (isMasterJobRunMessage(messageData) && messageData.method === undefined) {\n runFunction(messageData.uid, exposed, messageData.args.map(deserialize))\n }\n })\n postFunctionInitMessage()\n } else if (typeof exposed === 'object' && exposed !== null) {\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (isMasterJobRunMessage(messageData) && messageData.method !== undefined) {\n runFunction(messageData.uid, exposed[messageData.method], messageData.args.map(deserialize))\n }\n })\n\n const methodNames = Object.keys(exposed).filter(key => typeof exposed[key] === 'function')\n postModuleInitMessage(methodNames)\n } else {\n throw new Error(`Invalid argument passed to expose(). Expected a function or an object, got: ${exposed}`)\n }\n\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (!isMasterJobCancelMessage(messageData)) {\n return\n }\n\n const jobUID = messageData.uid\n const subscription = activeSubscriptions.get(jobUID)\n\n if (subscription) {\n subscription.unsubscribe()\n activeSubscriptions.delete(jobUID)\n }\n })\n }\n\n const subscribeToBrowserUncaughtErrors = () => {\n if (typeof globalThis === 'undefined' || typeof self.addEventListener !== 'function' || !implementation.isWorkerRuntime()) {\n return\n }\n\n self.addEventListener('error', (event) => {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(isErrorEvent(event) ? event.error : event), 250)\n })\n self.addEventListener('unhandledrejection', (event) => {\n const error = (event as any).reason\n if (error != null && typeof error === 'object' && typeof (error as Error).message === 'string') {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error), 250)\n }\n })\n }\n\n const subscribeToNodeUncaughtErrors = () => {\n const nodeProcess = (globalThis as ProcessGlobal).process\n if (nodeProcess === undefined || typeof nodeProcess.on !== 'function' || !implementation.isWorkerRuntime()) {\n return\n }\n\n nodeProcess.on('uncaughtException', (error) => {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error), 250)\n })\n nodeProcess.on('unhandledRejection', (error) => {\n if (error != null && typeof error === 'object' && typeof (error as Error).message === 'string') {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error as Error), 250)\n }\n })\n }\n\n subscribeToBrowserUncaughtErrors()\n subscribeToNodeUncaughtErrors()\n\n return expose\n}\n", "/// <reference lib=\"dom\" />\n\nimport type { AbstractedWorkerAPI } from '../types/worker.ts'\nimport { createExpose } from './expose.ts'\nimport type { WorkerGlobalScope } from './WorkerGlobalScope.ts'\n\ndeclare const self: WorkerGlobalScope\n\n/** Check if the current code is running inside a browser web worker context. */\nconst isWorkerRuntime: AbstractedWorkerAPI['isWorkerRuntime'] = function isWorkerRuntime() {\n const isWindowContext = self !== undefined && typeof Window !== 'undefined' && self instanceof Window\n return self?.postMessage !== undefined && !isWindowContext\n}\n\n/** Post a message from this worker to the master thread via the global `postMessage`. */\nconst postMessageToMaster: AbstractedWorkerAPI['postMessageToMaster'] = function postMessageToMaster(data, transferList?) {\n self.postMessage(data, transferList)\n}\n\n/** Subscribe to messages from the master thread via the global `addEventListener`. */\nconst subscribeToMasterMessages: AbstractedWorkerAPI['subscribeToMasterMessages'] = function subscribeToMasterMessages(onMessage) {\n const messageHandler = (messageEvent: MessageEvent) => {\n onMessage(messageEvent.data)\n }\n const unsubscribe = () => {\n self.removeEventListener('message', messageHandler as EventListener)\n }\n self.addEventListener('message', messageHandler as EventListener)\n return unsubscribe\n}\n\n/** Bound `addEventListener` from the worker global scope. */\n// eslint-disable-next-line unicorn/no-this-outside-of-class\nconst addEventListener = self.addEventListener.bind(this)\n/** Bound `postMessage` from the worker global scope. */\n// eslint-disable-next-line unicorn/no-this-outside-of-class\nconst postMessage = self.postMessage.bind(this)\n/** Bound `removeEventListener` from the worker global scope. */\n// eslint-disable-next-line unicorn/no-this-outside-of-class\nconst removeEventListener = self.removeEventListener.bind(this)\n\nexport {\n addEventListener,\n postMessage,\n removeEventListener,\n}\n\nconst expose = createExpose({\n isWorkerRuntime, postMessageToMaster, subscribeToMasterMessages,\n}, {\n addEventListener, postMessage, removeEventListener,\n})\n\nexport {\n isWorkerRuntime,\n postMessageToMaster,\n subscribeToMasterMessages,\n}\n\nexport { registerSerializer } from '../common.ts'\nexport { Transfer } from '../transferable.ts'\nexport { expose }\n"],
|
|
5
|
-
"mappings": ";AAyBO,SAAS,iBACd,QACA,gBACoC;AACpC,QAAM,uBAAuB,OAAO,YAAY,KAAK,MAAM;AAC3D,QAAM,qBAAqB,OAAO,UAAU,KAAK,MAAM;AAEvD,SAAO;AAAA,IACL,aAAa,CAAC,YAAoC,eAAe,YAAY,SAAS,oBAAoB;AAAA,IAE1G,WAAW,CAAC,UAAkC,eAAe,UAAU,OAAO,kBAAkB;AAAA,EAClG;AACF;AAWA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ACQzD,SAAS,eAAe,OAAmC;AACzD,MAAI,SAAS,QAAQ,OAAO,UAAU,SAAU,QAAO;AAEvD,SAAO;AACT;AAOO,SAAS,qBAAqB,OAAyC;AAC5E,SAAO,SAAS,QAAQ,OAAO,UAAU,YAAY,QAAQ,IAAI,OAAO,aAAa,MAAM;AAC7F;AAwCO,SAAS,SAAY,SAAY,eAAoD;AAC1F,UAAQ,IAAI,UAAU;AACtB,MAAI,CAAC,eAAe;AAClB,QAAI,CAAC,eAAe,OAAO,EAAG,OAAM,IAAI,MAAM,kBAAkB;AAChE,oBAAgB,CAAC,OAAO;AAAA,EAC1B;AAEA,QAAM,aAAa;AAAA,IACjB,MAAM;AAAA,IACN;AAAA,EACF;AAEA,SAAO,eAAe,YAAY,eAAe,EAAE,OAAO,KAAK,CAAC;AAChE,SAAO;AACT;;;
|
|
3
|
+
"sources": ["../../../src/serializers.ts", "../../../src/common.ts", "../../../src/isObservable.ts", "../../../src/symbols.ts", "../../../src/transferable.ts", "../../../src/types/messages.ts", "../../../src/worker/expose.ts", "../../../src/worker/worker.browser.ts"],
|
|
4
|
+
"sourcesContent": ["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { SerializedError } from './types/messages.ts'\n\n/** A serializer that can convert between a message format and an input type. */\nexport interface Serializer<Msg = JsonSerializable, Input = any> {\n /** Restore an input value from its message representation. */\n deserialize(message: Msg): Input\n /** Convert an input value to its message representation. */\n serialize(input: Input): Msg\n}\n\n/** A serializer implementation that receives a fallback (default) serializer for chaining. */\nexport interface SerializerImplementation<Msg = JsonSerializable, Input = any> {\n /** Restore a value, delegating unsupported messages to the fallback. */\n deserialize(message: Msg, defaultDeserialize: (msg: Msg) => Input): Input\n /** Serialize a value, delegating unsupported inputs to the fallback. */\n serialize(input: Input, defaultSerialize: (inp: Input) => Msg): Msg\n}\n\n/**\n * Extend a base serializer with an additional serializer implementation, creating a chain.\n * @param extend - The base serializer to extend.\n * @param implementation - The new serializer implementation that wraps the base.\n * @returns A new serializer combining both behaviors.\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 => implementation.deserialize(message, fallbackDeserializer),\n\n serialize: (input: InputType): MessageType => implementation.serialize(input, fallbackSerializer),\n }\n}\n\ntype JsonSerializablePrimitive = string | number | boolean | null\n\ntype JsonSerializableObject = {\n [key: string]: JsonSerializablePrimitive | JsonSerializablePrimitive[] | JsonSerializableObject | JsonSerializableObject[] | undefined\n}\n\n/** A JSON-compatible value that can be serialized for worker message passing. */\nexport type JsonSerializable = JsonSerializablePrimitive | JsonSerializablePrimitive[] | JsonSerializableObject | JsonSerializableObject[]\n\nconst DefaultErrorSerializer: Serializer<SerializedError, Error> = {\n deserialize: (message: SerializedError): Error => {\n const error = Object.create(Error.prototype) as Error\n error.message = message.message\n error.name = message.name\n error.stack = message.stack\n return error\n },\n serialize: (error: Error): SerializedError => ({\n __error_marker: '$$error',\n message: error.message,\n name: error.name,\n stack: error.stack,\n }),\n}\n\nconst isSerializedError = (thing: any): thing is SerializedError =>\n thing != null && typeof thing === 'object' && '__error_marker' in thing && thing.__error_marker === '$$error'\n\n/** Default serializer that handles Error instances and passes other values through. */\nexport const DefaultSerializer: Serializer<JsonSerializable> = {\n deserialize: (message: JsonSerializable): any => isSerializedError(message) ? DefaultErrorSerializer.deserialize(message) : message,\n serialize: (input: any): JsonSerializable => input instanceof Error ? (DefaultErrorSerializer.serialize(input) as any as JsonSerializable) : input,\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\n/**\n * Register a custom serializer to extend the default serialization behavior for worker messages.\n * @param serializer - The serializer implementation to register.\n */\n/** Register a custom serializer to extend the default serialization behavior for worker messages.\n * @param serializer - The serializer implementation to register.\n */\nexport function registerSerializer(serializer: SerializerImplementation<JsonSerializable>) {\n globalThis.registeredSerializer = extendSerializer(globalThis.registeredSerializer, serializer)\n}\n\n/**\n * Deserialize a message using the registered serializer.\n * @param message - The serialized message to deserialize.\n * @returns The deserialized value.\n */\nexport function deserialize(message: JsonSerializable): unknown {\n return globalThis.registeredSerializer.deserialize(message)\n}\n\n/**\n * Serialize an input value using the registered serializer.\n * @param input - The value to serialize.\n * @returns The serialized message.\n */\n/** Serialize an input value using the registered serializer.\n * @param input - The value to serialize.\n * @returns The serialized message.\n */\nexport function serialize(input: any): JsonSerializable {\n return globalThis.registeredSerializer.serialize(input)\n}\n", "// eslint-disable-next-line @typescript-eslint/no-explicit-any\n/** Determine whether a value implements one of the supported observable protocols. */\nexport const isSomeObservable = (value: any): boolean => {\n if (value == null) {\n return false\n }\n\n if (typeof Symbol.observable === 'symbol' && typeof value[Symbol.observable] === 'function') {\n return value === value[Symbol.observable]()\n }\n\n if (typeof value['@@observable'] === 'function') {\n return value === value['@@observable']()\n }\n\n return false\n}\n", "/** Symbol key for accessing a thread's error observable. */\nexport const $errors = Symbol('thread.errors')\n/** Symbol key for accessing a thread's event observable. */\nexport const $events = Symbol('thread.events')\n/** Symbol key for accessing a thread's terminate function. */\nexport const $terminate = Symbol('thread.terminate')\n/** Symbol key for marking an object as a transferable descriptor. */\nexport const $transferable = Symbol('thread.transferable')\n/** Symbol key for accessing the underlying worker instance of a thread. */\nexport const $worker = Symbol('thread.worker')\n", "/// <reference lib=\"webworker\" />\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { $transferable } from './symbols.ts'\n\n/** Descriptor wrapping a value with its associated transferable objects for zero-copy messaging. */\nexport interface TransferDescriptor<T = any> {\n /** Marker identifying the object as a transfer descriptor. */\n [$transferable]: true\n /** Payload sent to the receiving thread. */\n send: T\n /** Objects whose ownership is transferred with the payload. */\n transferables: Transferable[]\n}\n\nfunction isTransferable(thing: any): thing is Transferable {\n if (thing == null || typeof thing !== 'object') return false\n // Don't check too thoroughly, since the list of transferable things in JS might grow over time\n return true\n}\n\n/**\n * Check whether a value is a `TransferDescriptor` created by `Transfer()`.\n * @param thing - The value to check.\n * @returns True if the value is a transfer descriptor.\n */\nexport function isTransferDescriptor(thing: any): thing is TransferDescriptor {\n return thing != null && typeof thing === 'object' && Reflect.get(thing, $transferable) === true\n}\n\n/**\n * Mark a transferable object as such, so it will no be serialized and\n * deserialized on messaging with the main thread, but to transfer\n * ownership of it to the receiving thread.\n *\n * Only works with array buffers, message ports and few more special\n * types of objects, but it's much faster than serializing and\n * deserializing them.\n *\n * Note:\n * The transferable object cannot be accessed by this thread again\n * unless the receiving thread transfers it back again!\n *\n * @see <https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast>\n */\nexport function Transfer(transferable: Transferable): TransferDescriptor\n\n/**\n * Mark transferable objects within an arbitrary object or array as\n * being a transferable object. They will then not be serialized\n * and deserialized on messaging with the main thread, but ownership\n * of them will be tranferred to the receiving thread.\n *\n * Only array buffers, message ports and few more special types of\n * objects can be transferred, but it's much faster than serializing and\n * deserializing them.\n *\n * Note:\n * The transferable object cannot be accessed by this thread again\n * unless the receiving thread transfers it back again!\n *\n * @param payload Value sent to the receiving thread.\n * @param transferables Array buffers, message ports, or similar objects transferred with the payload.\n * @see <https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast>\n */\nexport function Transfer<T>(payload: T, transferables: Transferable[]): TransferDescriptor\n\n/** Create a transfer descriptor for a payload and its transferable objects. */\nexport function Transfer<T>(payload: T, transferables?: Transferable[]): TransferDescriptor {\n console.log('Transfer')\n if (!transferables) {\n if (!isTransferable(payload)) throw new Error('Not transferable')\n transferables = [payload]\n }\n\n const descriptor = {\n send: payload,\n transferables,\n } as TransferDescriptor\n\n Object.defineProperty(descriptor, $transferable, { value: true })\n return descriptor\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nimport { Enum, type EnumValue } from '@ariestools/sdk/enum'\n\n/** Serialized representation of an Error for transmission between threads. */\nexport interface SerializedError {\n /** Marker distinguishing serialized errors from ordinary values. */\n __error_marker: '$$error'\n /** Error message. */\n message: string\n /** Error class name. */\n name: string\n /** Captured stack trace, when available. */\n stack?: string\n}\n\n/////////////////////////////\n// Messages sent by master:\n\n/** Types of messages that the master thread can send to a worker. */\nexport const MasterMessageType = Enum({\n /** Cancel a previously submitted job. */\n cancel: 'cancel',\n /** Run a job in the worker. */\n run: 'run',\n} as const)\n/** Types of messages that the master thread can send to a worker. */\nexport type MasterMessageType = EnumValue<typeof MasterMessageType>\n\n/** Message sent by the master to cancel a running job. */\nexport type MasterJobCancelMessage = {\n /** Message discriminant. */\n type: (typeof MasterMessageType)['cancel']\n /** Unique identifier of the job to cancel. */\n uid: number\n}\n\n/** Message sent by the master to run a function in the worker. */\nexport type MasterJobRunMessage = {\n /** Message discriminant. */\n type: (typeof MasterMessageType)['run']\n /** Unique identifier assigned to the job. */\n uid: number\n /** Exposed module method to invoke, or omitted for an exposed function. */\n method?: string\n /** Arguments passed to the exposed function or method. */\n args: any[]\n}\n\n////////////////////////////\n// Messages sent by worker:\n\n/** Types of messages that a worker thread can send to the master. */\nexport const WorkerMessageType = Enum({\n /** A job failed. */\n error: 'error',\n /** The worker exposed its callable API. */\n init: 'init',\n /** A job produced a result. */\n result: 'result',\n /** A job started running. */\n running: 'running',\n /** An error escaped the worker job handler. */\n uncaughtError: 'uncaughtError',\n} as const)\n/** Types of messages that a worker thread can send to the master. */\nexport type WorkerMessageType = EnumValue<typeof WorkerMessageType>\n\n/** Message sent by a worker when an uncaught error occurs. */\nexport type WorkerUncaughtErrorMessage = {\n /** Message discriminant. */\n type: (typeof WorkerMessageType)['uncaughtError']\n /** Uncaught error details. */\n error: {\n message: string\n name: string\n stack?: string\n }\n}\n\n/** Message sent by a worker after calling `expose()` to signal its API to the master. */\nexport type WorkerInitMessage = {\n /** Message discriminant. */\n type: (typeof WorkerMessageType)['init']\n /** Shape of the function or module exposed by the worker. */\n exposed: { type: 'function' } | { type: 'module'; methods: string[] }\n}\n\n/** Message sent by a worker when a job encounters an error. */\nexport type WorkerJobErrorMessage = {\n /** Message discriminant. */\n type: (typeof WorkerMessageType)['error']\n /** Unique identifier of the failed job. */\n uid: number\n /** Serialized failure raised by the job. */\n error: SerializedError\n}\n\n/** Message sent by a worker containing a job's result value. */\nexport type WorkerJobResultMessage = {\n /** Message discriminant. */\n type: (typeof WorkerMessageType)['result']\n /** Unique identifier of the completed or updated job. */\n uid: number\n /** Whether an observable job has finished emitting values. */\n complete?: true\n /** Result value or observable emission. */\n payload?: any\n}\n\n/** Message sent by a worker when a job starts executing. */\nexport type WorkerJobStartMessage = {\n /** Message discriminant. */\n type: (typeof WorkerMessageType)['running']\n /** Unique identifier of the started job. */\n uid: number\n /** Asynchronous result protocol used by the job. */\n resultType: 'observable' | 'promise'\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-floating-promises */\n\nimport type { Observable, Subscription } from 'observable-fns'\n\nimport { deserialize, serialize } from '../common.ts'\nimport { isSomeObservable } from '../isObservable.ts'\nimport type { TransferDescriptor } from '../transferable.ts'\nimport { isTransferDescriptor } from '../transferable.ts'\nimport type {\n MasterJobCancelMessage,\n MasterJobRunMessage,\n SerializedError,\n WorkerInitMessage,\n WorkerJobErrorMessage,\n WorkerJobResultMessage,\n WorkerJobStartMessage,\n WorkerUncaughtErrorMessage,\n} from '../types/messages.ts'\nimport {\n MasterMessageType,\n WorkerMessageType,\n} from '../types/messages.ts'\nimport type {\n AbstractedWorkerAPI, WorkerFunction, WorkerModule,\n} from '../types/worker.ts'\nimport type { WorkerGlobalScope } from './WorkerGlobalScope.ts'\n\nconst isErrorEvent = (value: Event): value is ErrorEvent => value !== undefined && (value as ErrorEvent).error !== undefined\n\ninterface ProcessGlobal {\n process?: ProcessLike\n}\n\ninterface ProcessLike {\n on(eventName: 'uncaughtException', listener: (error: Error) => void): unknown\n on(eventName: 'unhandledRejection', listener: (error: unknown) => void): unknown\n}\n\n/**\n * Create an `expose()` function bound to a specific worker API implementation and global scope.\n * @param implementation - The abstracted worker API for communicating with the master thread.\n * @param self - The worker's global scope for subscribing to error events.\n * @returns The `expose()` function that workers call to register their API.\n */\nexport function createExpose(implementation: AbstractedWorkerAPI, self: WorkerGlobalScope) {\n let exposeCalled = false\n\n const activeSubscriptions = new Map<number, Subscription<any>>()\n\n const isMasterJobCancelMessage = (thing: any): thing is MasterJobCancelMessage => thing?.type === MasterMessageType.cancel\n const isMasterJobRunMessage = (thing: any): thing is MasterJobRunMessage => thing?.type === MasterMessageType.run\n\n /**\n * There are issues with `is-observable` not recognizing zen-observable's instances.\n * We are using `observable-fns`, but it's based on zen-observable, too.\n */\n const isObservable = (thing: any): thing is Observable<any> => isSomeObservable(thing) || isZenObservable(thing)\n\n function isZenObservable(thing: any): thing is Observable<any> {\n return thing != null && typeof thing === 'object' && typeof thing.subscribe === 'function'\n }\n\n function deconstructTransfer(thing: any) {\n return isTransferDescriptor(thing) ? { payload: thing.send, transferables: thing.transferables } : { payload: thing, transferables: undefined }\n }\n\n function postFunctionInitMessage() {\n const initMessage: WorkerInitMessage = {\n exposed: { type: 'function' },\n type: WorkerMessageType.init,\n }\n implementation.postMessageToMaster(initMessage)\n }\n\n function postModuleInitMessage(methodNames: string[]) {\n const initMessage: WorkerInitMessage = {\n exposed: {\n methods: methodNames,\n type: 'module',\n },\n type: WorkerMessageType.init,\n }\n implementation.postMessageToMaster(initMessage)\n }\n\n function postJobErrorMessage(uid: number, rawError: Error | TransferDescriptor<Error>) {\n const { payload: error, transferables } = deconstructTransfer(rawError)\n const errorMessage: WorkerJobErrorMessage = {\n error: serialize(error) as any as SerializedError,\n type: WorkerMessageType.error,\n uid,\n }\n implementation.postMessageToMaster(errorMessage, transferables)\n }\n\n function postJobResultMessage(uid: number, completed: boolean, resultValue?: any) {\n const { payload, transferables } = deconstructTransfer(resultValue)\n const resultMessage: WorkerJobResultMessage = {\n complete: completed ? true : undefined,\n payload,\n type: WorkerMessageType.result,\n uid,\n }\n implementation.postMessageToMaster(resultMessage, transferables)\n }\n\n function postJobStartMessage(uid: number, resultType: WorkerJobStartMessage['resultType']) {\n const startMessage: WorkerJobStartMessage = {\n resultType,\n type: WorkerMessageType.running,\n uid,\n }\n implementation.postMessageToMaster(startMessage)\n }\n\n function postUncaughtErrorMessage(error: Error) {\n try {\n const errorMessage: WorkerUncaughtErrorMessage = {\n error: serialize(error) as any as SerializedError,\n type: WorkerMessageType.uncaughtError,\n }\n implementation.postMessageToMaster(errorMessage)\n } catch (subError) {\n console.error(\n 'Not reporting uncaught error back to master thread as it occured while reporting an uncaught error already.\\nLatest error:',\n subError,\n '\\nOriginal error:',\n error,\n )\n }\n }\n\n async function runFunction(jobUID: number, fn: WorkerFunction, args: any[]) {\n let syncResult: any\n\n try {\n syncResult = fn(...args)\n } catch (ex) {\n const error = ex as Error\n return postJobErrorMessage(jobUID, error)\n }\n\n const resultType = isObservable(syncResult) ? 'observable' : 'promise'\n postJobStartMessage(jobUID, resultType)\n\n if (isObservable(syncResult)) {\n const subscription = syncResult.subscribe(\n value => postJobResultMessage(jobUID, false, serialize(value)),\n (error) => {\n postJobErrorMessage(jobUID, serialize(error) as any)\n activeSubscriptions.delete(jobUID)\n },\n () => {\n postJobResultMessage(jobUID, true)\n activeSubscriptions.delete(jobUID)\n },\n )\n activeSubscriptions.set(jobUID, subscription)\n } else {\n try {\n const result = await syncResult\n postJobResultMessage(jobUID, true, serialize(result))\n } catch (error) {\n postJobErrorMessage(jobUID, serialize(error) as any)\n }\n }\n }\n\n /**\n * Expose a function or a module (an object whose values are functions)\n * to the main thread. Must be called exactly once in every worker thread\n * to signal its API to the main thread.\n *\n * @param exposed Function or object whose values are functions\n */\n const expose = (exposed: WorkerFunction | WorkerModule<any>) => {\n if (!implementation.isWorkerRuntime()) {\n throw new Error('expose() called in the master thread.')\n }\n if (exposeCalled) {\n throw new Error('expose() called more than once. This is not possible. Pass an object to expose() if you want to expose multiple functions.')\n }\n exposeCalled = true\n\n if (typeof exposed === 'function') {\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (isMasterJobRunMessage(messageData) && messageData.method === undefined) {\n runFunction(messageData.uid, exposed, messageData.args.map(deserialize))\n }\n })\n postFunctionInitMessage()\n } else if (typeof exposed === 'object' && exposed !== null) {\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (isMasterJobRunMessage(messageData) && messageData.method !== undefined) {\n runFunction(messageData.uid, exposed[messageData.method], messageData.args.map(deserialize))\n }\n })\n\n const methodNames = Object.keys(exposed).filter(key => typeof exposed[key] === 'function')\n postModuleInitMessage(methodNames)\n } else {\n throw new Error(`Invalid argument passed to expose(). Expected a function or an object, got: ${exposed}`)\n }\n\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (!isMasterJobCancelMessage(messageData)) {\n return\n }\n\n const jobUID = messageData.uid\n const subscription = activeSubscriptions.get(jobUID)\n\n if (subscription) {\n subscription.unsubscribe()\n activeSubscriptions.delete(jobUID)\n }\n })\n }\n\n const subscribeToBrowserUncaughtErrors = () => {\n if (typeof globalThis === 'undefined' || typeof self.addEventListener !== 'function' || !implementation.isWorkerRuntime()) {\n return\n }\n\n self.addEventListener('error', (event) => {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(isErrorEvent(event) ? event.error : event), 250)\n })\n self.addEventListener('unhandledrejection', (event) => {\n const error = (event as any).reason\n if (error != null && typeof error === 'object' && typeof (error as Error).message === 'string') {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error), 250)\n }\n })\n }\n\n const subscribeToNodeUncaughtErrors = () => {\n const nodeProcess = (globalThis as ProcessGlobal).process\n if (nodeProcess === undefined || typeof nodeProcess.on !== 'function' || !implementation.isWorkerRuntime()) {\n return\n }\n\n nodeProcess.on('uncaughtException', (error) => {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error), 250)\n })\n nodeProcess.on('unhandledRejection', (error) => {\n if (error != null && typeof error === 'object' && typeof (error as Error).message === 'string') {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error as Error), 250)\n }\n })\n }\n\n subscribeToBrowserUncaughtErrors()\n subscribeToNodeUncaughtErrors()\n\n return expose\n}\n", "/// <reference lib=\"dom\" />\n\nimport type { AbstractedWorkerAPI } from '../types/worker.ts'\nimport { createExpose } from './expose.ts'\nimport type { WorkerGlobalScope } from './WorkerGlobalScope.ts'\n\ndeclare const self: WorkerGlobalScope\n\n/** Check if the current code is running inside a browser web worker context. */\nconst isWorkerRuntime: AbstractedWorkerAPI['isWorkerRuntime'] = function isWorkerRuntime() {\n const isWindowContext = self !== undefined && typeof Window !== 'undefined' && self instanceof Window\n return self?.postMessage !== undefined && !isWindowContext\n}\n\n/** Post a message from this worker to the master thread via the global `postMessage`. */\nconst postMessageToMaster: AbstractedWorkerAPI['postMessageToMaster'] = function postMessageToMaster(data, transferList?) {\n self.postMessage(data, transferList)\n}\n\n/** Subscribe to messages from the master thread via the global `addEventListener`. */\nconst subscribeToMasterMessages: AbstractedWorkerAPI['subscribeToMasterMessages'] = function subscribeToMasterMessages(onMessage) {\n const messageHandler = (messageEvent: MessageEvent) => {\n onMessage(messageEvent.data)\n }\n const unsubscribe = () => {\n self.removeEventListener('message', messageHandler as EventListener)\n }\n self.addEventListener('message', messageHandler as EventListener)\n return unsubscribe\n}\n\n/** Bound `addEventListener` from the worker global scope. */\n// eslint-disable-next-line unicorn/no-this-outside-of-class\nconst addEventListener = self.addEventListener.bind(this)\n/** Bound `postMessage` from the worker global scope. */\n// eslint-disable-next-line unicorn/no-this-outside-of-class\nconst postMessage = self.postMessage.bind(this)\n/** Bound `removeEventListener` from the worker global scope. */\n// eslint-disable-next-line unicorn/no-this-outside-of-class\nconst removeEventListener = self.removeEventListener.bind(this)\n\nexport {\n addEventListener,\n postMessage,\n removeEventListener,\n}\n\nconst expose = createExpose({\n isWorkerRuntime, postMessageToMaster, subscribeToMasterMessages,\n}, {\n addEventListener, postMessage, removeEventListener,\n})\n\nexport {\n isWorkerRuntime,\n postMessageToMaster,\n subscribeToMasterMessages,\n}\n\nexport { registerSerializer } from '../common.ts'\nexport { Transfer } from '../transferable.ts'\nexport { expose }\n"],
|
|
5
|
+
"mappings": ";AAyBO,SAAS,iBACd,QACA,gBACoC;AACpC,QAAM,uBAAuB,OAAO,YAAY,KAAK,MAAM;AAC3D,QAAM,qBAAqB,OAAO,UAAU,KAAK,MAAM;AAEvD,SAAO;AAAA,IACL,aAAa,CAAC,YAAoC,eAAe,YAAY,SAAS,oBAAoB;AAAA,IAE1G,WAAW,CAAC,UAAkC,eAAe,UAAU,OAAO,kBAAkB;AAAA,EAClG;AACF;AAWA,IAAM,yBAA6D;AAAA,EACjE,aAAa,CAAC,YAAoC;AAChD,UAAM,QAAQ,OAAO,OAAO,MAAM,SAAS;AAC3C,UAAM,UAAU,QAAQ;AACxB,UAAM,OAAO,QAAQ;AACrB,UAAM,QAAQ,QAAQ;AACtB,WAAO;AAAA,EACT;AAAA,EACA,WAAW,CAAC,WAAmC;AAAA,IAC7C,gBAAgB;AAAA,IAChB,SAAS,MAAM;AAAA,IACf,MAAM,MAAM;AAAA,IACZ,OAAO,MAAM;AAAA,EACf;AACF;AAEA,IAAM,oBAAoB,CAAC,UACzB,SAAS,QAAQ,OAAO,UAAU,YAAY,oBAAoB,SAAS,MAAM,mBAAmB;AAG/F,IAAM,oBAAkD;AAAA,EAC7D,aAAa,CAAC,YAAmC,kBAAkB,OAAO,IAAI,uBAAuB,YAAY,OAAO,IAAI;AAAA,EAC5H,WAAW,CAAC,UAAiC,iBAAiB,QAAS,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B,SAAOC;AACT;;;AC3PA,IAAM,kBAA0D,SAASC,mBAAkB;AACzF,QAAM,kBAAkB,SAAS,UAAa,OAAO,WAAW,eAAe,gBAAgB;AAC/F,SAAO,MAAM,gBAAgB,UAAa,CAAC;AAC7C;AAGA,IAAM,sBAAkE,SAASC,qBAAoB,MAAM,cAAe;AACxH,OAAK,YAAY,MAAM,YAAY;AACrC;AAGA,IAAM,4BAA8E,SAASC,2BAA0B,WAAW;AAChI,QAAM,iBAAiB,CAAC,iBAA+B;AACrD,cAAU,aAAa,IAAI;AAAA,EAC7B;AACA,QAAM,cAAc,MAAM;AACxB,SAAK,oBAAoB,WAAW,cAA+B;AAAA,EACrE;AACA,OAAK,iBAAiB,WAAW,cAA+B;AAChE,SAAO;AACT;AAIA,IAAM,mBAAmB,KAAK,iBAAiB,KAAK,MAAI;AAGxD,IAAM,cAAc,KAAK,YAAY,KAAK,MAAI;AAG9C,IAAM,sBAAsB,KAAK,oBAAoB,KAAK,MAAI;AAQ9D,IAAM,SAAS,aAAa;AAAA,EAC1B;AAAA,EAAiB;AAAA,EAAqB;AACxC,GAAG;AAAA,EACD;AAAA,EAAkB;AAAA,EAAa;AACjC,CAAC;",
|
|
6
6
|
"names": ["self", "expose", "isWorkerRuntime", "postMessageToMaster", "subscribeToMasterMessages"]
|
|
7
7
|
}
|
|
@@ -56,7 +56,16 @@ interface PoolOptions {
|
|
|
56
56
|
size?: number;
|
|
57
57
|
}
|
|
58
58
|
declare class WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {
|
|
59
|
-
static EventType:
|
|
59
|
+
static EventType: import("@ariestools/sdk/enum").Enum<{
|
|
60
|
+
initialized: 'initialized';
|
|
61
|
+
taskCanceled: 'taskCanceled';
|
|
62
|
+
taskCompleted: 'taskCompleted';
|
|
63
|
+
taskFailed: 'taskFailed';
|
|
64
|
+
taskQueued: 'taskQueued';
|
|
65
|
+
taskQueueDrained: 'taskQueueDrained';
|
|
66
|
+
taskStart: 'taskStart';
|
|
67
|
+
terminated: 'terminated';
|
|
68
|
+
}>;
|
|
60
69
|
private readonly debug;
|
|
61
70
|
private readonly eventObservable;
|
|
62
71
|
private readonly options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool-browser.d.ts","sourceRoot":"","sources":["../../../src/master/pool-browser.ts"],"names":[],"mappings":"AAWA,OAAO,EACM,UAAU,EACtB,MAAM,gBAAgB,CAAA;AAGvB,OAAO,KAAK,EACV,SAAS,EAAE,UAAU,EAAE,eAAe,EACvC,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC,gEAAgE;AAChE,MAAM,CAAC,OAAO,WAAW,IAAI,CAAC;IAC5B,KAAK,KAAK,CAAC,UAAU,SAAS,MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,UAAU,CAAC,CAAA;IACnE,KAAK,SAAS,GAAG,aAAa,CAAA;CAC/B;AAiCD;;;;GAIG;AACH,MAAM,WAAW,IAAI,CAAC,UAAU,SAAS,MAAM;IAC7C;;;;;OAKG;IACH,SAAS,CAAC,yBAAyB,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;IAE5D;;;;;OAKG;IACH,OAAO,CAAC,yBAAyB,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,CAAA;IAE9D;;OAEG;IACH,MAAM,IAAI,UAAU,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAA;IAE3C;;;;;OAKG;IACH,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;IAExF;;;;OAIG;IACH,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1C;AAED,UAAU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sCAEL;IAED,KAAK,CAAC,YAAY,EAAE,eAAe,CAAC,UAAU,EAAE,GAAG,CAAC,+BAuDnD;IAEK,SAAS,CAAC,KAAK,CAAC,EAAE,OAAO,iBAW9B;CACF;AAED;;GAEG;AACH,iBAAS,eAAe,CAAC,UAAU,SAAS,MAAM,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,WAAW,0BAI/H;AAID;;GAEG;AACH,eAAO,MAAM,IAAI,EAAsB,OAAO,eAAe,GAAG;IAAE,SAAS,EAAE,OAAO,aAAa,CAAA;CAAE,CAAA;AAEnG,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA"}
|
|
@@ -56,7 +56,16 @@ interface PoolOptions {
|
|
|
56
56
|
size?: number;
|
|
57
57
|
}
|
|
58
58
|
declare class WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {
|
|
59
|
-
static EventType:
|
|
59
|
+
static EventType: import("@ariestools/sdk/enum").Enum<{
|
|
60
|
+
initialized: 'initialized';
|
|
61
|
+
taskCanceled: 'taskCanceled';
|
|
62
|
+
taskCompleted: 'taskCompleted';
|
|
63
|
+
taskFailed: 'taskFailed';
|
|
64
|
+
taskQueued: 'taskQueued';
|
|
65
|
+
taskQueueDrained: 'taskQueueDrained';
|
|
66
|
+
taskStart: 'taskStart';
|
|
67
|
+
terminated: 'terminated';
|
|
68
|
+
}>;
|
|
60
69
|
private readonly debug;
|
|
61
70
|
private readonly eventObservable;
|
|
62
71
|
private readonly options;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool-node.d.ts","sourceRoot":"","sources":["../../../src/master/pool-node.ts"],"names":[],"mappings":"AAWA,OAAO,EACM,UAAU,EACtB,MAAM,gBAAgB,CAA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,MAAM,GAAG,WAAW,0BAI/H;AAID;;GAEG;AACH,eAAO,MAAM,IAAI,EAAsB,OAAO,eAAe,GAAG;IAAE,SAAS,EAAE,OAAO,aAAa,CAAA;CAAE,CAAA;AAEnG,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA"}
|
|
@@ -1,53 +1,48 @@
|
|
|
1
|
+
import { Enum, type EnumValue } from '@ariestools/sdk/enum';
|
|
1
2
|
import type { Thread } from './thread.ts';
|
|
2
3
|
/** Pool event type. Specifies the type of each `PoolEvent`. */
|
|
3
|
-
export declare
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
taskQueueDrained = "taskQueueDrained",
|
|
16
|
-
/** A worker started executing a task. */
|
|
17
|
-
taskStart = "taskStart",
|
|
18
|
-
/** The pool and its workers were terminated. */
|
|
19
|
-
terminated = "terminated"
|
|
20
|
-
}
|
|
4
|
+
export declare const PoolEventType: Enum<{
|
|
5
|
+
initialized: 'initialized';
|
|
6
|
+
taskCanceled: 'taskCanceled';
|
|
7
|
+
taskCompleted: 'taskCompleted';
|
|
8
|
+
taskFailed: 'taskFailed';
|
|
9
|
+
taskQueued: 'taskQueued';
|
|
10
|
+
taskQueueDrained: 'taskQueueDrained';
|
|
11
|
+
taskStart: 'taskStart';
|
|
12
|
+
terminated: 'terminated';
|
|
13
|
+
}>;
|
|
14
|
+
/** Pool event type. Specifies the type of each `PoolEvent`. */
|
|
15
|
+
export type PoolEventType = EnumValue<typeof PoolEventType>;
|
|
21
16
|
/** A function that runs a task on a worker thread and returns a promise of the result. */
|
|
22
17
|
export type TaskRunFunction<ThreadType extends Thread, Return> = (worker: ThreadType) => Promise<Return>;
|
|
23
18
|
/** Pool event. Subscribe to those events using `pool.events()`. Useful for debugging. */
|
|
24
19
|
export type PoolEvent<ThreadType extends Thread> = {
|
|
25
|
-
type: PoolEventType
|
|
20
|
+
type: (typeof PoolEventType)['initialized'];
|
|
26
21
|
size: number;
|
|
27
22
|
} | {
|
|
28
|
-
type: PoolEventType
|
|
23
|
+
type: (typeof PoolEventType)['taskQueued'];
|
|
29
24
|
taskID: number;
|
|
30
25
|
} | {
|
|
31
|
-
type: PoolEventType
|
|
26
|
+
type: (typeof PoolEventType)['taskQueueDrained'];
|
|
32
27
|
} | {
|
|
33
|
-
type: PoolEventType
|
|
28
|
+
type: (typeof PoolEventType)['taskStart'];
|
|
34
29
|
taskID: number;
|
|
35
30
|
workerID: number;
|
|
36
31
|
} | {
|
|
37
|
-
type: PoolEventType
|
|
32
|
+
type: (typeof PoolEventType)['taskCompleted'];
|
|
38
33
|
returnValue: any;
|
|
39
34
|
taskID: number;
|
|
40
35
|
workerID: number;
|
|
41
36
|
} | {
|
|
42
|
-
type: PoolEventType
|
|
37
|
+
type: (typeof PoolEventType)['taskFailed'];
|
|
43
38
|
error: Error;
|
|
44
39
|
taskID: number;
|
|
45
40
|
workerID: number;
|
|
46
41
|
} | {
|
|
47
|
-
type: PoolEventType
|
|
42
|
+
type: (typeof PoolEventType)['taskCanceled'];
|
|
48
43
|
taskID: number;
|
|
49
44
|
} | {
|
|
50
|
-
type: PoolEventType
|
|
45
|
+
type: (typeof PoolEventType)['terminated'];
|
|
51
46
|
remainingQueue: QueuedTask<ThreadType, any>[];
|
|
52
47
|
};
|
|
53
48
|
/** Descriptor for a worker in a pool, tracking its initialization and running tasks. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pool-types.d.ts","sourceRoot":"","sources":["../../../src/master/pool-types.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEzC,+DAA+D;AAC/D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AE,MAAM,CAAA;CACjB,GACC;IACA,IAAI,EAAE,CAAC,OAAO,aAAa,CAAC,CAAC,YAAY,CAAC,CAAA;IAC1C,KAAK,EAAE,KAAK,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;CACjB,GACC;IACA,IAAI,EAAE,CAAC,OAAO,aAAa,CAAC,CAAC,cAAc,CAAC,CAAA;IAC5C,MAAM,EAAE,MAAM,CAAA;CACf,GACC;IACA,IAAI,EAAE,CAAC,OAAO,aAAa,CAAC,CAAC,YAAY,CAAC,CAAA;IAC1C,cAAc,EAAE,UAAU,CAAC,UAAU,EAAE,GAAG,CAAC,EAAE,CAAA;CAC9C,CAAA;AAEH,wFAAwF;AACxF,MAAM,WAAW,gBAAgB,CAAC,UAAU,SAAS,MAAM;IACzD,mDAAmD;IACnD,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA;IACzB,+CAA+C;IAC/C,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAA;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,UAAU,CAAC,UAAU,SAAS,MAAM,EAAE,MAAM;IAC3D,eAAe;IACf,EAAE,EAAE,MAAM,CAAA;IAEV,eAAe;IACf,GAAG,EAAE,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;IAExC;;OAEG;IACH,MAAM,IAAI,IAAI,CAAA;IAEd;;;OAGG;IACH,IAAI,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;CAC9B"}
|
|
@@ -61,6 +61,17 @@ var $terminate = /* @__PURE__ */ Symbol("thread.terminate");
|
|
|
61
61
|
var $transferable = /* @__PURE__ */ Symbol("thread.transferable");
|
|
62
62
|
var $worker = /* @__PURE__ */ Symbol("thread.worker");
|
|
63
63
|
|
|
64
|
+
// src/types/master.ts
|
|
65
|
+
import { Enum } from "@ariestools/sdk/enum";
|
|
66
|
+
var WorkerEventType = Enum({
|
|
67
|
+
/** The threads implementation encountered an internal error. */
|
|
68
|
+
internalError: "internalError",
|
|
69
|
+
/** The worker emitted a message. */
|
|
70
|
+
message: "message",
|
|
71
|
+
/** The worker terminated. */
|
|
72
|
+
termination: "termination"
|
|
73
|
+
});
|
|
74
|
+
|
|
64
75
|
// src/master/invocation-proxy.ts
|
|
65
76
|
import DebugLogger from "debug";
|
|
66
77
|
import { multicast, Observable as Observable2 } from "observable-fns";
|
|
@@ -218,13 +229,34 @@ function isTransferDescriptor(thing) {
|
|
|
218
229
|
return thing != null && typeof thing === "object" && Reflect.get(thing, $transferable) === true;
|
|
219
230
|
}
|
|
220
231
|
|
|
232
|
+
// src/types/messages.ts
|
|
233
|
+
import { Enum as Enum2 } from "@ariestools/sdk/enum";
|
|
234
|
+
var MasterMessageType = Enum2({
|
|
235
|
+
/** Cancel a previously submitted job. */
|
|
236
|
+
cancel: "cancel",
|
|
237
|
+
/** Run a job in the worker. */
|
|
238
|
+
run: "run"
|
|
239
|
+
});
|
|
240
|
+
var WorkerMessageType = Enum2({
|
|
241
|
+
/** A job failed. */
|
|
242
|
+
error: "error",
|
|
243
|
+
/** The worker exposed its callable API. */
|
|
244
|
+
init: "init",
|
|
245
|
+
/** A job produced a result. */
|
|
246
|
+
result: "result",
|
|
247
|
+
/** A job started running. */
|
|
248
|
+
running: "running",
|
|
249
|
+
/** An error escaped the worker job handler. */
|
|
250
|
+
uncaughtError: "uncaughtError"
|
|
251
|
+
});
|
|
252
|
+
|
|
221
253
|
// src/master/invocation-proxy.ts
|
|
222
254
|
var debugMessages = DebugLogger("threads:master:messages");
|
|
223
255
|
var nextJobUID = 1;
|
|
224
256
|
var dedupe = (array) => [...new Set(array)];
|
|
225
|
-
var isJobErrorMessage = (data) => data?.type ===
|
|
226
|
-
var isJobResultMessage = (data) => data?.type ===
|
|
227
|
-
var isJobStartMessage = (data) => data?.type ===
|
|
257
|
+
var isJobErrorMessage = (data) => data?.type === WorkerMessageType.error;
|
|
258
|
+
var isJobResultMessage = (data) => data?.type === WorkerMessageType.result;
|
|
259
|
+
var isJobStartMessage = (data) => data?.type === WorkerMessageType.running;
|
|
228
260
|
function createObservableForJob(worker, jobUID) {
|
|
229
261
|
return new Observable2((observer) => {
|
|
230
262
|
let asyncType;
|
|
@@ -263,7 +295,7 @@ function createObservableForJob(worker, jobUID) {
|
|
|
263
295
|
return () => {
|
|
264
296
|
if (asyncType === "observable" || asyncType === void 0) {
|
|
265
297
|
const cancelMessage = {
|
|
266
|
-
type:
|
|
298
|
+
type: MasterMessageType.cancel,
|
|
267
299
|
uid: jobUID
|
|
268
300
|
};
|
|
269
301
|
worker.postMessage(cancelMessage);
|
|
@@ -301,7 +333,7 @@ function createProxyFunction(worker, method) {
|
|
|
301
333
|
const runMessage = {
|
|
302
334
|
args,
|
|
303
335
|
method,
|
|
304
|
-
type:
|
|
336
|
+
type: MasterMessageType.run,
|
|
305
337
|
uid
|
|
306
338
|
};
|
|
307
339
|
debugMessages("Sending command to run function to worker:", runMessage);
|
|
@@ -358,7 +390,7 @@ function createEventObservable(worker, workerTermination) {
|
|
|
358
390
|
const messageHandler = ((messageEvent) => {
|
|
359
391
|
const workerEvent = {
|
|
360
392
|
data: messageEvent.data,
|
|
361
|
-
type:
|
|
393
|
+
type: WorkerEventType.message
|
|
362
394
|
};
|
|
363
395
|
observer.next(workerEvent);
|
|
364
396
|
});
|
|
@@ -366,7 +398,7 @@ function createEventObservable(worker, workerTermination) {
|
|
|
366
398
|
debugThreadUtils("Unhandled promise rejection event in thread:", errorEvent);
|
|
367
399
|
const workerEvent = {
|
|
368
400
|
error: new Error(errorEvent.reason),
|
|
369
|
-
type:
|
|
401
|
+
type: WorkerEventType.internalError
|
|
370
402
|
};
|
|
371
403
|
observer.next(workerEvent);
|
|
372
404
|
});
|
|
@@ -374,7 +406,7 @@ function createEventObservable(worker, workerTermination) {
|
|
|
374
406
|
worker.addEventListener("unhandledrejection", rejectionHandler);
|
|
375
407
|
void (async () => {
|
|
376
408
|
await workerTermination;
|
|
377
|
-
const terminationEvent = { type:
|
|
409
|
+
const terminationEvent = { type: WorkerEventType.termination };
|
|
378
410
|
worker.removeEventListener("message", messageHandler);
|
|
379
411
|
worker.removeEventListener("unhandledrejection", rejectionHandler);
|
|
380
412
|
observer.next(terminationEvent);
|
|
@@ -392,7 +424,7 @@ function createTerminator(worker) {
|
|
|
392
424
|
return { terminate, termination };
|
|
393
425
|
}
|
|
394
426
|
function setPrivateThreadProps(raw, worker, workerEvents, terminate) {
|
|
395
|
-
const workerErrors = workerEvents.filter((event) => event.type ===
|
|
427
|
+
const workerErrors = workerEvents.filter((event) => event.type === WorkerEventType.internalError).map((errorEvent) => errorEvent.error);
|
|
396
428
|
const result = raw;
|
|
397
429
|
const privateProps = [
|
|
398
430
|
[$errors, { enumerable: false, value: workerErrors }],
|