@design.estate/dees-comms

中文文档
2.1.0发布于 2026/10/13MITTypeScriptES Module近 30 天下载 7330

A communications module for enabling DOM-based messaging and synchronization across browser tabs and workers.

原始使用文档
文档目录11 节
  1. Issue Reporting and Security
  2. Install
  3. Usage
  4. Channels
  5. Typed requests
  6. Typed events
  7. Closing
  8. What travels
  9. License and Legal Information
  10. Trademarks
  11. Company Information

@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 timeoutMs ends at the earlier of its own deadline and the instance's responseTimeoutMs, and rejects with a TypedRequestTimeoutError (carrying timeoutMs) 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 TypedResponseError whose errorText is Internal 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.
  • TypedResponseError and TypedRequestTimeoutError are exported by @design.estate/dees-comms and are the classes of the @api.global/typedrequest it routes with. Use these exports for instanceof: an application that depends on another version of @api.global/typedrequest has 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 new uniqueEventId.
  • 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/typedrequest 8 then logs TypedRouter received a malformed request DTO for 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.

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.

版本与发布记录

@design.estate/dees-comms 共发布 11 个版本,首次发布于 2023/08/08;过去 12 个月发布了 9 个版本。

版本发布日期距今
2.1.0latest2026/10/1329 天前
2.0.02026/10/031 个月前
1.1.22026/10/021 个月前
1.1.12026/09/291 个月前
1.1.02026/09/231 个月前
1.0.322026/08/312 个月前

关于 @design.estate/dees-comms 的常见问题

@design.estate/dees-comms 是什么?

A communications module for enabling DOM-based messaging and synchronization across browser tabs and workers.

如何安装 @design.estate/dees-comms?

在项目目录运行 npm install @design.estate/dees-comms,或使用 pnpm add / yarn add / bun add。

@design.estate/dees-comms 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@design.estate/dees-comms 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@design.estate/dees-comms 可以商用吗?

@design.estate/dees-comms 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@design.estate/dees-comms 的下载量有多少?

根据 npm 官方下载统计,@design.estate/dees-comms 在 2026/10/12 – 2026/11/10 这 30 天内被下载 7,330 次,日均约 244 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@design.estate/dees-comms 还在维护吗?

最新版本 2.1.0 发布于 2026/10/13(29 天前);至今共发布 11 个版本,其中过去 12 个月发布了 9 个;首次发布于 2023/08/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。