├── .github └── workflows │ └── main.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── src ├── browser │ └── index.js └── node │ └── index.js ├── test ├── fixtures │ ├── close.mjs │ ├── importscripts-2.cjs │ ├── importscripts.cjs │ ├── other.mjs │ └── worker.mjs └── index.test.js ├── tsup.config.js └── types ├── index.d.cts └── index.d.ts /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | node: [16, 18, 20, 22] 11 | name: Node ${{ matrix.node }} sample 12 | steps: 13 | - uses: actions/checkout@v4 14 | - name: Setup node 15 | uses: actions/setup-node@v4 16 | with: 17 | node-version: ${{ matrix.node }} 18 | env: 19 | CI: true 20 | - run: npm install 21 | - run: npm run prepare --if-present 22 | - run: npm test 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution; 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows 28 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | web-worker 3 | npm 4 |

5 |

6 | Native cross-platform Web Workers. Works in published npm modules. 7 |

8 |

9 | 10 |

11 | 12 | **In Node**, it's a web-compatible Worker implementation atop Node's [worker_threads](https://nodejs.org/api/worker_threads.html). 13 | 14 | **In the browser** (and when bundled for the browser), it's simply an alias of `Worker`. 15 | 16 | ### Features 17 | 18 | _Here's how this is different from worker_threads:_ 19 | 20 | - makes Worker code compatible across browser and Node 21 | - supports Module Workers (`{type:'module'}`) natively in Node 12.8+ 22 | - uses DOM-style events (`Event.data`, `Event.type`, etc) 23 | - supports event handler properties (`worker.onmessage=..`) 24 | - `Worker()` accepts a module URL, Blob URL or Data URL 25 | - emulates browser-style [WorkerGlobalScope] within the worker 26 | 27 | ### Usage Example 28 | 29 | In its simplest form: 30 | 31 | ```js 32 | import Worker from 'web-worker'; 33 | 34 | const worker = new Worker('data:,postMessage("hello")'); 35 | worker.onmessage = e => console.log(e.data); // "hello" 36 | ``` 37 | 38 | 39 | 40 | 66 |
main.jsworker.js
41 | 42 | ```js 43 | import Worker from 'web-worker'; 44 | 45 | const url = new URL('./worker.js', import.meta.url); 46 | const worker = new Worker(url); 47 | 48 | worker.addEventListener('message', e => { 49 | console.log(e.data) // "hiya!" 50 | }); 51 | 52 | worker.postMessage('hello'); 53 | ``` 54 | 55 | 56 | 57 | ```js 58 | addEventListener('message', e => { 59 | if (e.data === 'hello') { 60 | postMessage('hiya!'); 61 | } 62 | }); 63 | ``` 64 | 65 |
67 | 68 | 👉 Notice how `new URL('./worker.js', import.meta.url)` is used above to load the worker relative to the current module instead of the application base URL. Without this, Worker URLs are relative to a document's URL, which in Node.js is interpreted to be `process.cwd()`. 69 | 70 | > _Support for this pattern in build tools and test frameworks is still limited. We are [working on growing this](https://github.com/developit/web-worker/issues/4)._ 71 | 72 | ### Module Workers 73 | 74 | Module Workers are supported in Node 12.8+ using this plugin, leveraging Node's native ES Modules support. 75 | In the browser, they can be used natively in Chrome 80+, or in all browsers via [worker-plugin] or [rollup-plugin-off-main-thread]. As with classic workers, there is no difference in usage between Node and the browser: 76 | 77 | 78 | 79 | 108 |
main.mjsworker.mjs
80 | 81 | ```js 82 | import Worker from 'web-worker'; 83 | 84 | const worker = new Worker( 85 | new URL('./worker.mjs', import.meta.url), 86 | { type: 'module' } 87 | ); 88 | worker.addEventListener('message', e => { 89 | console.log(e.data) // "200 OK" 90 | }); 91 | worker.postMessage('https://httpstat.us/200'); 92 | ``` 93 | 94 | 95 | 96 | ```js 97 | import fetch from 'isomorphic-fetch'; 98 | 99 | addEventListener('message', async e => { 100 | const url = e.data; 101 | const res = await fetch(url) 102 | const text = await res.text(); 103 | postMessage(text); 104 | }); 105 | ``` 106 | 107 |
109 | 110 | 111 | ### Data URLs 112 | 113 | Instantiating Worker using a Data URL is supported in both module and classic workers: 114 | 115 | ```js 116 | import Worker from 'web-worker'; 117 | 118 | const worker = new Worker(`data:application/javascript,postMessage(42)`); 119 | worker.addEventListener('message', e => { 120 | console.log(e.data) // 42 121 | }); 122 | ``` 123 | 124 | ### Special Thanks 125 | 126 | This module aims to provide a simple and forgettable piece of infrastructure, 127 | and as such it needed an obvious and descriptive name. 128 | [@calvinmetcalf](https://github.com/calvinmetcalf), who you may recognize as the author of [Lie](https://github.com/calvinmetcalf/lie) and other fine modules, gratiously offered up the name from his `web-worker` package. 129 | Thanks Calvin! 130 | 131 | 132 | [worker-plugin]: https://github.com/googlechromelabs/worker-plugin 133 | [rollup-plugin-off-main-thread]: https://github.com/surma/rollup-plugin-off-main-thread 134 | [WorkerGlobalScope]: https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope 135 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "web-worker", 3 | "version": "1.5.0", 4 | "description": "Consistent Web Workers in browser and Node.", 5 | "main": "./dist/browser/index.cjs", 6 | "browser": "./dist/browser/index.cjs", 7 | "types": "./types/index.d.cts", 8 | "type": "module", 9 | "exports": { 10 | "import": { 11 | "types": "./types/index.d.ts", 12 | "bun": "./src/browser/index.js", 13 | "browser": "./src/browser/index.js", 14 | "default": "./src/node/index.js" 15 | }, 16 | "module": { 17 | "types": "./types/index.d.ts", 18 | "bun": "./src/browser/index.js", 19 | "browser": "./src/browser/index.js", 20 | "default": "./src/node/index.js" 21 | }, 22 | "default": { 23 | "types": "./types/index.d.cts", 24 | "bun": "./dist/browser/index.cjs", 25 | "browser": "./dist/browser/index.cjs", 26 | "default": "./dist/node/index.cjs" 27 | } 28 | }, 29 | "files": [ 30 | "dist", 31 | "src", 32 | "types" 33 | ], 34 | "scripts": { 35 | "prepare": "tsup", 36 | "test": "eslint '*.js' test && node --experimental-modules ./node_modules/.bin/ava" 37 | }, 38 | "repository": "developit/web-worker", 39 | "keywords": [ 40 | "worker", 41 | "worker_threads", 42 | "webworker", 43 | "web worker", 44 | "web-worker", 45 | "threads" 46 | ], 47 | "authors": [], 48 | "license": "Apache-2.0", 49 | "homepage": "https://github.com/developit/web-worker", 50 | "eslintConfig": { 51 | "extends": "developit", 52 | "rules": { 53 | "no-console": 0 54 | } 55 | }, 56 | "devDependencies": { 57 | "ava": "^6.2.0", 58 | "eslint": "^7.32.0", 59 | "eslint-config-developit": "^1.2.0", 60 | "eslint-plugin-compat": "^4.2.0", 61 | "tsup": "^8.0.2" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/browser/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export default typeof Worker !== 'undefined' ? Worker : undefined; 18 | -------------------------------------------------------------------------------- /src/node/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { URL, fileURLToPath, pathToFileURL } from 'url'; 18 | import path from 'path'; 19 | import fs from 'fs'; 20 | import VM from 'vm'; 21 | import threads from 'worker_threads'; 22 | 23 | const WORKER = Symbol.for('worker'); 24 | const EVENTS = Symbol.for('events'); 25 | 26 | class EventTarget { 27 | constructor() { 28 | Object.defineProperty(this, EVENTS, { 29 | value: new Map() 30 | }); 31 | } 32 | dispatchEvent(event) { 33 | event.target = event.currentTarget = this; 34 | if (this['on'+event.type]) { 35 | try { 36 | this['on'+event.type](event); 37 | } 38 | catch (err) { 39 | console.error(err); 40 | } 41 | } 42 | const list = this[EVENTS].get(event.type); 43 | if (list == null) return; 44 | list.forEach(handler => { 45 | try { 46 | handler.call(this, event); 47 | } 48 | catch (err) { 49 | console.error(err); 50 | } 51 | }); 52 | } 53 | addEventListener(type, fn) { 54 | let events = this[EVENTS].get(type); 55 | if (!events) this[EVENTS].set(type, events = []); 56 | events.push(fn); 57 | } 58 | removeEventListener(type, fn) { 59 | let events = this[EVENTS].get(type); 60 | if (events) { 61 | const index = events.indexOf(fn); 62 | if (index !== -1) events.splice(index, 1); 63 | } 64 | } 65 | } 66 | 67 | function Event(type, target) { 68 | this.type = type; 69 | this.timeStamp = Date.now(); 70 | this.target = this.currentTarget = this.data = null; 71 | } 72 | 73 | // this module is used self-referentially on both sides of the 74 | // thread boundary, but behaves differently in each context. 75 | export default typeof Worker === 'function' ? Worker : threads.isMainThread ? mainThread() : workerThread(); 76 | 77 | const baseUrl = pathToFileURL(process.cwd() + '/'); 78 | 79 | function mainThread() { 80 | 81 | /** 82 | * A web-compatible Worker implementation atop Node's worker_threads. 83 | * - uses DOM-style events (Event.data, Event.type, etc) 84 | * - supports event handler properties (worker.onmessage) 85 | * - Worker() constructor accepts a module URL 86 | * - accepts the {type:'module'} option 87 | * - emulates WorkerGlobalScope within the worker 88 | * @param {string} url The URL or module specifier to load 89 | * @param {object} [options] Worker construction options 90 | * @param {string} [options.name] Available as `self.name` within the Worker 91 | * @param {string} [options.type="classic"] Pass "module" to create a Module Worker. 92 | */ 93 | class Worker extends EventTarget { 94 | constructor(url, options) { 95 | super(); 96 | const { name, type } = options || {}; 97 | url += ''; 98 | let mod; 99 | if (/^data:/.test(url)) { 100 | mod = url; 101 | } 102 | else { 103 | mod = fileURLToPath(new URL(url, baseUrl)); 104 | } 105 | const worker = new threads.Worker( 106 | fileURLToPath(import.meta.url), 107 | { workerData: { mod, name, type } } 108 | ); 109 | Object.defineProperty(this, WORKER, { 110 | value: worker 111 | }); 112 | worker.on('message', data => { 113 | const event = new Event('message'); 114 | event.data = data; 115 | this.dispatchEvent(event); 116 | }); 117 | worker.on('error', error => { 118 | error.type = 'error'; 119 | this.dispatchEvent(error); 120 | }); 121 | worker.on('exit', () => { 122 | this.dispatchEvent(new Event('close')); 123 | }); 124 | } 125 | postMessage(data, transferList) { 126 | this[WORKER].postMessage(data, transferList); 127 | } 128 | terminate() { 129 | this[WORKER].terminate(); 130 | } 131 | } 132 | Worker.prototype.onmessage = Worker.prototype.onerror = Worker.prototype.onclose = null; 133 | return Worker; 134 | } 135 | 136 | function workerThread() { 137 | // loaded in a real Web Worker (eg: on Electron) 138 | if (typeof global.WorkerGlobalScope === 'function') { 139 | return; 140 | } 141 | let { mod, name, type } = threads.workerData; 142 | if (!mod) return mainThread(); 143 | 144 | // turn global into a mock WorkerGlobalScope 145 | const self = global.self = global; 146 | 147 | // enqueue messages to dispatch after modules are loaded 148 | let q = []; 149 | function flush() { 150 | const buffered = q; 151 | q = null; 152 | buffered.forEach(event => { self.dispatchEvent(event); }); 153 | } 154 | threads.parentPort.on('message', data => { 155 | const event = new Event('message'); 156 | event.data = data; 157 | if (q == null) self.dispatchEvent(event); 158 | else q.push(event); 159 | }); 160 | threads.parentPort.on('error', err => { 161 | err.type = 'Error'; 162 | self.dispatchEvent(err); 163 | }); 164 | 165 | class WorkerGlobalScope extends EventTarget { 166 | postMessage(data, transferList) { 167 | threads.parentPort.postMessage(data, transferList); 168 | } 169 | // Emulates https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/close 170 | close() { 171 | process.exit(); 172 | } 173 | importScripts() { 174 | for (let i = 0; i < arguments.length; i++) { 175 | const url = arguments[i]; 176 | let code; 177 | if (/^data:/.test(url)) { 178 | code = parseDataUrl(url).data; 179 | } 180 | else { 181 | code = fs.readFileSync( 182 | new URL(path.posix.normalize(url), pathToFileURL(mod)), 183 | 'utf-8' 184 | ); 185 | } 186 | VM.runInThisContext(code, { filename: url }); 187 | } 188 | } 189 | } 190 | let proto = Object.getPrototypeOf(global); 191 | delete proto.constructor; 192 | Object.defineProperties(WorkerGlobalScope.prototype, proto); 193 | proto = Object.setPrototypeOf(global, new WorkerGlobalScope()); 194 | ['postMessage', 'addEventListener', 'removeEventListener', 'dispatchEvent'].forEach(fn => { 195 | proto[fn] = proto[fn].bind(global); 196 | }); 197 | global.name = name; 198 | global.WorkerGlobalScope = WorkerGlobalScope; 199 | 200 | const isDataUrl = /^data:/.test(mod); 201 | if (type === 'module') { 202 | import(isDataUrl ? mod : pathToFileURL(mod)) 203 | .catch(err => { 204 | if (isDataUrl && err.message === 'Not supported') { 205 | console.warn('Worker(): Importing data: URLs requires Node 12.10+. Falling back to classic worker.'); 206 | return evaluateDataUrl(mod, name); 207 | } 208 | console.error(err); 209 | }) 210 | .then(flush); 211 | } 212 | else { 213 | try { 214 | if (/^data:/.test(mod)) { 215 | evaluateDataUrl(mod, name); 216 | } 217 | else { 218 | global.importScripts(mod); 219 | } 220 | } 221 | catch (err) { 222 | console.error(err); 223 | } 224 | Promise.resolve().then(flush); 225 | } 226 | } 227 | 228 | function evaluateDataUrl(url, name) { 229 | const { data } = parseDataUrl(url); 230 | return VM.runInThisContext(data, { 231 | filename: 'worker.<'+(name || 'data:')+'>' 232 | }); 233 | } 234 | 235 | function parseDataUrl(url) { 236 | let [m, type, encoding, data] = url.match(/^data: *([^;,]*)(?: *; *([^,]*))? *,(.*)$/) || []; 237 | if (!m) throw Error('Invalid Data URL.'); 238 | data = decodeURIComponent(data); 239 | if (encoding) switch (encoding.toLowerCase()) { 240 | case 'base64': 241 | data = Buffer.from(data, 'base64').toString(); 242 | break; 243 | default: 244 | throw Error('Unknown Data URL encoding "' + encoding + '"'); 245 | } 246 | return { type, data }; 247 | } 248 | -------------------------------------------------------------------------------- /test/fixtures/close.mjs: -------------------------------------------------------------------------------- 1 | self.close(); 2 | -------------------------------------------------------------------------------- /test/fixtures/importscripts-2.cjs: -------------------------------------------------------------------------------- 1 | postMessage('from importscripts-2.cjs'); 2 | -------------------------------------------------------------------------------- /test/fixtures/importscripts.cjs: -------------------------------------------------------------------------------- 1 | importScripts('./importscripts-2.cjs'); 2 | importScripts('data:application/javascript,postMessage("from data url")'); 3 | -------------------------------------------------------------------------------- /test/fixtures/other.mjs: -------------------------------------------------------------------------------- 1 | export function other() { 2 | return 42; 3 | } -------------------------------------------------------------------------------- /test/fixtures/worker.mjs: -------------------------------------------------------------------------------- 1 | import { other } from './other.mjs'; 2 | 3 | postMessage(other()); 4 | 5 | self.onmessage = e => { 6 | postMessage(['received onmessage', e.timeStamp, e.data]); 7 | }; 8 | 9 | addEventListener('message', e => { 10 | postMessage(['received message event', e.timeStamp, e.data]); 11 | }); 12 | -------------------------------------------------------------------------------- /test/index.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import test from 'ava'; 18 | import Worker from '../dist/node/index.cjs'; 19 | 20 | let worker; 21 | 22 | function createModuleWorker(url, opts) { 23 | const worker = new Worker(url, opts || { type: 'module' }); 24 | worker.events = []; 25 | worker.addEventListener('message', e => { 26 | worker.events.push(e); 27 | }); 28 | return worker; 29 | } 30 | 31 | const sleep = ms => new Promise(r => setTimeout(r, ms)); 32 | 33 | test.after.always(t => { 34 | if (worker) worker.terminate(); 35 | }); 36 | 37 | test.serial('instantiation', async t => { 38 | worker = createModuleWorker('./test/fixtures/worker.mjs'); 39 | await sleep(500); 40 | t.is(worker.events.length, 1, 'should have received a message event'); 41 | t.is(worker.events[0].data, 42); 42 | }); 43 | 44 | test.serial('postMessage', async t => { 45 | // reset events list 46 | worker.events.length = 0; 47 | 48 | const msg = { greeting: 'hello' }; 49 | worker.postMessage(msg); 50 | const timestamp = Date.now(); 51 | 52 | await sleep(500); 53 | 54 | t.is(worker.events.length, 2, 'should have received two message responses'); 55 | 56 | const first = worker.events[0]; 57 | t.is(first.data[0], 'received onmessage'); 58 | t.assert(Math.abs(timestamp - first.data[1]) < 500); 59 | t.deepEqual(first.data[2], msg); 60 | t.not(first.data[2], msg); 61 | 62 | const second = worker.events[1]; 63 | t.is(second.data[0], 'received message event'); 64 | t.assert(Math.abs(timestamp - second.data[1]) < 500); 65 | t.deepEqual(second.data[2], msg); 66 | t.not(second.data[2], msg); 67 | }); 68 | 69 | test.serial('close', async t => { 70 | const worker = new Worker('./test/fixtures/close.mjs', { type: 'module' }); 71 | // Not emitted in the browser, just for testing 72 | const closed = await new Promise((resolve, reject) => { 73 | worker.addEventListener('close', () => resolve(true)); 74 | setTimeout(reject, 500); 75 | }); 76 | t.is(closed, true, 'should have closed itself'); 77 | }); 78 | 79 | test.serial('data URL - module', async t => { 80 | t.teardown(() => worker && worker.terminate()); 81 | const worker = createModuleWorker('data:application/javascript,postMessage(42)'); 82 | await sleep(500); 83 | t.is(worker.events.length, 1, 'should have received a message event'); 84 | t.is(worker.events[0].data, 42); 85 | }); 86 | 87 | test.serial('data URL - classic', async t => { 88 | t.teardown(() => worker && worker.terminate()); 89 | const worker = createModuleWorker('data:application/javascript,postMessage(42)', {}); 90 | await sleep(500); 91 | t.is(worker.events.length, 1, 'should have received a message event'); 92 | t.is(worker.events[0].data, 42); 93 | }); 94 | 95 | test.serial('importScripts', async t => { 96 | t.teardown(() => worker && worker.terminate()); 97 | const worker = createModuleWorker('./test/fixtures/importscripts.cjs', {}); 98 | await sleep(500); 99 | t.is(worker.events.length, 2, 'should have received two message events'); 100 | t.is(worker.events[0].data, 'from importscripts-2.cjs'); 101 | t.is(worker.events[1].data, 'from data url'); 102 | }); 103 | -------------------------------------------------------------------------------- /tsup.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'tsup'; 2 | 3 | export default defineConfig((options) => ({ 4 | target: 'es2020', 5 | treeshake: { 6 | preset: 'recommended' 7 | }, 8 | splitting: false, 9 | entry: ['src/**/*.js'], 10 | format: ['cjs'], 11 | dts: false, 12 | minifySyntax: true, 13 | clean: false, 14 | shims: true, 15 | ...options 16 | })); 17 | -------------------------------------------------------------------------------- /types/index.d.cts: -------------------------------------------------------------------------------- 1 | type ConstructorOf = { new (...args: any[]): C }; 2 | 3 | declare const _default: ConstructorOf; 4 | export default _default; 5 | -------------------------------------------------------------------------------- /types/index.d.ts: -------------------------------------------------------------------------------- 1 | type ConstructorOf = { new (...args: any[]): C }; 2 | 3 | declare const _default: ConstructorOf; 4 | export default _default; 5 | --------------------------------------------------------------------------------