# @happyvertical/smrt-messages 中文文档

规范地址：https://npmcn.com/package/%40happyvertical/smrt-messages/

版本：0\.62\.1
npm 元数据更新时间：2026-11-17T07:56:40.611Z
中文译文更新时间：2026-11-17T09:44:24.125Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40happyvertical/smrt-messages
原文对照：https://npmcn.com/package/%40happyvertical/smrt-messages/?lang=original
项目主页：https://github.com/happyvertical/smrt#readme
源码仓库：https://github.com/happyvertical/smrt

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.9 MB，268 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：13 个
- peer 依赖：svelte ^5\.57\.0，@happyvertical/encryption \*
- 首次发布：2026-06-23T01:18:42.410Z
- 最新版本发布：2026-11-17T07:56:40.446Z
- 近 30 天下载量：19670（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：365（近 12 个月 365 个）

## 中文简介

以科学、技术和创新为基础的统一多渠道信息

## 安装

```sh
npm install @happyvertical/smrt-messages
```

也可以使用：`pnpm add @happyvertical/smrt-messages`、`yarn add @happyvertical/smrt-messages`、`bun add @happyvertical/smrt-messages`

## README

# @ 快乐的垂直/ smrt- messages

统一多频道消息,包括个人路线、加密证书和 供应商适配器。 外出发送支持电子邮件、Zulip和Telegram;短消息是 供提供者适配器使用的预留频道.

## 安装

```bash
pnpm add @happyvertical/smrt-messages
```

## 使用量

```typescript
import {
  AttachmentCollection,
  Email, EmailCollection,
  EmailAccount, EmailAccountCollection,
  EmailSender,
  MessageCollection,
} from '@happyvertical/smrt-messages';

// Create an email account with encrypted credentials
const accounts = await EmailAccountCollection.create({ db });
const account = await accounts.create({
  name: 'Support',
  providerType: 'smtp',
});
await account.setCredentials({
  host: 'smtp.example.com',
  user: 'support@example.com',
  pass: process.env.SMTP_PASSWORD,
});

// Send an email through the send lifecycle
const emails = await EmailCollection.create({ db });
const email = await emails.create({
  accountId: account.id,
  subject: 'Welcome',
  toAddresses: JSON.stringify([{ address: 'user@example.com' }]),
  textBody: 'Thanks for signing up!',
});
const result = await email.send();
// sendStatus transitions: draft -> sending -> sent (or failed)

// Retry a failed message (respects maxRetries budget)
if (!result.success) {
  await email.retrySend();
}

// Attach files: stored `Attachment` rows are read through
// `Attachment.readContent()` at send time, and bytes rendered on demand go in
// `send({ attachments })`. Both reach the transport together; a stored file
// that cannot be read fails the send (sendStatus 'failed', sendError set)
// instead of being dropped.
const order = await emails.create({
  accountId: account.id,
  subject: 'Purchase order PO-1042',
  toAddresses: JSON.stringify([{ address: 'orders@vendor.example' }]),
  textBody: 'Please find our purchase order attached.',
  hasAttachments: true,
});
const attachments = await AttachmentCollection.create({ db });
await attachments.create({
  messageId: order.id,
  filename: 'PO-1042.pdf',
  contentType: 'application/pdf',
  size: pdfBytes.length,
  filePath: '/data/po/PO-1042.pdf',
});
await order.send({
  attachments: [
    { filename: 'terms.txt', contentType: 'text/plain', content: termsBytes },
  ],
});

// Query messages across all channels via base collection
const messages = await MessageCollection.create({ db });
const recent = await messages.list({ orderBy: 'createdAt DESC', limit: 20 });
```

## API 密码

### 模型(STI 等级)

消息和帐号都使用单表继承. 科学、技术和创新歧视者使用合格名称(例如, `@happyvertical/smrt-messages:Email`) (中文(简体) ).

