UNPKG

isoworker

Version:

Isomorphic workerization with dependencies

54 lines (53 loc) 2.72 kB
declare type SymbolMap = Record<symbol, number>; export declare type Context = [string, Array<string | [string, unknown]>, unknown[]]; export declare type DepList = () => unknown[]; export declare type Environment = { s: SymbolMap; r: symbol | string; }; /** * Creates a context for a worker execution environment * @param depList The dependencies in the worker environment * @param env The environment to use for the worker. If this object was used * before, `isoworker` will use certain optimizations to avoid code * duplication. This is useful for sending a serialized message to * a worker to be dynamically evaluated, in which case you may want * to avoid duplicating existing function declarations. * @returns An environment that can be built to a Worker. Note the fourth * element of the tuple, the global element registry, is currently not useful. */ export declare function createContext(depList: DepList | DepList[], env?: Partial<Environment>): Context; /** * A RegExp that matches the placeholder used in isoworker's initial message code. * Used after loading structured-cloneable data onto the worker thread in order to * finalize the context creation. */ export declare const dataPlaceholder: RegExp; /** * A workerized function (from arguments and return type) */ export declare type Workerized<A extends unknown[], R> = ((...args: [...A, (err: Error, res: R) => unknown]) => void) & { /** * Kills the worker associated with this workerized function. * Subsequent calls will fail. */ close(): void; }; /** * Converts a function with dependencies into a worker * @param fn The function to workerize * @param deps The dependencies to add. This should include sub-dependencies. * For example, if you are workerizing a function that calls * another function, put any dependencies of the other function * here as well. * @param replaceTransfer The list of objects to replace the default transfer * list with. If you provide an array of transferable * items, they will be used; if you provide the value * `true`, `isoworker` will refrain from the default * behavior of automatically transferring everything * it can. * @returns A function that accepts parameters and, as the last argument, a * callback to use when the worker returns. */ export declare function workerize<TA extends unknown[], TR>(fn: (...args: TA) => TR, deps: DepList | DepList[], serializeArgs?: boolean, replaceTransfer?: unknown[] | boolean): Workerized<TA, TR>; export {};