在上一篇文章中,我把 EmDash 的整个仓库掰开来看了一遍。其中 `src/plugins/` 模块我只用了一段话概括:
definePlugin() 的声明式 API、能力分级、Cloudflare Worker 沙箱隔离——这三层设计让插件既灵活又安全。
那篇文章是"全景图",每个模块点到为止。但插件系统是 EmDash 最有设计感的模块,值得一篇独立的深度拆解。
这篇文章,我会从源码层面逐个拆开 EmDash 插件系统的核心组件:
- **`definePlugin()`** — 插件定义函数,两种格式的设计选择
- **PluginDescriptor** — 插件的构建时元数据(ID、版本、存储、Admin UI)
- **Manifest Schema** — 能力分级、Hook 名称、权限继承
- **Plugin Manager** — 注册、生命周期、执行调度
- **Hook Pipeline** — 事件分发、优先级、超时、排他性、返回值干预
- **Plugin Context** — 能力门控的上下文工厂(KV、Storage、Content、Media、HTTP、Cron、Email、Users)
- **Settings Schema** — 插件的用户配置界面(5 种 SettingField 类型)
- **Sandbox 适配器** — 标准格式如何被转换为可执行的插件
- **plugin-audit-log** — 官方插件逐行拆解
- **Astro 集成** — 插件在构建时和运行时的完整流程
二、PluginDescriptor — 插件的"身份证"
在深入 Manifest Schema 之前,先看一个关键类型:`PluginDescriptor`。它是标准格式插件的构建时元数据,在 `src/index.ts` 中定义。
interface PluginDescriptor<TOptions = Record<string, unknown>> {
id: string; // 唯一标识,小写字母+数字+短横线
version: string; // 语义化版本(如 "1.0.0")
entrypoint: string; // 模块说明符,如 "@scope/my-plugin"
format?: "standard" | "native"; // 插件格式(默认 "native")
capabilities?: string[]; // 能力声明
allowedHosts?: string[]; // 网络白名单(支持 "*.example.com")
options?: TOptions; // 传递给 createPlugin() 的选项(仅 native)
adminEntry?: string; // admin UI 模块说明符(仅 native)
componentsEntry?: string; // Astro 组件模块说明符(仅 native)
storage?: Record<string, StorageCollectionDeclaration>; // 插件专属存储
adminPages?: Array<{ path: string; label: string; icon?: string }>; // 管理页面
adminWidgets?: Array<{ id: string; size?: "full" | "half" | "third"; title?: string }>; // 仪表盘小组件
} **`format` 字段**可以显式声明插件格式。如果不声明,默认为 `"native"`。系统也会根据是否存在 `id` + `version` 来推断。
**`entrypoint`** 指向 sandbox-entry 模块,告诉 EmDash 去哪里找插件的实际运行逻辑。
**`storage`** 是插件专属存储声明——EmDash 会自动为插件创建独立的数据表:
storage: {
records: {
indexes: ["status", "createdAt"], // 普通索引
uniqueIndexes: ["slug"], // 唯一索引
},
} 三、Plugin Manager — 插件的生命周期管理器
`packages/core/src/plugins/manager.ts` 实现了完整的插件生命周期管理。
状态机
每个插件有四个状态:
registered → installed → active → inactive → (uninstalled)
↑ ↓
└─────────┘ 状态 | 说明 | 触发
`registered` | 已注册,尚未安装 | `register()`
`installed` | 已安装,存储已配置 | `install()`
`active` | 已激活,hooks 和 routes 生效 | `activate()`
`inactive` | 已停用,hooks 和 routes 禁用 | `deactivate()`
关键方法
class PluginManager {
// 注册插件 — 验证 ID 唯一性,初始化状态
register(definition: PluginDefinition): ResolvedPlugin
// 安装 — 运行 plugin:install hook,配置存储
async install(pluginId: string): Promise<void>
// 激活 — 运行 plugin:activate hook,启用 routes 和 hooks
async activate(pluginId: string): Promise<void>
// 停用 — 运行 plugin:deactivate hook
async deactivate(pluginId: string): Promise<void>
// 卸载 — 运行 plugin:uninstall hook,清理数据
async uninstall(pluginId: string): Promise<void>
// 执行内容相关 Hook
async runContentBeforeSave(...)
async runContentAfterSave(...)
async runContentBeforeDelete(...)
async runContentAfterDelete(...)
// 执行媒体相关 Hook
async runMediaBeforeUpload(...)
async runMediaAfterUpload(...)
// 调用插件路由
async invokeRoute(pluginId, routeName, options): Promise<unknown>
} 懒初始化设计
HookPipeline 和 PluginRouteRegistry 不是在 `register()` 时创建的,而是在**首次使用时**才初始化。这是一种性能优化——如果你的 Astro 站点大部分页面不涉及插件逻辑,这些管道根本不会被创建。
private get hookPipeline(): HookPipeline {
if (!this._hookPipeline) {
this._hookPipeline = createHookPipeline(...);
}
return this._hookPipeline;
} 五、Plugin Context — 能力门控的运行时环境
`packages/core/src/plugins/context.ts` 是插件系统的"权限边界"。
设计原则
**一个插件只能访问它声明了能力(capabilities)的资源。** 这是通过 `PluginContextFactory` 实现的。
export function createPluginContext(
options: PluginContextFactoryOptions,
plugin: ResolvedPlugin,
): PluginContext 上下文能力的动态创建
`PluginContextFactory.createContext()` 根据插件声明的能力,**动态构建**上下文对象。以下能力**所有插件默认拥有**:`plugin`(插件自身 id+version)、`storage`(声明的专属存储集合)、`kv`(键值存储)、`log`(日志)、`site`(站点信息)、`url`(URL 生成函数)。其余能力需要显式声明:
createContext(plugin: ResolvedPlugin): PluginContext {
const ctx: Partial<PluginContext> = {};
// KV 存储 — 所有插件都有
ctx.kv = createKVAccess(this.optionsRepo, plugin.id);
// 内容访问 — 需要 read:content 或 write:content
if (hasCapability(plugin, "read:content")) {
ctx.content = hasCapability(plugin, "write:content")
? createContentAccessWithWrite(...)
: createContentAccess(...);
}
// 媒体访问 — 需要 read:media 或 write:media
if (hasCapability(plugin, "read:media")) {
ctx.media = hasCapability(plugin, "write:media")
? createMediaAccessWithWrite(...)
: createMediaAccess(...);
}
// HTTP 访问 — 分三级
ctx.http = createHttpAccess(plugin);
// 用户访问 — 需要 read:users
if (hasCapability(plugin, "read:users")) {
ctx.users = createUserAccess(...);
}
// 日志 — 所有插件都有
ctx.log = createLogAccess(plugin.id);
return ctx;
} 各模块详解
KV 存储(`ctx.kv`)
为每个插件提供**命名空间隔离**的键值存储:
export function createKVAccess(optionsRepo: OptionsRepository, pluginId: string): KVAccess {
return {
get: (key) => optionsRepo.get(`${pluginId}:${key}`),
set: (key, value) => optionsRepo.set(`${pluginId}:${key}`, value),
delete: (key) => optionsRepo.delete(`${pluginId}:${key}`),
list: (prefix?) => optionsRepo.list(pluginId, prefix),
};
} 底层存储在 EmDash 的 `_options` 数据库表中,所有键自动加上 `pluginId:` 前缀,确保不同插件的数据不会冲突。
HTTP 访问(`ctx.http`)— 三级安全
function createHttpAccess(plugin: ResolvedPlugin) {
// 级别 1:network:fetch:any — 不受限制
if (hasCapability(plugin, "network:fetch:any")) {
return createUnrestrictedHttpAccess();
}
// 级别 2:network:fetch + allowedHosts — 白名单限制
if (hasCapability(plugin, "network:fetch")) {
return createRestrictedHttpAccess(plugin.allowedHosts);
}
// 级别 3:无能力 — 禁止网络请求
return createDisabledHttpAccess();
} HTTP 访问还内置了 **SSRF 防护**:
- 验证请求 URL,防止访问内部网络
- 重定向限制(最多 5 次)
- 跨域重定向时清除凭证头
内容访问(`ctx.content`)
// 只读
ctx.content.list({ collection: "posts" })
ctx.content.get("my-article-slug")
// 读写(需要 write:content)
ctx.content.create({ collection: "posts", data: {...} })
ctx.content.update("my-article-slug", { data: {...} })
ctx.content.delete("my-article-slug") 媒体访问(`ctx.media`)
// 只读
ctx.media.list()
ctx.media.get("image-id")
// 读写(需要 write:media)
ctx.media.upload(file, options)
ctx.media.delete("image-id") 日志(`ctx.log`)
ctx.log.info("Processing content", { slug: "my-post" });
ctx.log.warn("Rate limit approaching", { remaining: 3 });
ctx.log.error("API call failed", { error: err.message }); 每个插件的日志都带有插件 ID 前缀,方便排查问题。
插件专属存储(`ctx.storage.xxx`)
除了通用的 KV 存储,插件还可以声明**专属的存储集合**(在 descriptor 的 `storage` 字段中声明)。EmDash 会自动创建对应的数据表:
// 声明(在 descriptor 中)
storage: {
records: { indexes: ["status", "createdAt"], uniqueIndexes: ["slug"] }
}
// 使用(在 sandbox-entry 中)
ctx.storage.records.put("record-1", { title: "Hello", status: "draft", slug: "hello" });
ctx.storage.records.get("record-1");
ctx.storage.records.delete("record-1");
// 高级查询
const result = await ctx.storage.records.query({
where: { status: "published" },
orderBy: { createdAt: "desc" },
limit: 20,
cursor: "next-page-token",
});
// result = { items: [...], cursor: "next-token", hasMore: true }
// 批量操作
ctx.storage.records.getMany(["id-1", "id-2", "id-3"]); // 返回 Map<string, T>
ctx.storage.records.putMany([{ id: "id-1", data: {...} }, ...]);
ctx.storage.records.deleteMany(["id-1", "id-2"]); // 返回删除数量
// 统计
await ctx.storage.records.count({ where: { status: "draft" } }); 存储集合 API 相比 KV 存储更强大——支持条件过滤、排序、分页、批量操作和计数。
定时任务(`ctx.cron`)
EmDash 内置了定时任务能力(基于 `croner` 库),插件可以注册和管理定时任务:
// 注册定时任务(每天早上 9 点执行)
await ctx.cron.schedule("daily-digest", {
schedule: "0 9 * * *",
data: { type: "email" },
});
// 取消定时任务
await ctx.cron.cancel("daily-digest");
// 列出所有定时任务
const tasks = await ctx.cron.list(); 定时任务触发时会调用插件的 `cron` Hook,事件数据包含 `{ name, data?, scheduledAt }`。
邮件(`ctx.email`)
需要声明 `email:send` 能力,且系统需配置邮件提供商:
await ctx.email.send({
to: "user@example.com",
subject: "新文章发布通知",
text: "您关注的作者发布了新文章...",
html: "<h1>新文章发布通知</h1>...",
}); 更高级的邮件能力:
能力 | 说明 | 对应 Hook
`email:send` | 发送邮件 | 无
`email:provide` | 注册邮件服务提供商 | `email:deliver`(Exclusive)
`email:intercept` | 拦截/修改邮件 | `email:beforeSend` / `email:afterSend`
用户访问(`ctx.users`)
需要声明 `read:users` 能力。**敏感字段(密码哈希、会话数据等)会被自动过滤**,只返回基本用户信息:
const user = await ctx.users.get("user-id");
// { id, email, name, role, ... }
const user = await ctx.users.getByEmail("user@example.com");
const { items, nextCursor } = await ctx.users.list({ role: "editor", limit: 10 }); 六、Sandbox 适配器 — 标准格式的运行时转换
`packages/core/src/plugins/adapt-sandbox-entry.ts` 是连接两种格式的桥梁。
为什么需要适配器?
标准格式的插件在构建时只是被 `definePlugin()` 原样返回(身份函数)。到了运行时,系统需要把它转换为 `ResolvedPlugin` 才能注册到 Plugin Manager 中。这个转换就是 `adaptSandboxEntry()` 做的。
转换过程
export function adaptSandboxEntry(
definition: StandardPluginDefinition, // 标准格式:{ hooks, routes }
descriptor: PluginDescriptor, // 描述符:来自 src/index.ts
): ResolvedPlugin {
// 1. 从 descriptor 中获取 id、version、capabilities
// 2. 验证 capabilities 是否在允许列表内
// 3. 推导隐含权限(write → read)
// 4. 标准化 storage 配置
// 5. 将标准 hooks 转换为 ResolvedHook
// 6. 将标准 routes 的双参数模式包装为单参数模式
} Hook 参数适配
标准格式的 Hook 使用双参数 `(event, ctx)`,这和 HookPipeline 的分发方式一致,所以 Hook 不需要特殊处理。
Route 参数适配
但 Route 的参数需要适配:
// 标准格式:双参数
handler: async (routeCtx, pluginCtx) => {
return { status: routeCtx.input.status };
}
// 原生格式/运行时:单参数
handler: async (ctx) => {
// ctx 包含 input + request + requestMeta + ...pluginContext
return { status: ctx.input.status };
}
// 适配器的包装
handler: async (ctx) => {
const routeCtx = { input: ctx.input, request: ctx.request, requestMeta: ctx.requestMeta };
const { input: _, request: __, requestMeta: ___, ...pluginCtx } = ctx;
return standardHandler(routeCtx, pluginCtx); // 拆回双参数调用
} 八、Astro 集成 — 构建时验证 + 运行时加载
插件系统如何在 Astro 中工作?分两个阶段。
构建时(`astro:config:setup`)
EmDash 的 Astro 集成(`packages/core/src/astro/integration/index.ts`)在 Astro 配置阶段做这些事:
// 1. 接收两个插件数组
const pluginDescriptors = resolvedConfig.plugins ?? []; // 原生格式(可信)
const sandboxedDescriptors = resolvedConfig.sandboxed ?? []; // 标准格式(沙箱)
// 2. 格式验证
for (const desc of sandboxedDescriptors) {
// 标准格式不允许有 adminEntry 或 componentsEntry
if (desc.adminEntry || desc.componentsEntry) {
throw new Error("Standard plugins cannot declare adminEntry or componentsEntry");
}
}
for (const desc of pluginDescriptors) {
// 原生格式不能放入 sandboxed 数组
// ...
}
// 3. 通过 Vite 虚拟模块将配置传递给运行时
updateConfig({
vite: createViteConfig({
serializableConfig,
resolvedConfig,
pluginDescriptors,
astroConfig,
}, command),
}); astro.config.mjs 中的使用
import emdash from "emdash/astro";
import { sqlite } from "emdash/db";
import { auditLogPlugin } from "@emdash-cms/plugin-audit-log";
export default defineConfig({
integrations: [
emdash({
database: sqlite({ url: "file:./data.db" }),
plugins: [
auditLogPlugin(), // 原生格式插件
],
}),
],
}); 运行时
插件的实际加载和执行发生在运行时。Plugin Manager 在首次请求时懒初始化,按照以下流程:
- 读取虚拟模块中的插件配置
- 对原生格式插件:直接调用 `definePlugin()` 得到 `ResolvedPlugin`
- 对标准格式插件:读取 descriptor + sandbox-entry,通过 `adaptSandboxEntry()` 转换
- 注册到 Plugin Manager
- 根据数据库中的插件状态(active/inactive)决定是否激活
十、与 WordPress 插件系统的对比
维度 | WordPress | EmDash
定义方式 | PHP 函数 + Hook 注册 | `definePlugin()` TypeScript
运行环境 | 共享 PHP 运行时 | 沙箱隔离 / 能力门控
安全模型 | 信任插件 | 隔离插件
数据存储 | 直接操作 MySQL | 通过 Context API
权限声明 | 无 | `capabilities` 明确声明
Hook 类型 | Action + Filter | 21 个具名 Hook + 配置项
优先级 | `priority` 参数 | `priority` + `timeout` + `errorPolicy`
错误处理 | 影响全局 | `abort` / `continue` 可选
管理界面 | PHP + HTML | Block Kit 声明式 / React
网络请求 | 无限制 | `allowedHosts` 白名单
插件市场 | wordpress.org | 自建 Marketplace Worker
GitHub 仓库:[https://github.com/emdash-cms/emdash](https://github.com/emdash-cms/emdash)