Stagehand provides a type-safe means of coordinating communication across an evented message-passing boundary, such as a web worker or a Node.js child process.
The following is a quick example of how you might spin up a child process in Node to perform expensive computations:
// greeting-worker.js;launchnew GreetingWorker;
// main.js;;;;console.loggreeting; // 'Hello, World!'
stagehand module exports three functions:
disconnect. These functions all center around the concept of a
MessageEndpoint, which is the core interface Stagehand uses for communication.
launch<T>(endpoint: MessageEndpoint, implementation: Implementation<T>)
This function is called to expose a backing implementation object across the given endpoint. Typically you'll call this from your child process/web worker/otherwise-somehow-secondary context in order to begin servicing commands from the parent.
In general, all functions on the implementation object passed to
launch will be exposed on the corresponding object on the
connect side, but made async where appropriate. This means that all return values from methods on
implementation will be promises, but also that functions passed in to methods on the backing implementation will be asynchronous as well.
If you're using TypeScript, you'll find this invariant enforced by the signature of
// This is valid:launchendpoint,;// But this is not:launchendpoint,;
connect<T>(endpoint: MessageEndpoint): Promise<Remote<T>>
This function is called to connect to a backing implementation that was set up on the other end of the given message endpoint. It returns a promise that will ultimately resolve to a value that exposes the same methods as the backing implementation.
When calling these methods, their results will always be promises that resolve or reject based on the return value or thrown execption when that method is called on the implementation side.
Disconnects the given stagehand worker, clearing any saved state on both ends and calling
disconnect on both halves of the corresponding
MessageEndpoint is any object with the following three methods:
onMessage(callback: (message: unknown) => void): void
sendMessage(message: unknown): void
Several adapters for converting common communication objects to this type are included in this library:
stagehand/lib/adapters/child-processcreates endpoints for communicating to/from processes spawned with Node.js's
fork(see the example above)
stagehand/lib/adapters/web-workercreates endpoints for communicating to /from web workers
stagehand/lib/adapters/in-memorycreate endpoints from scratch that both exist within the same process (mostly useful for testing)
These adapter modules also generally expose specialized versions of
connect that accept appropriate objects for the domain they deal with and internally convert them using the endpoint adapters also defined there.