| 导出 | 说明 |
| --- | --- |
| `Message` | 带有发送周期(草稿/发送/发送/失效)的基础信息 |
| `Email` | 电子邮件:RFC 822 线程、cc/bcc、htmlBody/textBody、文件夹 |
| `SlackMessage` | 带有频道Id, laffTs, 反应, 块的黑信息 |
| `Tweet` | Twitter讯息有TwitterId, retweetCount,类似Count,标签 |
| `Account` | 基地账户 `setCredentials()`编号 :`getCredentials()` 通过 smrt- 机密 |
| `EmailAccount` | 电子邮件账户( SMTP/ IMAP 提供者) |
| `SlackAccount` | 空白工作空间账户 |
| `TwitterAccount` | Twitter API 账户 |
| `Attachment` | 信件附件 |
| `EmailAttachment` | 电子邮件专用附件 |
| `EmailFolder` | 电子邮件文件夹/ 标签 |

### 收款

`MessageCollection`, (中文(简体) ), `EmailCollection`, (中文(简体) ), `AccountCollection`, (中文(简体) ), `EmailAccountCollection`, (中文(简体) ), `AttachmentCollection`, (中文(简体) ), `EmailAttachmentCollection`, (中文(简体) ), `EmailFolderCollection`

### 发件人

每个频道都有专用发送器 `MessageSenderInterface`。 。 。 .

| 导出 | 说明 |
| --- | --- |
| `EmailSender` | 通过电子邮件发送 `@happyvertical/email` 客户端 |
| `SlackSender` | 通过 API 发送黑消息 |
| `TweetSender` | 透过Twitter API的推文 |
| `ZulipSender` | 通过 bot 证书发送流或私人 Zulip 信件 |
| `TelegramSender` | 向聊天/专题发送Telegram bot 消息 |

### 个人范围外传消息

`MessagingSettingsService` 是用于保存的授权的服务器边界 账户、只写证书、目的地和个人路线. `PersonaMessagingService` 选择最优先匹配的路由, 坚持 信息,然后运行正常的发送生命周期.

斯克马变化是明显驱动的. 更新应用程序后运行 `smrt db:diff` 财务报告和审定财务报表 `smrt db:migrate` 添加账户/信件栏和 `messaging_endpoints` 编号 : `persona_message_routes` 图表.

构建时 `MessagingSettingsService`,提供 `resolvePersonaTenantId(personaId)` 从主人的人格集。 路线 写作失败关闭,除非证明一个人属于同一房客.

```typescript
import {
  messagingPrincipalFromPermissions,
  PersonaMessagingService,
} from '@happyvertical/smrt-messages';

const messaging = new PersonaMessagingService({
  db,
  tenantId,
  principal: messagingPrincipalFromPermissions(['messages.send'], { tenantId }),
});

await messaging.send({
  personaId,
  channel: 'telegram', // optional; default route otherwise
  body: 'The scheduled report is ready.',
});

// Email routes also take send-time attachments; any other route rejects them.
await messaging.send({
  personaId,
  channel: 'email',
  subject: 'Weekly report',
  body: 'The report is attached.',
  attachments: [
    { filename: 'report.pdf', contentType: 'application/pdf', content: pdf },
  ],
});
```

代理从 `@happyvertical/smrt-personas`数字 :

```typescript
const tool = createPersonaMessagingTool({ db, tenantId, personaId });
```

该工具只接受消息内容和路由意图. 人a,账户, 端点,及证书身份标识仍为可信任的服务器状态.

应用软件可以渲染 `MessagingSettingsPanel` 从 `@happyvertical/smrt-messages/svelte` 使用已消毒视图返回 `MessagingSettingsService.list()` 并将其保存的回调线接回 服务.

### 申请通知

`UserNotification` 每人保存一份读取状态的通知; `UserNotificationService` 为一个收件人创建、列出和更新它们.

```typescript
import { UserNotificationService } from '@happyvertical/smrt-messages';

const notifications = new UserNotificationService({ db });

// Idempotent per (tenant, recipient, sourceRef).
await notifications.notify({
  tenantId,
  recipientUserId: post.createdByUserId,
  kind: 'social-post.failed',
  title: "A post to X didn't go out",
  href: `/sites/${slug}/social-posts`,
  severity: 'error',
  sourceRef: `social-post:${post.id}:failed`,
});

const items = await notifications.listForUser(userId, { tenantIds });
const unread = await notifications.countUnread(userId, { tenantIds });
await notifications.markRead(userId, [id], { tenantId });
await notifications.dismiss(userId, [id], { tenantId });
await notifications.markAllRead(userId, { tenantIds });
```

