├── .browserslistrc
├── .github
└── workflows
│ ├── node.js.yml
│ └── release.yml
├── .gitignore
├── LICENSE.md
├── README.md
├── jest.config.js
├── node_test.js
├── nodemon.json
├── package-lock.json
├── package.json
├── rollup.config.dev.js
├── rollup.config.js
├── rollup.config.worker.dev.js
├── rollup.config.worker.js
├── src
├── index.ts
├── lib
│ ├── colors.ts
│ ├── getErrorPreview.ts
│ ├── keys.ts
│ ├── parseTopLevelYieldStatements.ts
│ ├── polyfills
│ │ ├── ErrorEvent.ts
│ │ ├── Event.ts
│ │ ├── EventTarget.ts
│ │ ├── Promise.withResolvers.ts
│ │ ├── PromiseRejectionEvent.ts
│ │ ├── Worker.ts
│ │ ├── WorkerGlobalScope.ts
│ │ ├── import.meta.resolve.ts
│ │ └── web-worker.ts
│ ├── replaceContents.ts
│ ├── serialize.ts
│ ├── setupWorkerListeners.ts
│ ├── types.d.ts
│ └── worker.worker.ts
└── test.ts
├── test
├── edge-cases.test.js
├── examples.test.js
└── import.test.js
└── tsconfig.json
/.browserslistrc:
--------------------------------------------------------------------------------
1 | defaults and fully supports es6-module
2 | maintained node versions
--------------------------------------------------------------------------------
/.github/workflows/node.js.yml:
--------------------------------------------------------------------------------
1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
3 |
4 | name: Node.js CI
5 |
6 | on:
7 | push:
8 | branches: ["main"]
9 | pull_request:
10 | branches: ["main"]
11 |
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 |
16 | strategy:
17 | matrix:
18 | node-version: [20.x, 21.x]
19 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
20 |
21 | steps:
22 | - uses: actions/checkout@v3
23 | - name: Use Node.js ${{ matrix.node-version }}
24 | uses: actions/setup-node@v3
25 | with:
26 | node-version: ${{ matrix.node-version }}
27 | cache: "npm"
28 | - run: npm ci
29 | - run: npm run build --if-present
30 | - run: npm test
31 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Publish Package to npmjs
2 | on:
3 | release:
4 | types: [published]
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/checkout@v4
10 | - uses: actions/setup-node@v3
11 | with:
12 | node-version: "20.x"
13 | registry-url: "https://registry.npmjs.org"
14 | - run: npm ci
15 | - run: npm publish
16 | env:
17 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | /dist
3 | /.temp
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Walter van der Giessen
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [](https://multithreading.io)
4 |
5 | [](https://github.com/W4G1/multithreading/blob/main/LICENSE.md)
6 | [](https://www.npmjs.com/package/multithreading)
7 | [](https://www.npmjs.com/package/multithreading?activeTab=versions)
8 | [&color=rgb(13%2C%2017%2C%2023))](https://github.com/W4G1/multithreading)
9 | [](https://github.com/W4G1/multithreading/actions/workflows/node.js.yml)
10 |
11 |
12 |
13 | # multithreading
14 |
15 | Multithreading is a tiny runtime that allows you to execute JavaScript functions on separate threads. It is designed to be as simple and fast as possible, and to be used in a similar way to regular functions.
16 |
17 | With a minified size of only 4.5kb, it has first class support for [Node.js](https://nodejs.org/), [Deno](https://deno.com/) and the [browser](https://caniuse.com/?search=webworkers). It can also be used with any framework or library such as [React](https://react.dev/), [Vue](https://vuejs.org/) or [Svelte](https://svelte.dev/).
18 |
19 | Depending on the environment, it uses [Worker Threads](https://nodejs.org/api/worker_threads.html) or [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker). In addition to [ES6 generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) to make multithreading as simple as possible.
20 |
21 | ### The State of Multithreading in JavaScript
22 |
23 | JavaScript's single-threaded nature means that tasks are executed one after the other, leading to potential performance bottlenecks and underutilized CPU resources. While [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Worker) and [Worker Threads](https://nodejs.org/api/worker_threads.html) offer a way to offload tasks to separate threads, managing the state and communication between these threads is often complex and error-prone.
24 |
25 | This project aims to solve these challenges by providing an intuitive Web Worker abstraction that mirrors the behavior of regular JavaScript functions.
26 | This way it feels like you're executing a regular function, but in reality, it's running in parallel on a separate threads.
27 |
28 | ## Installation
29 |
30 | ```bash
31 | npm install multithreading
32 | ```
33 |
34 | ## Usage
35 |
36 | #### Basic example
37 |
38 | ```js
39 | import { threaded } from "multithreading";
40 |
41 | const add = threaded(function* (a, b) {
42 | return a + b;
43 | });
44 |
45 | console.log(await add(5, 10)); // 15
46 | ```
47 | The `add` function is executed on a separate thread, and the result is returned to the main thread when the function is done executing. Consecutive invocations will be automatically executed in parallel on separate threads.
48 |
49 | #### Example with shared state
50 |
51 | ```js
52 | import { threaded, $claim, $unclaim } from "multithreading";
53 |
54 | const user = {
55 | name: "john",
56 | balance: 0,
57 | };
58 |
59 | const add = threaded(async function* (amount) {
60 | yield user; // Add user to dependencies
61 |
62 | await $claim(user); // Wait for write lock
63 |
64 | user.balance += amount;
65 |
66 | $unclaim(user); // Release write lock
67 | });
68 |
69 | await Promise.all([
70 | add(5),
71 | add(10),
72 | ]);
73 |
74 | console.log(user.balance); // 15
75 | ```
76 | This example shows how to use a shared state across multiple threads. It introduces the concepts of claiming and unclaiming write access using `$claim` and `$unclaim`. This is to ensure that only one thread can write to a shared state at a time.
77 |
78 | > Always `$unclaim()` a shared state after use, otherwise the write lock will never be released and other threads that want to write to this state will be blocked indefinitely.
79 |
80 | The `yield` statement is used to specify external dependencies, and must be defined at the top of the function.
81 |
82 | #### Example with external functions
83 |
84 | ```js
85 | import { threaded, $claim, $unclaim } from "multithreading";
86 |
87 | // Some external function
88 | function add (a, b) {
89 | return a + b;
90 | }
91 |
92 | const user = {
93 | name: "john",
94 | balance: 0,
95 | };
96 |
97 | const addBalance = threaded(async function* (amount) {
98 | yield user;
99 | yield add; // Add external function to dependencies
100 |
101 | await $claim(user);
102 |
103 | user.balance = add(user.balance, amount);
104 |
105 | $unclaim(user);
106 | });
107 |
108 |
109 | await Promise.all([
110 | addBalance(5),
111 | addBalance(10),
112 | ]);
113 |
114 | console.log(user.balance); // 15
115 | ```
116 | In this example, the `add` function is used within the multithreaded `addBalance` function. The `yield` statement is used to declare external dependencies. You can think of it as a way to import external data, functions or even packages.
117 |
118 | As with previous examples, the shared state is managed using `$claim` and `$unclaim` to guarantee proper synchronization and prevent data conflicts.
119 |
120 | > External functions like `add` cannot have external dependencies themselves. All variables and functions used by an external function must be declared within the function itself.
121 |
122 | ### Using imports from external packages
123 |
124 | When using external modules, you can dynamically import them by using `yield "some-package"`. This is useful when you want to use other packages within a threaded function.
125 |
126 | ```js
127 | import { threaded } from "multithreading";
128 |
129 | const getId = threaded(function* () {
130 | /**
131 | * @type {import("uuid")}
132 | */
133 | const { v4 } = yield "uuid"; // Import other package
134 |
135 | return v4();
136 | }
137 |
138 | console.log(await getId()); // 1a107623-3052-4f61-aca9-9d9388fb2d81
139 | ```
140 |
141 | You can also import external modules in a variety of other ways:
142 | ```js
143 | const { v4 } = yield "npm:uuid"; // Using npm specifier (available in Deno)
144 | const { v4 } = yield "https://esm.sh/uuid"; // From CDN url (available in browser and Deno)
145 | ```
146 |
147 | ## Enhanced Error Handling
148 | Errors inside threads are automatically injected with a pretty stack trace.
149 | This makes it easier to identify which line of your function caused the error, and in which thread the error occured.
150 |
151 | 
152 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('jest').Config} */
2 | module.exports = {
3 | // verbose: true,
4 | rootDir: "./test",
5 | };
6 |
--------------------------------------------------------------------------------
/node_test.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | /** @type {import('./src/index.ts').threaded} */
4 | const threaded = require("./dist/index.js").threaded;
5 | /** @type {import('./src/index.ts').$unclaim}*/
6 | const $unclaim = require("./dist/index.js").$unclaim;
7 | /** @type {import('./src/index.ts').$claim}*/
8 | const $claim = require("./dist/index.js").$claim;
9 |
10 | function add(a, b) {
11 | return a + b;
12 | }
13 |
14 | async function main() {
15 | const add = threaded(function* (a, b) {
16 | return a + b;
17 | });
18 |
19 | console.log(await add(5, 10)); // 15
20 |
21 | // const user = {
22 | // name: "john",
23 | // balance: 100,
24 | // };
25 |
26 | // const addBalance = threaded(async function* (amount) {
27 | // yield { user, add };
28 |
29 | // await $claim(user);
30 |
31 | // // Thread now has ownership over user and is
32 | // // guaranteed not to change by other threads
33 | // user.balance = add(user.balance, amount);
34 |
35 | // $unclaim(user);
36 |
37 | // return user;
38 | // });
39 |
40 | // await Promise.all([
41 | // addBalance(10),
42 | // addBalance(10),
43 | // addBalance(10),
44 | // addBalance(10),
45 | // addBalance(10),
46 | // addBalance(10),
47 | // addBalance(10),
48 | // addBalance(10),
49 | // addBalance(10),
50 | // addBalance(10),
51 | // ]);
52 |
53 | // console.assert(user.balance === 200, "Balance should be 200");
54 |
55 | // console.log("Result in main:", user);
56 |
57 | // addBalance.dispose();
58 | }
59 |
60 | main();
61 |
--------------------------------------------------------------------------------
/nodemon.json:
--------------------------------------------------------------------------------
1 | {
2 | "watch": ["."],
3 | "ext": "js,ts,json",
4 | "ignore": [".temp", "dist", ".rollup.cache"],
5 | "exec": "rollup -c rollup.config.worker.dev.js --configPlugin @rollup/plugin-swc && rollup -c rollup.config.dev.js --configPlugin @rollup/plugin-swc && node ./node_test.js"
6 | }
7 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "multithreading",
3 | "version": "0.2.1",
4 | "description": "⚡ Multithreading functions in JavaScript to speedup heavy workloads, designed to feel like writing vanilla functions.",
5 | "author": "Walter van der Giessen ",
6 | "homepage": "https://multithreading.io",
7 | "license": "MIT",
8 | "keywords": [
9 | "multithreading",
10 | "threads",
11 | "webworkers",
12 | "parallel",
13 | "concurrent",
14 | "concurrency",
15 | "web-workers",
16 | "worker-threads"
17 | ],
18 | "types": "./dist/index.d.ts",
19 | "module": "./dist/index.mjs",
20 | "main": "./dist/index.js",
21 | "exports": {
22 | "types": "./dist/index.d.ts",
23 | "import": "./dist/index.mjs",
24 | "require": "./dist/index.js"
25 | },
26 | "files": [
27 | "dist/"
28 | ],
29 | "repository": {
30 | "type": "git",
31 | "url": "git+https://github.com/W4G1/multithreading.git"
32 | },
33 | "publishConfig": {
34 | "access": "public"
35 | },
36 | "engines": {
37 | "node": ">=20"
38 | },
39 | "devDependencies": {
40 | "@babel/plugin-transform-runtime": "^7.24.0",
41 | "@babel/preset-env": "^7.24.0",
42 | "@babel/preset-typescript": "^7.23.3",
43 | "@rollup/plugin-babel": "^6.0.4",
44 | "@rollup/plugin-inject": "^5.0.5",
45 | "@rollup/plugin-node-resolve": "^15.2.3",
46 | "@rollup/plugin-replace": "^5.0.5",
47 | "@rollup/plugin-swc": "^0.3.0",
48 | "@rollup/plugin-terser": "^0.4.4",
49 | "@types/node": "^20.11.26",
50 | "cross-env": "^7.0.3",
51 | "jest": "^29.7.0",
52 | "nodemon": "^3.1.0",
53 | "rimraf": "^5.0.5",
54 | "rollup": "^4.13.0",
55 | "rollup-plugin-ts": "^3.4.5",
56 | "tslib": "^2.6.2",
57 | "typescript": "^5.4.2",
58 | "uuid": "^9.0.1"
59 | },
60 | "scripts": {
61 | "build:worker": "rimraf .temp && rollup -c rollup.config.worker.js --configPlugin @rollup/plugin-swc",
62 | "build": "npm run build:worker && rollup -c rollup.config.js --configPlugin @rollup/plugin-swc && rimraf .temp",
63 | "dev": "nodemon",
64 | "prepublishOnly": "npm run build",
65 | "test": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest"
66 | },
67 | "bugs": {
68 | "url": "https://github.com/W4G1/multithreading/issues"
69 | },
70 | "optionalDependencies": {
71 | "@rollup/rollup-linux-x64-gnu": "^4.13.0"
72 | }
73 | }
--------------------------------------------------------------------------------
/rollup.config.dev.js:
--------------------------------------------------------------------------------
1 | import terser from "@rollup/plugin-terser";
2 | import replace from "@rollup/plugin-replace";
3 | import fs from "node:fs";
4 | import swc from "@rollup/plugin-swc";
5 |
6 | const bundleResolve = {
7 | esm: "import.meta.resolve",
8 | cjs: "require.resolve",
9 | };
10 |
11 | export default ["cjs"].flatMap((type) => {
12 | const ext = type === "esm" ? "mjs" : "js";
13 | return [""].map(
14 | (version) =>
15 | /** @type {import('rollup').RollupOptions} */ ({
16 | input: `src/index.ts`,
17 | treeshake: version === ".min",
18 |
19 | plugins: [
20 | swc(),
21 | replace({
22 | __INLINE_WORKER__: fs
23 | .readFileSync(`.temp/worker.${type}${version}.js`, "utf8")
24 | .replaceAll("\\", "\\\\")
25 | .replaceAll("`", "\\`")
26 | .replaceAll("$", "\\$"),
27 | }),
28 | {
29 | resolveImportMeta(prop, { format }) {
30 | if (prop === "resolve") {
31 | return bundleResolve[format];
32 | }
33 | },
34 | },
35 | ],
36 | output: [
37 | {
38 | file: `dist/index.${ext}`,
39 | format: type,
40 | sourcemap: false,
41 | name: "multithreading",
42 | dynamicImportInCjs: true,
43 | globals: {
44 | "web-worker": "Worker",
45 | },
46 | plugins: [...(version === ".min" ? [terser()] : [])],
47 | },
48 | ],
49 | })
50 | );
51 | });
52 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import resolve from "@rollup/plugin-node-resolve";
2 | import terser from "@rollup/plugin-terser";
3 | import babel from "@rollup/plugin-babel";
4 | import replace from "@rollup/plugin-replace";
5 | import swc from "@rollup/plugin-swc";
6 | import fs from "node:fs";
7 | import ts from "rollup-plugin-ts";
8 |
9 | const bundleResolve = {
10 | esm: "import.meta.resolve",
11 | cjs: "require.resolve",
12 | };
13 |
14 | export default ["esm", "cjs"].flatMap((type) => {
15 | const ext = type === "esm" ? "mjs" : "js";
16 | return ["", ".min"].map(
17 | (version) =>
18 | /** @type {import('rollup').RollupOptions} */ ({
19 | input: `src/index.ts`,
20 | treeshake: version === ".min",
21 | plugins: [
22 | ...(type === "cjs" && version === ""
23 | ? [
24 | ts({
25 | browserslist: false,
26 | transpileOnly: true,
27 | }),
28 | ]
29 | : []),
30 | swc(),
31 | resolve(),
32 | babel({
33 | babelHelpers: "bundled",
34 | include: ["src/**/*.ts"],
35 | extensions: [".js", ".ts"],
36 | exclude: ["./node_modules/**"],
37 | }),
38 | replace({
39 | __INLINE_WORKER__: fs
40 | .readFileSync(`.temp/worker.${type}${version}.js`, "utf8")
41 | .replaceAll("\\", "\\\\")
42 | .replaceAll("`", "\\`")
43 | .replaceAll("$", "\\$"),
44 | }),
45 | {
46 | resolveImportMeta(prop, { format }) {
47 | if (prop === "resolve") {
48 | return bundleResolve[format];
49 | }
50 | },
51 | },
52 | ],
53 |
54 | output: [
55 | {
56 | file: `dist/index${version}.${ext}`,
57 | format: type,
58 | sourcemap: false,
59 | name: "multithreading",
60 | dynamicImportInCjs: true,
61 | globals: {
62 | "web-worker": "Worker",
63 | },
64 | plugins: [
65 | ...(version === ".min"
66 | ? [
67 | terser({
68 | compress: {
69 | toplevel: true,
70 | passes: 2,
71 | },
72 | mangle: {},
73 | }),
74 | ]
75 | : []),
76 | ],
77 | },
78 | ],
79 | })
80 | );
81 | });
82 |
--------------------------------------------------------------------------------
/rollup.config.worker.dev.js:
--------------------------------------------------------------------------------
1 | import swc from "@rollup/plugin-swc";
2 |
3 | /** @type {import('rollup').RollupOptions[]} */
4 | export default [
5 | {
6 | input: `src/lib/worker.worker.ts`,
7 | plugins: [swc()],
8 | output: [
9 | {
10 | file: ".temp/worker.cjs.js",
11 | format: "cjs",
12 | sourcemap: false,
13 | dynamicImportInCjs: true,
14 | name: "multithreading",
15 | },
16 | ],
17 | },
18 | ];
19 |
--------------------------------------------------------------------------------
/rollup.config.worker.js:
--------------------------------------------------------------------------------
1 | import resolve from "@rollup/plugin-node-resolve";
2 | import terser from "@rollup/plugin-terser";
3 | import babel from "@rollup/plugin-babel";
4 |
5 | /** @type {import('rollup').RollupOptions[]} */
6 | export default [
7 | {
8 | input: `src/lib/worker.worker.ts`,
9 | plugins: [
10 | resolve(),
11 | babel({
12 | babelHelpers: "bundled",
13 | include: ["src/**/*.ts"],
14 | extensions: [".js", ".ts"],
15 | exclude: ["./node_modules/**"],
16 | presets: ["@babel/typescript"],
17 | }),
18 | ],
19 | output: [
20 | {
21 | file: ".temp/worker.esm.js",
22 | format: "esm",
23 | sourcemap: false,
24 | name: "multithreading",
25 | },
26 | {
27 | file: ".temp/worker.esm.min.js",
28 | format: "esm",
29 | sourcemap: false,
30 | plugins: [
31 | terser({
32 | compress: {
33 | toplevel: true,
34 | passes: 3,
35 | },
36 | }),
37 | ],
38 | name: "multithreading",
39 | },
40 | {
41 | file: ".temp/worker.cjs.js",
42 | format: "cjs",
43 | sourcemap: false,
44 | dynamicImportInCjs: true,
45 | name: "multithreading",
46 | },
47 | {
48 | file: ".temp/worker.cjs.min.js",
49 | format: "cjs",
50 | sourcemap: false,
51 | dynamicImportInCjs: true,
52 | plugins: [
53 | terser({
54 | compress: {
55 | toplevel: true,
56 | passes: 2,
57 | },
58 | mangle: {},
59 | }),
60 | ],
61 | name: "multithreading",
62 | },
63 | ],
64 | },
65 | ];
66 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import "./lib/polyfills/Promise.withResolvers.ts";
2 | import "./lib/polyfills/import.meta.resolve.ts";
3 | import "./lib/polyfills/web-worker.ts";
4 |
5 | import { serialize } from "./lib/serialize.ts";
6 | import * as $ from "./lib/keys.ts";
7 | import { MainEvent, UserFunction } from "./lib/types";
8 | import { setupWorkerListeners } from "./lib/setupWorkerListeners.ts";
9 | import { parseTopLevelYieldStatements } from "./lib/parseTopLevelYieldStatements.ts";
10 |
11 | const inlineWorker = `__INLINE_WORKER__`;
12 |
13 | export async function $claim(value: Object) {}
14 | export function $unclaim(value: Object) {}
15 |
16 | const workerPools = new WeakMap();
17 | const valueOwnershipQueue = new WeakMap