npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@xylabs/threads

v5.0.95

Published

Web workers & worker threads as simple as a function call

Readme

@xylabs/threads

logo

main-build npm-badge npm-downloads-badge jsdelivr-badge npm-license-badge codacy-badge codeclimate-badge snyk-badge socket-badge

Web workers & worker threads as simple as a function call

Reference

@xylabs/threads


Modules

| Module | Description | | ------ | ------ | | index-browser | - | | index-node | - |

index-browser

functions

### <a id="Transfer"></a>Transfer

@xylabs/threads


Call Signature

function Transfer(transferable: Transferable): TransferDescriptor;

Mark a transferable object as such, so it will no be serialized and deserialized on messaging with the main thread, but to transfer ownership of it to the receiving thread.

Only works with array buffers, message ports and few more special types of objects, but it's much faster than serializing and deserializing them.

Note: The transferable object cannot be accessed by this thread again unless the receiving thread transfers it back again!

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | transferable | Transferable | Array buffer, message port or similar. |

Returns

TransferDescriptor

See

https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast

Call Signature

function Transfer<T>(payload: T, transferables: Transferable[]): TransferDescriptor;

Mark transferable objects within an arbitrary object or array as being a transferable object. They will then not be serialized and deserialized on messaging with the main thread, but ownership of them will be tranferred to the receiving thread.

Only array buffers, message ports and few more special types of objects can be transferred, but it's much faster than serializing and deserializing them.

Note: The transferable object cannot be accessed by this thread again unless the receiving thread transfers it back again!

Type Parameters

| Type Parameter | | ------ | | T |

Parameters

| Parameter | Type | | ------ | ------ | | payload | T | | transferables | Transferable[] |

Returns

TransferDescriptor

See

https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast

### <a id="isWorkerRuntime"></a>isWorkerRuntime

@xylabs/threads


function isWorkerRuntime(): boolean;

Check whether the current code is running inside a web worker context.

Returns

boolean

True if running in a worker, false otherwise.

### <a id="registerSerializer"></a>registerSerializer

@xylabs/threads


function registerSerializer(serializer: SerializerImplementation<JsonSerializable>): void;

Register a custom serializer to extend the default serialization behavior for worker messages.

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | serializer | SerializerImplementation<JsonSerializable> | The serializer implementation to register. |

Returns

void

### <a id="spawn"></a>spawn

@xylabs/threads


function spawn<Exposed>(worker: Worker, options?: {
  timeout?: number;
}): Promise<ExposedAs<Exposed>>;

Spawn a new thread. Takes a fresh worker instance, wraps it in a thin abstraction layer to provide the transparent API and verifies that the worker has initialized successfully.

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | Exposed extends WorkerFunction | WorkerModule<any> | ArbitraryWorkerInterface |

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | worker | Worker | Instance of Worker. Either a web worker or worker_threads worker. | | options? | { timeout?: number; } | - | | options.timeout? | number | Init message timeout. Default: 10000 or set by environment variable. |

Returns

Promise<ExposedAs<Exposed>>

interfaces

### <a id="Pool"></a>Pool

@xylabs/threads


Thread pool managing a set of worker threads. Use it to queue tasks that are run on those threads with limited concurrency.

Type Parameters

| Type Parameter | | ------ | | ThreadType extends Thread |

Methods

completed()

completed(allowResolvingImmediately?: boolean): Promise<any>;

Returns a promise that resolves once the task queue is emptied. Promise will be rejected if any task fails.

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | allowResolvingImmediately? | boolean | Set to true to resolve immediately if task queue is currently empty. |

Returns

Promise<any>


settled()

settled(allowResolvingImmediately?: boolean): Promise<Error[]>;

Returns a promise that resolves once the task queue is emptied. Failing tasks will not cause the promise to be rejected.

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | allowResolvingImmediately? | boolean | Set to true to resolve immediately if task queue is currently empty. |

Returns

Promise<Error[]>


events()

events(): Observable<PoolEvent<ThreadType>>;

