@design.estate/dees-comms
Typed messaging between the tabs, frames and workers of one origin over a BroadcastChannel: typed requests that expect an answer, and typed events that do not.
Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.
Install
pnpm add @design.estate/dees-comms
Usage
Channels
Every DeesComms instance talks on one BroadcastChannel. Instances hear each other only when they use the same channel name, in any tab, frame or worker of the same origin.
import { DeesComms } from '@design.estate/dees-comms';
// the default channel, 'dees-comms'
const comms = new DeesComms();
// a channel of this application's own
const appComms = new DeesComms({ channelName: 'my-app' });
console.log(DeesComms.defaultChannelName); // 'dees-comms'
console.log(appComms.channelName); // 'my-app'
An instance created without a name uses DeesComms.defaultChannelName, the channel every instance used before names existed. Other packages talk on it: DomTools of @design.estate/dees-domtools opens an instance on it, and the service worker of @api.global/typedserver exchanges its messages with its pages there. Give your application's messages a channel of their own, so that they neither reach nor disturb that traffic.
The platform's BroadcastChannel is used wherever there is one (browsers, workers, Node.js); elsewhere the broadcast-channel package stands in for it.
Typed requests
A typed request goes to every other instance on the channel; an instance with a handler for its method answers it.
import { DeesComms } from '@design.estate/dees-comms';
import type { ITypedRequest } from '@api.global/typedrequest-interfaces';
interface IGreetRequest extends ITypedRequest {
method: 'greet';
request: {
name: string;
};
response: {
reply: string;
};
}
// in one tab or worker
const answering = new DeesComms({ channelName: 'my-app' });
answering.createTypedHandler<IGreetRequest>('greet', async (request) => {
return { reply: `Hello ${request.name}, nice to meet you!` };
});
// in another one
const asking = new DeesComms({ channelName: 'my-app' });
const response = await asking.createTypedRequest<IGreetRequest>('greet').fire({ name: 'Alice' });
console.log(response.reply); // 'Hello Alice, nice to meet you!'
postMessage() posts a typed request object as it is; typedrouter and typedtarget are the @api.global/typedrequest 9 router and target the instance routes with. A handler answers with what it returns, false, 0 and '' included; a handler that returns nothing answers response: null.
- Every other instance on the channel hears a request, but only one with a handler for its method answers it; the others stay silent. When several instances have a handler for it, the first answer to arrive is the response and the later ones are dropped.
- An instance has at most one handler per method:
createTypedHandler()rejects a second one. - The instance that fires a request does not answer it itself, even when it has a handler for its method.
Waiting for the answer
A request waits 30 seconds for its answer by default. responseTimeoutMs sets that limit for every request an instance fires; it must be a whole number of milliseconds from 1 to 2147483647, or the constructor throws a RangeError. A request that reaches the limit rejects with an Error (TypedTarget response timed out after …ms).
A single request can wait less with timeoutMs, and its caller can cancel it with an AbortSignal:
import { DeesComms, TypedRequestTimeoutError } from '@design.estate/dees-comms';
const asking = new DeesComms({ channelName: 'my-app', responseTimeoutMs: 10_000 });
const greet = asking.createTypedRequest<IGreetRequest>('greet');
try {
await greet.fire({ name: 'Alice' }, { timeoutMs: 1_000 });
} catch (error) {
if (error instanceof TypedRequestTimeoutError) {
console.log(`nobody answered within ${error.timeoutMs} ms`);
}
}
const controller = new AbortController();
const pending = greet.fire({ name: 'Bob' }, { abortSignal: controller.signal });
controller.abort(new Error('the tab is closing'));
await pending.catch((reason) => console.log(reason.message)); // 'the tab is closing'
- A request with its own
timeoutMsends at the earlier of its own deadline and the instance'sresponseTimeoutMs, and rejects with aTypedRequestTimeoutError(carryingtimeoutMs) when its own deadline comes first. - An aborted request rejects with the signal's reason at once. A request fired with a signal that is already aborted is never sent. A handler that is already working on an aborted request still finishes; its answer is dropped.
Refusing a request
A handler refuses a request by throwing a TypedResponseError. Its caller rejects with that error at once, with its errorText and errorData, instead of waiting for its timeout:
import { DeesComms, TypedResponseError } from '@design.estate/dees-comms';
answering.createTypedHandler<IGreetRequest>('greet', async (request) => {
if (request.name === '') {
throw new TypedResponseError('name-required', { field: 'name' });
}
return { reply: `Hello ${request.name}, nice to meet you!` };
});
try {
await asking.createTypedRequest<IGreetRequest>('greet').fire({ name: '' });
} catch (error) {
if (error instanceof TypedResponseError) {
console.log(error.errorText, error.errorData); // 'name-required' { field: 'name' }
}
}
- A handler that throws any other error answers with a
TypedResponseErrorwhoseerrorTextisInternal server error; the error itself does not travel. - A refusal is an answer: when several instances have a handler for the method, the first answer wins, whether it is a response or a refusal. An instance that cannot help but wants to leave the request to the others removes its handler instead of refusing.
TypedResponseErrorandTypedRequestTimeoutErrorare exported by@design.estate/dees-commsand are the classes of the@api.global/typedrequestit routes with. Use these exports forinstanceof: an application that depends on another version of@api.global/typedrequesthas classes of its own that the errors are not instances of.
Removing a handler
createTypedHandler() resolves with a handle whose remove() stops the handler:
const handler = await answering.createTypedHandler<IGreetRequest>('greet', async (request) => {
return { reply: `Hello ${request.name}!` };
});
// later: the requests are left to the other instances
handler.remove();
A request that arrives after remove() is left to the other instances, as if this one never had the handler; one the handler is working on still gets its answer. The method can be handled again with a new createTypedHandler(). Calling remove() again does nothing.
Typed events
A typed event is sent to every other instance on the channel and expects no answer. It is declared as an ITypedEvent of @api.global/typedrequest-interfaces: its name is the contract, its payload is what travels.
import { DeesComms } from '@design.estate/dees-comms';
import type { ITypedEvent } from '@api.global/typedrequest-interfaces';
interface ISettingsChangedEvent extends ITypedEvent<{ section: string }> {
name: 'settingsChanged';
uniqueEventId: string;
payload: {
section: string;
};
}
// in every tab that has to follow
const listening = new DeesComms({ channelName: 'my-app' });
const subscription = listening.subscribe<ISettingsChangedEvent>('settingsChanged', (payload, event) => {
console.log(`settings changed in ${payload.section}`, event.uniqueEventId);
});
// in the tab where it happened
const telling = new DeesComms({ channelName: 'my-app' });
await telling.broadcast<ISettingsChangedEvent>('settingsChanged', { section: 'profile' });
// later
subscription.unsubscribe();
- The instance that broadcasts an event does not receive it; every other instance on the channel does, in the same context or another one.
broadcast()gives every event a newuniqueEventId.- Handlers of one name run in the order they subscribed. A handler that throws or rejects is reported with
console.error, naming the event and the error but never the payload, and does not keep the others from running. A handler that an earlier one unsubscribes during the same event is not called for it. - Events and typed requests stay apart: an event never reaches a typed handler, and a typed request never reaches a subscription, whatever their names.
- An instance of 1.0.32 routes every message it receives as a typed request; on the platform's own BroadcastChannel,
@api.global/typedrequest8 then logsTypedRouter received a malformed request DTOfor every event. That is one more reason to broadcast on a channel of your application's own.
Closing
await comms.close();
A closed instance receives nothing: its subscriptions end and its typed handlers are no longer asked. postMessage(), broadcast() and the typed requests it fires reject, and subscribe() throws. A typed request that is still waiting for its response when the channel closes cannot receive it and ends at its timeout; abort it with its AbortSignal to end it at once. Closing again does nothing.
In Node.js an instance keeps the process alive only while something listens on it, as a MessagePort with a message listener does: while it has a subscription or a typed handler. An instance nobody listens on, such as the one @design.estate/dees-domtools opens on import, lets the process end. An instance whose subscriptions ended and whose handlers were removed lets it end too, as a closed one does, so remove every typed handler or close every instance with one that a test or a script opens. In browsers and workers nothing changes.
What travels
Requests, responses and events are copied with the structured clone algorithm, so they carry data, not functions or class instances. A BroadcastChannel is confined to its origin, but every script of that origin can listen on a channel whose name it knows: send no secrets, and nothing that identifies a person, on it.
License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the repository license file.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.