生成的 REST/MCP/CLI 表面已关闭; 暴露通过 注册用户的ID。 表格是新建的: 运行 `db:migrate`。 。 。 .

### 通知电子邮件收发箱

`NotificationOutboxService` 每个事件和收件人发送一个邮件 耐用,租赁的收发箱。 主机解决收件人和发件人账户; 调用者通过一个用户代号以及一个主机相对的链接路径,从没有地址.

```typescript
import { NotificationOutboxService } from '@happyvertical/smrt-messages';
import '@happyvertical/smrt-messages/providers/email'; // default transport

const outbox = new NotificationOutboxService({
  db,
  linkBaseUrl: 'https://app.example.com',
  resolveRecipient: async ({ tenantId, recipientUserId }) =>
    (await isMember(tenantId, recipientUserId))
      ? { address: await emailOf(recipientUserId) }
      : null, // denied
  resolveSenderAccountId: ({ tenantId }) => senderAccountIdFor(tenantId),
});

// Idempotent per (tenant, recipient, email, sourceRef).
await outbox.enqueueEmail({
  tenantId,
  recipientUserId,
  sourceRef: `project-question:${question.id}:asked`,
  kind: 'project-question.asked',
  subject: 'A question is waiting for you',
  text: question.prompt,
  path: `/portal/projects/${projectId}/questions#question-${question.id}`,
});

// From a scheduled job; safe to run concurrently and after a crash.
await outbox.dispatchDue({ limit: 25 });
```

提供者可能已经看到但没有确认的结果 `uncertain` 等待着 `reconcile()`。见 [代理/通知-出柜](https://npmcn.com/package/%40happyvertical/smrt-messages/agents/notification-outbox.md) 租赁, 重试 和解政策 表格是新建的: 运行 `db:migrate`。 。 。 .

#### 受援者选择退出

`NotificationOptOutService` 是“选择退出”分类账(`notification_opt_outs`(中文(简体) ) 收发箱 `isSuppressed` 钩. 范围是 `*` 或主机密钥, 如 `project:<uuid>`。 。 。 .

```typescript
import {
  NotificationOptOutService,
  optOutSuppression,
} from '@happyvertical/smrt-messages';

const optOuts = new NotificationOptOutService({ db });
// Idempotent; with a principal only the recipient may change their own row,
// in the tenant the principal is authenticated in.
await optOuts.optOut({
  tenantId,
  recipientUserId,
  channel: 'email',
  scope: `project:${projectId}`,
  principal: { userId: session.userId, tenantId },
});