Returns an observable that yields pool events.

Returns

Observable<PoolEvent<ThreadType>>


queue()

queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return>;

Queue a task and return a promise that resolves once the task has been dequeued, started and finished.

Type Parameters

| Type Parameter | | ------ | | Return |

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | task | TaskRunFunction<ThreadType, Return> | An async function that takes a thread instance and invokes it. |

Returns

QueuedTask<ThreadType, Return>


terminate()

terminate(force?: boolean): Promise<void>;

Terminate all pool threads.

Parameters

| Parameter | Type | Description | | ------ | ------ | ------ | | force? | boolean | Set to true to kill the thread even if it cannot be stopped gracefully. |

Returns

Promise<void>

### <a id="QueuedTask"></a>QueuedTask

@xylabs/threads


Task that has been pool.queued()-ed.

Type Parameters

| Type Parameter | | ------ | | ThreadType extends Thread | | Return |

Properties

| Property | Type | Description | | ------ | ------ | ------ | | then | <TResult1, TResult2>(onfulfilled?: (value: Return) => TResult1 | PromiseLike<TResult1> | null, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2> | null) => Promise<TResult1 | TResult2> | QueuedTask is thenable, so you can await it. Resolves when the task has successfully been executed. Rejects if the task fails. |

Methods

cancel()

cancel(): void;

Queued tasks can be cancelled until the pool starts running them on a worker thread.

Returns

void

### <a id="Serializer"></a>Serializer

@xylabs/threads


A serializer that can convert between a message format and an input type.

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | Msg | JsonSerializable | | Input | any |

Methods

deserialize()

deserialize(message: Msg): Input;

Parameters

| Parameter | Type | | ------ | ------ | | message | Msg |

Returns

Input


serialize()

serialize(input: Input): Msg;

Parameters

| Parameter | Type | | ------ | ------ | | input | Input |

Returns

Msg

### <a id="SerializerImplementation"></a>SerializerImplementation

@xylabs/threads


A serializer implementation that receives a fallback (default) serializer for chaining.

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | Msg | JsonSerializable | | Input | any |

Methods

deserialize()

deserialize(message: Msg, defaultDeserialize: (msg: Msg) => Input): Input;

Parameters

| Parameter | Type | | ------ | ------ | | message | Msg | | defaultDeserialize | (msg: Msg) => Input |

Returns

Input


serialize()

serialize(input: Input, defaultSerialize: (inp: Input) => Msg): Msg;

Parameters

| Parameter | Type | | ------ | ------ | | input | Input | | defaultSerialize | (inp: Input) => Msg |

Returns

Msg

### <a id="TransferDescriptor"></a>TransferDescriptor

@xylabs/threads


Descriptor wrapping a value with its associated transferable objects for zero-copy messaging.

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | T | any |

Properties

| Property | Type | | ------ | ------ | | [$transferable] | true | | send | T | | transferables | Transferable[] |

namespaces

### Pool

  ### type-aliases

    ### <a id="Event"></a>Event

@xylabs/threads


type Event<ThreadType> = PoolEvent<ThreadType>;

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | ThreadType extends Thread | any |

    ### <a id="EventType"></a>EventType

@xylabs/threads


type EventType = PoolEventType;

type-aliases

### <a id="BlobWorker"></a>BlobWorker

@xylabs/threads


type BlobWorker = typeof BlobWorkerClass;

Separate class to spawn workers from source code blobs or strings.

### <a id="ExposedAs"></a>ExposedAs

@xylabs/threads


type ExposedAs<Exposed> = Exposed extends ArbitraryWorkerInterface ? ArbitraryThreadType : Exposed extends WorkerFunction ? FunctionThread<Parameters<Exposed>, StripAsync<ReturnType<Exposed>>> : Exposed extends WorkerModule<any> ? ModuleThread<Exposed> : never;

Maps a worker's exposed API type to its corresponding thread type (FunctionThread or ModuleThread).

Type Parameters

