@design.estate/dees-comms
v1.1.0
Published
A communications module for enabling DOM-based messaging and synchronization across browser tabs and workers.
Maintainers
Readme
@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-commsUsage
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 router and target the instance routes with.
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 with its own timeout. Closing again does nothing. An open channel keeps a Node.js process alive, so close every instance a test or a script opens.
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 [email protected].
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.