// Pass to the outbox: enqueue and dispatch both honour opt-outs.
const isSuppressed = optOutSuppression(optOuts, async (request) => {
  // The host maps its own event to a scope; null = not opt-out-able.
  // Here a question's sourceRef is resolved to its project by a host lookup.
  const projectId = await projectIdForSourceRef(request.tenantId, request.sourceRef);
  return projectId ? `project:${projectId}` : null;
});
```

表格是新建的: 运行 `db:migrate`。 。 。 .

### 证书安全

账户证书通过 `credentialSecretId` 指向机密信封加密 使用 `account.setCredentials()` 财务报告和审定财务报表 `account.getCredentials()` - 从不将密码作为普通字段存储.

### 密钥类型

`MessageType`, (中文(简体) ), `ProviderType`, (中文(简体) ), `SendStatus`, (中文(简体) ), `SendMessageOptions`, (中文(简体) ), `SendEmailOptions`, (中文(简体) ), `SendSlackOptions`, (中文(简体) ), `SendTweetOptions`, (中文(简体) ), `MessageSendResult`, (中文(简体) ), `MessageSenderInterface`, (中文(简体) ), `SyncOptions`, (中文(简体) ), `SyncResult`, (中文(简体) ), `SyncProgress`

## 依赖关系

-   `@happyvertical/smrt-core` -- ORM 和代码生成
-   `@happyvertical/smrt-secrets` -- 证书加密(信封加密)
-   `@happyvertical/smrt-tenancy` -- 可选多租户范围界定
-   `@happyvertical/smrt-types` -- 共同类型定义
-   `@happyvertical/email` -- SMTP/IMAP 电子邮件客户端
-   端点 : `@happyvertical/smrt-svelte` (可选)

## 贡献者指南

见 [`AGENTS.md`](https://npmcn.com/package/%40happyvertical/smrt-messages/AGENTS.md) 用于软件包结构、变化、验证、, 和贡献者的指导.

### 通知铃和邮箱食谱

`Messages` 出口 `NotificationsRecipe` (单位:千美元)`messages.notifications`和 `MailboxRecipe` (单位:千美元)`messages.mailbox`) (中文(简体) ). 邮箱游乐场提供交互式虚构收件箱; 其作曲动作报告为模拟发送,从不呼叫邮件运输.

对于服务器授权主机, 构建 `createUserNotificationBellProvider` 从 `@happyvertical/smrt-messages/svelte` 带有 `UserNotificationService`,签名 `userId`和授权 `tenantIds`。通过该提供者到 `NotificationBell` 从 `@happyvertical/smrt-svelte/notifications`。浏览器主机执行相同的 供应商界面超过认证的服务器端点; 从不发送数据库服务 到浏览器。 当用户或租户上下文发生变化时替换提供者。 可选 `subscribe` 连接主机拥有的运输工具; UI 在处置时不订阅.

Message功能卡独立提供邮箱和通知控制. 邮箱导航包括一个稳定的失败发送条目 `sendStatus = failed`。 。 。 . 通知故意宣布没有通用型号导航:接收者范围d 仍然需要供应商进入.

邮箱路由表面解析 `MessageList`;核准的东道方用品 `messages`,账户DTO,和回调。 内容 `email-inbox` 提供者列表 已执行 IMAP、 POP3 和 Gmail 读取器; 可选 `email-send` 提供者 列表 SMTP 和 Gmail 发送。 导入 `@happyvertical/smrt-messages/providers/email` 在服务器上保存证书,并保存在现有秘密支持的账户设置中. 提供方元数据名称执行,而非自动连接或证书. 这个 `MailboxDemo` 游乐场仍然自成一体 每一次发送都被嘲笑. 它的JSON演示种子是虚构的 `MessageList` 道具有效载荷, 从来没有一个活账户.

通知的表面位置 `NotificationBell` 时间 `header.end`必要的 `user-notification-service` 执行地图 `createUserNotificationBellProvider` 还需要一个经东道主授权的用户和租户的套装。 浏览器主机 通过认证的终点连接服务。 杰森号 `items` 种子为 演示文稿数据: 演示主机将其包入内存 `NotificationProvider`· ; 绝对不能把降级变异带给生产通知处. 所有这些食谱都用 `runtime: both` 因为用户界面在运行时对浏览器安全 邮件和通知的持久性仍然是服务器操作.

## 常见问题

### @happyvertical/smrt-messages 是什么？

以科学、技术和创新为基础的统一多渠道信息

### 如何安装 @happyvertical/smrt-messages？

在项目目录运行 npm install @happyvertical/smrt-messages，或使用 pnpm add / yarn add / bun add。

### @happyvertical/smrt-messages 支持 TypeScript 吗？

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

### @happyvertical/smrt-messages 支持 ESM 还是 CommonJS？

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

### @happyvertical/smrt-messages 可以商用吗？

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

### @happyvertical/smrt-messages 的下载量有多少？

根据 npm 官方下载统计，@happyvertical/smrt-messages 在 2026/10/17 – 2026/11/15 这 30 天内被下载 19,670 次，日均约 656 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @happyvertical/smrt-messages 还在维护吗？

最新版本 0\.62\.1 发布于 2026/11/17（今天）；至今共发布 365 个版本，其中过去 12 个月发布了 365 个；首次发布于 2026/06/23。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

