Pronounced like the name Rafe, as in:
My uncle, Thrafe lives in the Cayman Islands.
This is a library that aims to make it simple and straightforward to make typesafe, multithreaded web applications (using Typescript and web workers) -- hence the annoying name, Thrafe: threading + typesafe.
When working on my CommunicativeCode webapp, I found it tricky to use both Typescript and web workers for reasons I outline further below.
Additionally, existing awesome worker libraries like Comlink and workway didn't make it easy to accomplish the twoway message passing I needed (i.e. in addition to the main thread talking to the web worker, I also wanted the worker code to be able to talk to the main thread at will*):
MainThread ⇄ Worker
_*= This is probably also possible through passing callbacks using a 'proxy' mechanism in one of these libraries, but that seemed like more indirection than I wanted
Using thrafe requires you to do 4 things (3 development steps, and 1 build step):
- Define your Threading Architecture using types
- Instantiate a Context in your threaded code
- Instantiate a Thread in your client / main thread code
- Add the thrafe generation step in your application's build steps
Check out the specifics of each step below.
This can go in its own .ts
file, or at the top of the worker file, or wherever you want really! It's just a type definition, so will be transpiled away.
An architecture consists of 6 things:
A string literal type definition that defines what this thread should be referred to as, and utlimately the name of the file that is created by the thrafe generator.
For example:
type MyVerySpecialThreadName = "myWorkerThread";
const enum
defining the events where the MAIN THREAD calls into a worker thread
For example:
const enum ToMyVerySpecialThreadEvents {
DoSomeWork,
FactorTheseNumbers
}
blah blah blah
const enum
defining the events where the WORKER THREAD calls into the main thread
blah blah blah
...TBD...
...TBD...
...TBD...
On one side, it's completely unobvious how best to compile & bundle a web worker written in typescript down to a single javascript file so that it can then be executed as a worker in the browser, e.g.:
const worker = new Worker('https://www.my-example-website.com/static/worker.js');
Bundlers are supporting this in different ways, which I think is already confusing.
Vite's solution seems pretty neat, webpack seems to be working on it (not immediately clear to me how this works with typescript), but regardless I don't like how any of the solutions I've seen.