| Type Parameter | | ------ | | Exposed extends WorkerFunction | WorkerModule<any> |

### <a id="FunctionThread"></a>FunctionThread

@xylabs/threads


type FunctionThread<Args, ReturnType> = ProxyableFunction<Args, ReturnType> & PrivateThreadProps;

A thread wrapping a single exposed function.

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | Args extends any[] | any[] | | ReturnType | any |

### <a id="JsonSerializable"></a>JsonSerializable

@xylabs/threads


type JsonSerializable = 
  | JsonSerializablePrimitive
  | JsonSerializablePrimitive[]
  | JsonSerializableObject
  | JsonSerializableObject[];

A JSON-compatible value that can be serialized for worker message passing.

### <a id="ModuleThread"></a>ModuleThread

@xylabs/threads


type ModuleThread<Methods> = ModuleProxy<Methods> & PrivateThreadProps;

A thread wrapping an exposed module of functions.

Type Parameters

| Type Parameter | Default type | | ------ | ------ | | Methods extends ModuleMethods | any |

### <a id="Thread"></a>Thread

@xylabs/threads


type Thread = ThreadType;

Re-exported Thread type from the master types module.

### <a id="Worker"></a>Worker

@xylabs/threads


type Worker = WorkerType;

Worker implementation. Either web worker or a node.js Worker class.

variables

### <a id="BlobWorker"></a>BlobWorker

@xylabs/threads


BlobWorker: typeof BlobWorker;

Separate class to spawn workers from source code blobs or strings.

### <a id="DefaultSerializer"></a>DefaultSerializer

@xylabs/threads


const DefaultSerializer: Serializer<JsonSerializable>;

Default serializer that handles Error instances and passes other values through.

### <a id="Pool"></a>Pool

@xylabs/threads


Pool: <ThreadType>(spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions) => WorkerPool<ThreadType> & {
  EventType: typeof PoolEventType;
};

Thread pool constructor. Creates a new pool and spawns its worker threads.

Type Declaration

| Name | Type | | ------ | ------ | | EventType | typeof PoolEventType |

### <a id="Thread"></a>Thread

@xylabs/threads


Thread: {
  errors: Observable<Error>;
  events: Observable<WorkerEvent>;
  terminate: Promise<void>;
};

Thread utility functions. Use them to manage or inspect a spawn()-ed thread.

Type Declaration

| Name | Type | Description | | ------ | ------ | ------ | | errors() | (thread: ThreadT) => Observable<Error> | Return an observable that can be used to subscribe to all errors happening in the thread. | | events() | (thread: ThreadT) => Observable<WorkerEvent> | Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. | | terminate() | (thread: ThreadT) => Promise<void> | Terminate a thread. Remember to terminate every thread when you are done using it. |

### <a id="Worker"></a>Worker

@xylabs/threads


Worker: typeof WorkerImplementation;

Worker implementation. Either web worker or a node.js Worker class.

index-node

functions

### <a id="isWorkerRuntime"></a>isWorkerRuntime

@xylabs/threads


function isWorkerRuntime(): boolean;

Check whether the current code is running inside a Node.js worker thread.

Returns

boolean

True if running in a worker thread (not the main thread), false otherwise.

type-aliases

### <a id="BlobWorker"></a>BlobWorker

@xylabs/threads


type BlobWorker = typeof BlobWorkerClass;

Separate class to spawn workers from source code blobs or strings.

### <a id="Worker"></a>Worker

@xylabs/threads


type Worker = WorkerType;

Worker implementation. Either web worker or a node.js Worker class.

variables

### <a id="BlobWorker"></a>BlobWorker

@xylabs/threads


BlobWorker: typeof BlobWorker;

Separate class to spawn workers from source code blobs or strings.

### <a id="Worker"></a>Worker

@xylabs/threads


Worker: typeof WorkerImplementation;

Worker implementation. Either web worker or a node.js Worker class.

Part of sdk-js

Maintainers

License

See the LICENSE file for license details

Credits

Made with 🔥 and ❄️ by XYLabs