@xylabs/threads 5.0.14 → 5.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index-browser.mjs +119 -209
- package/dist/browser/index-browser.mjs.map +1 -1
- package/dist/browser/master/implementation.browser.mjs +11 -36
- package/dist/browser/master/implementation.browser.mjs.map +1 -1
- package/dist/browser/master/index-browser.mjs +117 -201
- package/dist/browser/master/index-browser.mjs.map +1 -1
- package/dist/browser/master/pool-browser.mjs +53 -65
- package/dist/browser/master/pool-browser.mjs.map +1 -1
- package/dist/browser/worker/worker.browser.mjs +43 -79
- package/dist/browser/worker/worker.browser.mjs.map +1 -1
- package/dist/neutral/master/register.mjs +62 -121
- package/dist/neutral/master/register.mjs.map +1 -1
- package/dist/neutral/master/spawn.mjs +53 -106
- package/dist/neutral/master/spawn.mjs.map +1 -1
- package/dist/neutral/master/thread.mjs +0 -4
- package/dist/neutral/master/thread.mjs.map +1 -1
- package/dist/neutral/observable-promise.mjs +20 -27
- package/dist/neutral/observable-promise.mjs.map +1 -1
- package/dist/neutral/observable.mjs +3 -12
- package/dist/neutral/observable.mjs.map +1 -1
- package/dist/neutral/types/messages.mjs +4 -4
- package/dist/neutral/types/messages.mjs.map +1 -1
- package/dist/node/index-node.mjs +169 -293
- package/dist/node/index-node.mjs.map +1 -1
- package/dist/node/master/implementation.node.mjs +62 -121
- package/dist/node/master/implementation.node.mjs.map +1 -1
- package/dist/node/master/index-node.mjs +168 -286
- package/dist/node/master/index-node.mjs.map +1 -1
- package/dist/node/master/pool-node.mjs +115 -183
- package/dist/node/master/pool-node.mjs.map +1 -1
- package/dist/node/worker/worker.node.mjs +43 -80
- package/dist/node/worker/worker.node.mjs.map +1 -1
- package/package.json +3 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/worker/worker.node.ts","../../../src/worker/expose.ts","../../../src/serializers.ts","../../../src/common.ts","../../../src/symbols.ts","../../../src/transferable.ts","../../../src/types/messages.ts"],"sourcesContent":["/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// tslint:disable no-shadowed-variable\n\nimport type { MessagePort, TransferListItem } from 'node:worker_threads'\nimport { parentPort as optionalParentPort } from 'node:worker_threads'\n\nimport { assertEx } from '@xylabs/assert'\n\nimport type { AbstractedWorkerAPI } from '../types/worker.ts'\nimport { createExpose } from './expose.ts'\n\nconst parentPort = assertEx(optionalParentPort, () => 'Invariant violation: MessagePort to parent is not available.')\n\nfunction assertMessagePort(port: MessagePort | null | undefined): MessagePort {\n if (!port) {\n throw new Error('Invariant violation: MessagePort to parent is not available.')\n }\n return port\n}\n\nconst isWorkerRuntime: AbstractedWorkerAPI['isWorkerRuntime'] = function isWorkerRuntime() {\n return true // isMainThread\n}\n\nconst postMessageToMaster: AbstractedWorkerAPI['postMessageToMaster'] = function postMessageToMaster(data, transferList) {\n assertMessagePort(parentPort).postMessage(data, transferList as TransferListItem[])\n}\n\nconst subscribeToMasterMessages: AbstractedWorkerAPI['subscribeToMasterMessages'] = function subscribeToMasterMessages(onMessage) {\n if (!parentPort) {\n throw new Error('Invariant violation: MessagePort to parent is not available.')\n }\n const messageHandler = (message: any) => {\n onMessage(message)\n }\n const unsubscribe = () => {\n assertMessagePort(parentPort).off('message', messageHandler)\n }\n assertMessagePort(parentPort).on('message', messageHandler)\n return unsubscribe\n}\n\nconst addEventListener = parentPort?.on.bind(parentPort)\nconst postMessage = parentPort?.postMessage.bind(parentPort)\nconst removeEventListener = parentPort?.off.bind(parentPort)\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","/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-floating-promises */\n\nimport isSomeObservable from 'is-observable-2-1-0'\nimport type { Observable, Subscription } from 'observable-fns'\n\nimport { deserialize, serialize } from '../common.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 && (value as ErrorEvent).error\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 && thing.type === MasterMessageType.cancel\n const isMasterJobRunMessage = (thing: any): thing is MasterJobRunMessage => thing && 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 && 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 // tslint:disable-next-line no-console\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) {\n runFunction(messageData.uid, exposed, messageData.args.map(deserialize))\n }\n })\n postFunctionInitMessage()\n } else if (typeof exposed === 'object' && exposed) {\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (isMasterJobRunMessage(messageData) && messageData.method) {\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 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\n if (typeof globalThis !== 'undefined' && typeof self.addEventListener === 'function' && implementation.isWorkerRuntime()) {\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 && typeof (error as any).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 if (typeof process !== 'undefined' && typeof process.on === 'function' && implementation.isWorkerRuntime()) {\n process.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 process.on('unhandledRejection', (error) => {\n if (error && typeof (error as any).message === 'string') {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error as any), 250)\n }\n })\n }\n\n return expose\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","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","/// <reference lib=\"webworker\" />\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { $transferable } from './symbols.ts'\n\nexport interface TransferDescriptor<T = any> {\n [$transferable]: true\n send: T\n transferables: Transferable[]\n}\n\nfunction isTransferable(thing: any): thing is Transferable {\n if (!thing || 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\nexport function isTransferDescriptor(thing: any): thing is TransferDescriptor {\n return thing && typeof thing === 'object' && thing[$transferable]\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 * @param transferable Array buffer, message port or similar.\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 transferable Array buffer, message port or similar.\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\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 return {\n [$transferable]: true,\n send: payload,\n transferables,\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/member-ordering */\nexport interface SerializedError {\n __error_marker: '$$error'\n message: string\n name: string\n stack?: string\n}\n\n/////////////////////////////\n// Messages sent by master:\n\nexport enum MasterMessageType {\n cancel = 'cancel',\n run = 'run',\n}\n\nexport type MasterJobCancelMessage = {\n type: MasterMessageType.cancel\n uid: number\n}\n\nexport type MasterJobRunMessage = {\n type: MasterMessageType.run\n uid: number\n method?: string\n args: any[]\n}\n\n////////////////////////////\n// Messages sent by worker:\n\nexport enum WorkerMessageType {\n error = 'error',\n init = 'init',\n result = 'result',\n running = 'running',\n uncaughtError = 'uncaughtError',\n}\n\nexport type WorkerUncaughtErrorMessage = {\n type: WorkerMessageType.uncaughtError\n error: {\n message: string\n name: string\n stack?: string\n }\n}\n\nexport type WorkerInitMessage = {\n type: WorkerMessageType.init\n exposed: { type: 'function' } | { type: 'module'; methods: string[] }\n}\n\nexport type WorkerJobErrorMessage = {\n type: WorkerMessageType.error\n uid: number\n error: SerializedError\n}\n\nexport type WorkerJobResultMessage = {\n type: WorkerMessageType.result\n uid: number\n complete?: true\n payload?: any\n}\n\nexport type WorkerJobStartMessage = {\n type: WorkerMessageType.running\n uid: number\n resultType: 'observable' | 'promise'\n}\n"],"mappings":";;;;AAKA,SAASA,cAAcC,0BAA0B;AAEjD,SAASC,gBAAgB;;;ACHzB,OAAOC,sBAAsB;;;ACUtB,SAASC,iBACdC,QACAC,gBAAgE;AAEhE,QAAMC,uBAAuBF,OAAOG,YAAYC,KAAKJ,MAAAA;AACrD,QAAMK,qBAAqBL,OAAOM,UAAUF,KAAKJ,MAAAA;AAEjD,SAAO;IACLG,YAAYI,SAAoB;AAC9B,aAAON,eAAeE,YAAYI,SAASL,oBAAAA;IAC7C;IAEAI,UAAUE,OAAgB;AACxB,aAAOP,eAAeK,UAAUE,OAAOH,kBAAAA;IACzC;EACF;AACF;AAhBgBN;AA0BhB,IAAMU,yBAA6D;EACjEN,YAAYI,SAAwB;AAClC,WAAOG,OAAOC,OAAO,IAAIC,MAAML,QAAQA,OAAO,GAAG;MAC/CM,MAAMN,QAAQM;MACdC,OAAOP,QAAQO;IACjB,CAAA;EACF;EACAR,UAAUS,OAAY;AACpB,WAAO;MACLC,gBAAgB;MAChBT,SAASQ,MAAMR;MACfM,MAAME,MAAMF;MACZC,OAAOC,MAAMD;IACf;EACF;AACF;AAEA,IAAMG,oBAAoB,wBAACC,UACz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,MAAI,CAACA,MAAM;AACT,UAAM,IAAIC,MAAM,8DAAA;EAClB;AACA,SAAOD;AACT;AALSD;AAOT,IAAMG,kBAA0D,gCAASA,mBAAAA;AACvE,SAAO;AACT,GAFgE;AAIhE,IAAMC,sBAAkE,gCAASA,qBAAoBC,MAAMC,cAAY;AACrHN,oBAAkBH,UAAAA,EAAYU,YAAYF,MAAMC,YAAAA;AAClD,GAFwE;AAIxE,IAAME,4BAA8E,gCAASA,2BAA0BC,WAAS;AAC9H,MAAI,CAACZ,YAAY;AACf,UAAM,IAAIK,MAAM,8DAAA;EAClB;AACA,QAAMQ,iBAAiB,wBAACC,YAAAA;AACtBF,cAAUE,OAAAA;EACZ,GAFuB;AAGvB,QAAMC,cAAc,6BAAA;AAClBZ,sBAAkBH,UAAAA,EAAYgB,IAAI,WAAWH,cAAAA;EAC/C,GAFoB;AAGpBV,oBAAkBH,UAAAA,EAAYiB,GAAG,WAAWJ,cAAAA;AAC5C,SAAOE;AACT,GAZoF;AAcpF,IAAMG,mBAAmBlB,YAAYiB,GAAGE,KAAKnB,UAAAA;AAC7C,IAAMU,cAAcV,YAAYU,YAAYS,KAAKnB,UAAAA;AACjD,IAAMoB,sBAAsBpB,YAAYgB,IAAIG,KAAKnB,UAAAA;AAQjD,IAAMqB,SAASC,aAAa;EAC1BC;EAAiBC;EAAqBC;AACxC,GAAG;EACDC;EAAkBC;EAAaC;AACjC,CAAA;","names":["parentPort","optionalParentPort","assertEx","isSomeObservable","extendSerializer","extend","implementation","fallbackDeserializer","deserialize","bind","fallbackSerializer","serialize","message","input","DefaultErrorSerializer","Object","assign","Error","name","stack","error","__error_marker","isSerializedError","thing","DefaultSerializer","globalThis","registeredSerializer","DefaultSerializer","registerSerializer","serializer","extendSerializer","deserialize","message","serialize","input","$errors","Symbol","$events","$terminate","$transferable","$worker","isTransferable","thing","isTransferDescriptor","$transferable","Transfer","payload","transferables","console","log","Error","send","MasterMessageType","WorkerMessageType","isErrorEvent","value","error","createExpose","implementation","self","exposeCalled","activeSubscriptions","Map","isMasterJobCancelMessage","thing","type","MasterMessageType","cancel","isMasterJobRunMessage","run","isObservable","isSomeObservable","isZenObservable","subscribe","deconstructTransfer","isTransferDescriptor","payload","send","transferables","undefined","postFunctionInitMessage","initMessage","exposed","WorkerMessageType","init","postMessageToMaster","postModuleInitMessage","methodNames","methods","postJobErrorMessage","uid","rawError","errorMessage","serialize","postJobResultMessage","completed","resultValue","resultMessage","complete","result","postJobStartMessage","resultType","startMessage","running","postUncaughtErrorMessage","uncaughtError","subError","console","runFunction","jobUID","fn","args","syncResult","ex","subscription","delete","set","expose","isWorkerRuntime","Error","subscribeToMasterMessages","messageData","method","map","deserialize","Object","keys","filter","key","get","unsubscribe","globalThis","addEventListener","event","setTimeout","reason","message","process","on","parentPort","assertEx","optionalParentPort","assertMessagePort","port","Error","isWorkerRuntime","postMessageToMaster","data","transferList","postMessage","subscribeToMasterMessages","onMessage","messageHandler","message","unsubscribe","off","on","addEventListener","bind","removeEventListener","expose","createExpose","isWorkerRuntime","postMessageToMaster","subscribeToMasterMessages","addEventListener","postMessage","removeEventListener"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/worker/worker.node.ts","../../../src/worker/expose.ts","../../../src/serializers.ts","../../../src/common.ts","../../../src/symbols.ts","../../../src/transferable.ts"],"sourcesContent":["/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// tslint:disable no-shadowed-variable\n\nimport type { MessagePort, TransferListItem } from 'node:worker_threads'\nimport { parentPort as optionalParentPort } from 'node:worker_threads'\n\nimport { assertEx } from '@xylabs/assert'\n\nimport type { AbstractedWorkerAPI } from '../types/worker.ts'\nimport { createExpose } from './expose.ts'\n\nconst parentPort = assertEx(optionalParentPort, () => 'Invariant violation: MessagePort to parent is not available.')\n\nfunction assertMessagePort(port: MessagePort | null | undefined): MessagePort {\n if (!port) {\n throw new Error('Invariant violation: MessagePort to parent is not available.')\n }\n return port\n}\n\nconst isWorkerRuntime: AbstractedWorkerAPI['isWorkerRuntime'] = function isWorkerRuntime() {\n return true // isMainThread\n}\n\nconst postMessageToMaster: AbstractedWorkerAPI['postMessageToMaster'] = function postMessageToMaster(data, transferList) {\n assertMessagePort(parentPort).postMessage(data, transferList as TransferListItem[])\n}\n\nconst subscribeToMasterMessages: AbstractedWorkerAPI['subscribeToMasterMessages'] = function subscribeToMasterMessages(onMessage) {\n if (!parentPort) {\n throw new Error('Invariant violation: MessagePort to parent is not available.')\n }\n const messageHandler = (message: any) => {\n onMessage(message)\n }\n const unsubscribe = () => {\n assertMessagePort(parentPort).off('message', messageHandler)\n }\n assertMessagePort(parentPort).on('message', messageHandler)\n return unsubscribe\n}\n\nconst addEventListener = parentPort?.on.bind(parentPort)\nconst postMessage = parentPort?.postMessage.bind(parentPort)\nconst removeEventListener = parentPort?.off.bind(parentPort)\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","/* eslint-disable import-x/no-internal-modules */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-floating-promises */\n\nimport isSomeObservable from 'is-observable-2-1-0'\nimport type { Observable, Subscription } from 'observable-fns'\n\nimport { deserialize, serialize } from '../common.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 && (value as ErrorEvent).error\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 && thing.type === MasterMessageType.cancel\n const isMasterJobRunMessage = (thing: any): thing is MasterJobRunMessage => thing && 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 && 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 // tslint:disable-next-line no-console\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) {\n runFunction(messageData.uid, exposed, messageData.args.map(deserialize))\n }\n })\n postFunctionInitMessage()\n } else if (typeof exposed === 'object' && exposed) {\n implementation.subscribeToMasterMessages((messageData: unknown) => {\n if (isMasterJobRunMessage(messageData) && messageData.method) {\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 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\n if (typeof globalThis !== 'undefined' && typeof self.addEventListener === 'function' && implementation.isWorkerRuntime()) {\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 && typeof (error as any).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 if (typeof process !== 'undefined' && typeof process.on === 'function' && implementation.isWorkerRuntime()) {\n process.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 process.on('unhandledRejection', (error) => {\n if (error && typeof (error as any).message === 'string') {\n // Post with some delay, so the master had some time to subscribe to messages\n setTimeout(() => postUncaughtErrorMessage(error as any), 250)\n }\n })\n }\n\n return expose\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","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","/// <reference lib=\"webworker\" />\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { $transferable } from './symbols.ts'\n\nexport interface TransferDescriptor<T = any> {\n [$transferable]: true\n send: T\n transferables: Transferable[]\n}\n\nfunction isTransferable(thing: any): thing is Transferable {\n if (!thing || 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\nexport function isTransferDescriptor(thing: any): thing is TransferDescriptor {\n return thing && typeof thing === 'object' && thing[$transferable]\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 * @param transferable Array buffer, message port or similar.\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 transferable Array buffer, message port or similar.\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\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 return {\n [$transferable]: true,\n send: payload,\n transferables,\n }\n}\n"],"mappings":";AAKA,SAAS,cAAc,0BAA0B;AAEjD,SAAS,gBAAgB;;;ACHzB,OAAO,sBAAsB;;;ACUtB,SAAS,iBACd,QACA,gBACoC;AACpC,QAAM,uBAAuB,OAAO,YAAY,KAAK,MAAM;AAC3D,QAAM,qBAAqB,OAAO,UAAU,KAAK,MAAM;AAEvD,SAAO;AAAA,IACL,YAAY,SAAiC;AAC3C,aAAO,eAAe,YAAY,SAAS,oBAAoB;AAAA,IACjE;AAAA,IAEA,UAAU,OAA+B;AACvC,aAAO,eAAe,UAAU,OAAO,kBAAkB;AAAA,IAC3D;AAAA,EACF;AACF;AAUA,IAAM,yBAA6D;AAAA,EACjE,YAAY,SAAiC;AAC3C,WAAO,OAAO,OAAO,IAAI,MAAM,QAAQ,OAAO,GAAG;AAAA,MAC/C,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,IACjB,CAAC;AAAA,EACH;AAAA,EACA,UAAU,OAA+B;AACvC,WAAO;AAAA,MACL,gBAAgB;AAAA,MAChB,SAAS,MAAM;AAAA,MACf,MAAM,MAAM;AAAA,MACZ,OAAO,MAAM;AAAA,IACf;AAAA,EACF;AACF;AA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mBAAmB,YAAY,GAAG,KAAK,UAAU;AACvD,IAAM,cAAc,YAAY,YAAY,KAAK,UAAU;AAC3D,IAAM,sBAAsB,YAAY,IAAI,KAAK,UAAU;AAQ3D,IAAM,SAAS,aAAa;AAAA,EAC1B;AAAA,EAAiB;AAAA,EAAqB;AACxC,GAAG;AAAA,EACD;AAAA,EAAkB;AAAA,EAAa;AACjC,CAAC;","names":["expose","isWorkerRuntime","postMessageToMaster","subscribeToMasterMessages"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xylabs/threads",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.16",
|
|
4
4
|
"description": "Web workers & worker threads as simple as a function call",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"thread",
|
|
@@ -113,15 +113,14 @@
|
|
|
113
113
|
"package-compile-tsup": "tsup --config tsup.browser.config.ts && tsup --config tsup.node.config.ts && tsup --config tsup.neutral.config.ts"
|
|
114
114
|
},
|
|
115
115
|
"dependencies": {
|
|
116
|
-
"@xylabs/assert": "~5.0.
|
|
116
|
+
"@xylabs/assert": "~5.0.16",
|
|
117
117
|
"debug": "~4.4.3",
|
|
118
118
|
"is-observable-2-1-0": "npm:is-observable@2.1.0",
|
|
119
119
|
"observable-fns": "~0.6.1"
|
|
120
120
|
},
|
|
121
121
|
"devDependencies": {
|
|
122
|
-
"@swc/core": "1.13.5",
|
|
123
122
|
"@types/debug": "~4.1.12",
|
|
124
|
-
"@types/node": "~24.9.
|
|
123
|
+
"@types/node": "~24.9.2",
|
|
125
124
|
"@xylabs/eslint-config-flat": "~7.1.8",
|
|
126
125
|
"@xylabs/ts-scripts-yarn3": "~7.1.8",
|
|
127
126
|
"eslint": "~9.38.0",
|