@ 快乐的垂直/ smrt- messages
统一多频道消息,包括个人路线、加密证书和 供应商适配器。 外出发送支持电子邮件、Zulip和Telegram;短消息是 供提供者适配器使用的预留频道.
安装
pnpm add @happyvertical/smrt-messages
使用量
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: '[email protected]',
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: '[email protected]' }]),
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: '[email protected]' }]),
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) 从主人的人格集。 路线
写作失败关闭,除非证明一个人属于同一房客.
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数字 :
const tool = createPersonaMessagingTool({ db, tenantId, personaId });
该工具只接受消息内容和路由意图. 人a,账户, 端点,及证书身份标识仍为可信任的服务器状态.
应用软件可以渲染 MessagingSettingsPanel 从
@happyvertical/smrt-messages/svelte 使用已消毒视图返回
MessagingSettingsService.list() 并将其保存的回调线接回
服务.
申请通知
UserNotification 每人保存一份读取状态的通知;
UserNotificationService 为一个收件人创建、列出和更新它们.
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 每个事件和收件人发送一个邮件
耐用,租赁的收发箱。 主机解决收件人和发件人账户;
调用者通过一个用户代号以及一个主机相对的链接路径,从没有地址.
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()。见
代理/通知-出柜 租赁,
重试 和解政策 表格是新建的: 运行 db:migrate。 。 。 .
受援者选择退出
NotificationOptOutService 是“选择退出”分类账(notification_opt_outs(中文(简体) )
收发箱 isSuppressed 钩. 范围是 * 或主机密钥, 如
project:<uuid>。 。 。 .
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 用于软件包结构、变化、验证、,
和贡献者的指导.
通知铃和邮箱食谱
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 因为用户界面在运行时对浏览器安全
邮件和通知的持久性仍然是服务器操作.