沙盒插件将其设置存储在每个插件的 KV 存储中,并将编辑 UI 渲染为 Block Kit 页面:您用 JSON 描述表单并从路由提供它。
一切都通过插件已经用于钩子和路由的同一机制进行——没有额外的东西需要学习。
KV 存储
每个插件都获得一个私有键值存储,可在任何钩子或路由中以 ctx.kv 的形式访问。它是设置和任何其他小型持久状态的规范位置:
interface KVAccess {
get<T>(key: string): Promise<T | null>;
set(key: string, value: unknown): Promise<void>;
delete(key: string): Promise<boolean>;
list(prefix?: string): Promise<Array<{ key: string; value: unknown }>>;
}
KV 是按插件划分的——您写入的键存储在您的插件 ID 下,对其他插件不可见。
读取和写入
// Read
const enabled = await ctx.kv.get<boolean>("settings:enabled");
const config = await ctx.kv.get<{ url: string; timeout: number }>("state:config");
// Write
await ctx.kv.set("settings:lastSync", new Date().toISOString());
await ctx.kv.set("state:cache", { data: items, expiry: Date.now() + 3600000 });
// Delete
const deleted = await ctx.kv.delete("state:tempData");
// List by prefix
const allSettings = await ctx.kv.list("settings:");
// → [{ key: "settings:enabled", value: true }, ...]
键命名约定
使用前缀来分离不同类型的值。EmDash 插件中的约定:
| 前缀 | 用途 | 示例 |
|---|---|---|
settings: | 用户可配置的首选项 | settings:apiKey |
state: | 内部插件状态 | state:lastSync |
cache: | 缓存数据 | cache:results |
// Clear prefixes
await ctx.kv.set("settings:webhookUrl", url);
await ctx.kv.set("state:lastRun", timestamp);
await ctx.kv.set("cache:feed", feedData);
// Avoid bare keys
await ctx.kv.set("url", url);
Block Kit 中的设置 UI
沙盒插件将其设置页面描述为 Block Kit。管理员向您插件的路由(通常为 routes.admin)发送 page_load 交互,插件返回表单的 JSON 描述。当用户点击保存时,管理员发送 block_action 或 form_submit 交互;插件写入 KV 并返回更新的块。
import type { PluginContext, SandboxedPlugin } from "emdash/plugin";
interface BlockInteraction {
type: "page_load" | "block_action" | "form_submit";
page?: string;
action_id?: string;
values?: Record<string, unknown>;
}
export default {
routes: {
admin: {
handler: async (routeCtx, ctx) => {
const interaction = routeCtx.input as BlockInteraction;
if (interaction.type === "page_load" && interaction.page === "/settings") {
return renderSettings(ctx);
}
if (interaction.type === "form_submit" && interaction.action_id === "save") {
await saveSettings(ctx, interaction.values ?? {});
return {
...(await renderSettings(ctx)),
toast: { message: "Settings saved", type: "success" },
};
}
return { blocks: [] };
},
},
},
} satisfies SandboxedPlugin;
async function renderSettings(ctx: PluginContext) {
const apiKey = (await ctx.kv.get<string>("settings:apiKey")) ?? "";
const enabled = (await ctx.kv.get<boolean>("settings:enabled")) ?? true;
const maxItems = (await ctx.kv.get<number>("settings:maxItems")) ?? 100;
return {
blocks: [
{ type: "header", text: "Plugin settings" },
{
type: "form",
block_id: "settings",
fields: [
{
type: "secret_input",
action_id: "apiKey",
label: "API key",
initial_value: apiKey,
},
{
type: "toggle",
action_id: "enabled",
label: "Enabled",
initial_value: enabled,
},
{
type: "number_input",
action_id: "maxItems",
label: "Max items",
min: 1,
max: 1000,
initial_value: maxItems,
},
],
submit: { label: "Save", action_id: "save" },
},
],
};
}
async function saveSettings(ctx: PluginContext, values: Record<string, unknown>) {
for (const [key, value] of Object.entries(values)) {
if (value !== undefined) {
await ctx.kv.set(`settings:${key}`, value);
}
}
}
要将设置页面连接到管理侧边栏,在清单中声明它:
"admin": {
"pages": [{ "path": "/settings", "label": "Settings", "icon": "settings" }]
}
EmDash 自动将该路径的 page_load 交互路由到您的 admin 路由。
有关块类型、表单字段、条件字段和 @emdash-cms/blocks 构建器助手的完整集合,请参阅 Block Kit。
秘密值
Block Kit 的 secret_input 字段渲染为掩码输入。小心处理用户在那里输入的任何值:
{
type: "secret_input",
action_id: "apiKey",
label: "API key",
// Don't seed initial_value with the real secret — pass an empty string or a sentinel,
// and only overwrite when the user enters a non-empty value.
initial_value: "",
}
保存时,跳过空字符串以避免在每次保存时清除现有秘密:
async function saveSettings(ctx: PluginContext, values: Record<string, unknown>) {
if (typeof values.apiKey === "string" && values.apiKey.length > 0) {
await ctx.kv.set("settings:apiKey", values.apiKey);
}
// ... other fields
}
默认值
KV 读取对于尚未写入的键返回 null。在读取位置传递默认值:
const enabled = (await ctx.kv.get<boolean>("settings:enabled")) ?? true;
const maxItems = (await ctx.kv.get<number>("settings:maxItems")) ?? 100;
或在安装期间持久化默认值:
hooks: {
"plugin:install": async (_event, ctx) => {
await ctx.kv.set("settings:enabled", true);
await ctx.kv.set("settings:maxItems", 100);
},
},
权衡是 plugin:install 每次安装运行一次。如果您在后续版本中发布新设置,只有新安装才能看到默认值——现有安装需要在 plugin:activate 中进行迁移(幂等:仅在缺失时写入)或继续使用读取时回退。
设置 vs. storage vs. KV
| 用例 | 机制 |
|---|---|
| 管理员可编辑的首选项 | 带有 settings: 前缀的 ctx.kv + Block Kit 页面 |
| 内部插件状态 | 带有 state: 前缀的 ctx.kv |
| 文档集合(查询) | ctx.storage |
KV 用于由字符串键入的小值——设置、同步游标、缓存计算。无查询,无索引。
Storage 用于具有索引查询的文档集合——表单提交、审计日志,任何您想要过滤、分页或计数的内容。
存储布局
KV 值位于 _options 表中,具有插件命名空间的键。您的代码使用 settings:apiKey;EmDash 将其存储为 plugin:<your-plugin-id>:settings:apiKey。前缀自动添加,防止一个插件读取或覆盖另一个插件的 KV 数据。
原生插件:settingsSchema
如果您正在编写原生插件(因为您需要 React 管理页面或 PT 组件),您可以直接在 definePlugin() 内部声明设置模式,并让 EmDash 自动生成表单。有关该路径,请参阅原生插件。