wirejs-web-worker
v1.0.75
Published
An experimental utility for type safe Web Workers.
Readme
⚠️ Experimental Alpha ⚠️
An experimental utility for type safe Web Workers.
npm i wirejs-web-workerFor example, create code you want to run as a worker in a my-worker sub-package:
src/
my-app-code.ts
my-worker/
src/index.ts <-- here
package.json
package.jsonmy-worker/src/index.ts
Let's just count up to some number and report on progress every 50ms.
import { SingleWorker } from 'wirejs-web-worker';
export const worker = SingleWorker({
async count(
upTo: number,
options?: { tick?: (pct: number) => void }
) {
let lastUpdate = new Date();
options?.tick?.(0);
let c = 0;
for (let i = 0; i < upTo; i++) {
let current = new Date();
if (current.getTime() - lastUpdate.getTime() > 50) {
options?.tick?.(i / upTo);
lastUpdate = current;
}
c++;
}
options?.tick?.(1);
return c;
}
});src/my-app-code.ts
The page will just need to import worker from the my-worker sub-package and call worker.count().
import { html, hydrate, text } from 'wirejs-dom/v2';
import { Main } from '../layouts/main.js';
import { worker } from 'my-worker';
async function App() {
return html`<div id='app'>
<h4>Web Worker Demo</h4>
<div>${text('status', '...')}</div>
<div>Web Worker output: ${text('output', '...')}</div>
</div>`.onadd(async self => {
console.log('starting web worker');
self.data.output = (await worker.count(256_000_000, {
tick: pct => self.data.status = `${Math.floor(pct * 100)} % complete.`
})).toString();
});
}
export async function generate() {
return Main({
pageTitle: 'Welcome!',
content: await App()
})
}
hydrate('app', App as any);In this example, we pass a function to the worker (the tick callback). An adapter is injected by wirejs-web-worker during the build that takes care of creating the necessary lookup tables, message passing, and garbage cleanup jobs on both ends of the pipe.
(The overarching framework for this example yet another experimental project. 😅)
my-worker/package.json
To make this work, the worker sub-package must be built using the wirejs-web-worker build script, and the sub-package exports must be explicitly set:
{
"name": "my-worker",
"private": true,
"type": "module",
"exports": {
"types": "./src/index.ts",
"default": "./dist/index.js"
},
"scripts": {
"prebuild": "wirejs-web-worker-build",
"prestart": "npm run prebuild",
"start": "wirejs-scripts watch src npm run prebuild"
}
}This example builds during the prebuild and prestart stage to ensure it is ready for the main package's build and start steps — assuming we're using vanilla workspaces and don't have luxury of dependency-aware build sequencing.
package.json
An example top-level package.json using vanilla workspaces:
{
"name": "sample-app",
"version": "1.0.0",
"private": true,
"type": "module",
"workspaces": [
"src",
"web-worker"
],
"dependencies": {
"wirejs-dom": "^1.0.41",
"wirejs-web-worker": "^1.0.0"
},
"devDependencies": {
"wirejs-scripts": "^3.0.101",
"typescript": "^5.7.3"
},
"scripts": {
"prebuild": "npm run prebuild --workspaces --if-present",
"prestart": "npm run prestart --workspaces --if-present",
"start": "wirejs-scripts ws-run-parallel start",
"build": "npm run build --workspaces --if-present"
}
}In this example, build and prebuild are run across all workspaces. src is treated as a sub-package that contains its own build steps. start runs all workspace start scripts in parallel. All of this ensures the web worker is built and ready when the src code needs it.
Your package.json will probably look different, especially if you're using a build management tool that builds in a dependency-aware manner.
Either way, the end result is magic. 🪄
⚠️ Known Limitations ⚠️
- Only a single export is supported per worker package.
- Worker pools are not yet supported.
- Type-validation on workers is limited.
- Behavior is undefined when exporting non-worker from a worker package.
- No built-in mechanism for killing a worker.
In addition to these known limitations, this code has only been lightly tested and is still experimental.
