外掛可以為管理 UI 和外部整合暴露 API 路由。路由掛載在 /_emdash/api/plugins/<slug>/<route-name> 下(<slug> 是 emdash-plugin.jsonc 中外掛的 slug 欄位 — 執行時期通過 ctx.plugin.id 暴露),並在與鉤子接收到的相同 PluginContext 的沙盒執行時期內執行。
本頁面涵蓋沙盒外掛。原生外掛的 API 表面相同;唯一的差異是處理器簽章 — 詳見原生外掛中的說明。
定義路由
在 src/plugin.ts 的預設匯出中宣告路由:
import type { SandboxedPlugin } from "emdash/plugin";
import { z } from "astro/zod";
export default {
routes: {
status: {
handler: async (_routeCtx, ctx) => {
return { ok: true, plugin: ctx.plugin.id };
},
},
submissions: {
input: z.object({
formId: z.string().optional(),
limit: z.number().default(50),
cursor: z.string().optional(),
}),
handler: async (routeCtx, ctx) => {
const { formId, limit, cursor } = routeCtx.input;
const result = await ctx.storage.submissions.query({
where: formId ? { formId } : undefined,
orderBy: { createdAt: "desc" },
limit,
cursor,
});
return result;
},
},
},
} satisfies SandboxedPlugin;
satisfies SandboxedPlugin 推斷 routeCtx 和 ctx — 無需參數註解。沙盒路由處理器接受兩個引數:(routeCtx, ctx)。
routeCtx攜帶請求相關資料:{ input, request, requestMeta }。ctx與鉤子中取得的PluginContext相同 —ctx.storage、ctx.kv、ctx.content、ctx.http、ctx.log等。
路由 URL
路由掛載在 /_emdash/api/plugins/<slug>/<route-name>。路由名稱可以包含斜線用於巢狀路徑。
| 外掛 ID | 路由名稱 | URL |
|---|---|---|
forms | status | /_emdash/api/plugins/forms/status |
forms | submissions | /_emdash/api/plugins/forms/submissions |
seo | settings/save | /_emdash/api/plugins/seo/settings/save |
analytics | events/recent | /_emdash/api/plugins/analytics/events/recent |
驗證和 CSRF
外掛路由預設需要驗證。 調度器在呼叫你的處理器之前需要一個工作階段(或具有 admin 作用域的權杖)。私有路由預設使用 plugins:manage 權限以實現向後相容。當操作屬於現有的內容、媒體、架構或設定功能時,將 permission 設定為更窄的 EmDash RBAC 權限:
routes: {
create: {
permission: "content:create",
input: z.object({ title: z.string() }),
handler: async (routeCtx, ctx) => {
// ...
},
},
},
私有路由要求 Cookie 驗證請求攜帶 X-EmDash-Request: 1 CSRF 標頭。管理 UI 會自動傳送它;權杖驗證請求不受此限制。
要將路由排除在驗證和 CSRF 之外,標記為 public: true:
routes: {
track: {
public: true,
input: z.object({ event: z.string() }),
handler: async (routeCtx, ctx) => {
ctx.log.info("Tracked", { event: routeCtx.input.event });
return { ok: true };
},
},
},
快取公開回應
API 回應預設使用 Cache-Control: private, no-store。對於向所有人提供相同資料的公開路由 — 產品目錄、公開搜尋索引 — 這意味著每次頁面瀏覽都要支付到來源的完整往返。公開路由可以透過 cacheControl 選擇 CDN/瀏覽器快取:
routes: {
catalog: {
public: true,
cacheControl: "public, max-age=60, stale-while-revalidate=300",
handler: async (ctx) => listProducts(ctx),
},
},
標頭僅應用於公開路由的成功 GET 回應。錯誤永遠不會被快取,其他方法保持預設值,在私有路由上設定 cacheControl 沒有效果 — 驗證回應始終保持 private, no-store。
將路由作為 MCP 工具暴露
外掛可以透過 EmDash 的 MCP 伺服器明確暴露選定的私有路由。MCP 暴露永遠不會從路由列表推斷:
const createEventInput = z.object({
title: z.string().min(1),
startsAt: z.string().datetime(),
});
export default {
routes: {
"events/create": {
permission: "content:create",
input: createEventInput,
handler: async (routeCtx, ctx) => {
return { id: await createEvent(routeCtx.input, ctx) };
},
},
},
mcp: {
tools: {
createEvent: {
description: "Create a calendar event when the user asks to add one.",
route: "events/create",
input: createEventInput,
output: z.object({ id: z.string() }),
destructive: false,
},
},
},
} satisfies SandboxedPlugin;
EmDash 將其暴露為 <pluginId>__createEvent。參照的路由必須是私有的並宣告 permission。輸入綱要是必需的;輸出綱要是選用的。對於刪除、覆寫、發布、收費或執行其他難以撤銷操作的工具,設定 destructive: true。
管理員必須在審查工具的名稱、描述、路由、權限和 destructive 旗標後,個別啟用外掛的 MCP 工具。呼叫工具需要路由權限和 mcp:tools 權杖作用域或 mcp:tools:<pluginId>。
輸入驗證
input 接受 Zod 綱要。調度器解析請求本文(POST/PUT/PATCH)或查詢字串(GET/DELETE),驗證它,並將型別化結果作為 routeCtx.input 傳遞給你的處理器。無效輸入在你的處理器執行之前回傳 400。
routes: {
create: {
input: z.object({
title: z.string().min(1).max(200),
email: z.string().email(),
priority: z.enum(["low", "medium", "high"]).default("medium"),
tags: z.array(z.string()).optional(),
}),
handler: async (routeCtx, ctx) => {
const { title, email, priority, tags } = routeCtx.input;
await ctx.storage.items.put(`item_${Date.now()}`, {
title,
email,
priority,
tags: tags ?? [],
createdAt: new Date().toISOString(),
});
return { success: true };
},
},
},
回傳值
回傳任何可 JSON 序列化的值。調度器將其包裝在 EmDash 的標準信封({ success: true, data: <你的值> })中,並以 application/json 形式提供。
return { id: "abc", count: 42 }; // 包裝為 { success: true, data: { id, count } }
return [1, 2, 3]; // 包裝為 { success: true, data: [1, 2, 3] }
錯誤
拋出例外以回傳錯誤回應。任何不是已知外掛錯誤的內容都回傳通用訊息 — 內部例外被遮蔽而不是洩露堆疊追蹤或資料庫錯誤:
handler: async (routeCtx, ctx) => {
const item = await ctx.storage.items.get(routeCtx.input.id);
if (!item) {
throw new Error("Item not found");
}
return item;
},
對於特定狀態碼,拋出 Response:
handler: async (routeCtx, ctx) => {
const item = await ctx.storage.items.get(routeCtx.input.id);
if (!item) {
throw new Response(JSON.stringify({ error: "Not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
return item;
},
HTTP 方法
路由回應所有方法。如果需要按方法區分行為,在 routeCtx.request.method 上分支:
routes: {
item: {
input: z.object({ id: z.string() }),
handler: async (routeCtx, ctx) => {
const { id } = routeCtx.input;
switch (routeCtx.request.method) {
case "GET":
return await ctx.storage.items.get(id);
case "DELETE":
await ctx.storage.items.delete(id);
return { deleted: true };
default:
throw new Response("Method not allowed", { status: 405 });
}
},
},
},
存取請求
routeCtx.request 是 SandboxedRequest:一個可攜式的 { url, method, headers } 記錄,在程序內和隔離區內行為相同。headers 是小寫鍵的 Record<string, string> — 按小寫名稱索引或使用 Object.entries 迭代。url 是字串,所以 new URL(request.url) 解析查詢參數。routeCtx.requestMeta 包含可用時跨平台標準化的 IP、使用者代理和地理資料。
handler: async (routeCtx, ctx) => {
const { request, requestMeta } = routeCtx;
const auth = request.headers["authorization"]; // 小寫鍵,無 .get()
const url = new URL(request.url);
const page = url.searchParams.get("page");
ctx.log.info("Request", { meta: requestMeta });
if (request.method !== "POST") {
throw new Response("POST required", { status: 405 });
}
},
常見模式
透過 KV 的設定
沙盒外掛透過 KV 儲存讀寫設定,慣例上使用 settings: 前綴。自動產生的 settingsSchema 表單僅適用於原生外掛 — 對於沙盒外掛,透過路由暴露讀寫並在 Block Kit 中呈現表單。
routes: {
settings: {
handler: async (_routeCtx, ctx) => {
const settings = await ctx.kv.list("settings:");
const result: Record<string, unknown> = {};
for (const entry of settings) {
result[entry.key.replace("settings:", "")] = entry.value;
}
return result;
},
},
"settings/save": {
input: z.object({
enabled: z.boolean().optional(),
apiKey: z.string().optional(),
maxItems: z.number().optional(),
}),
handler: async (routeCtx, ctx) => {
for (const [key, value] of Object.entries(routeCtx.input)) {
if (value !== undefined) {
await ctx.kv.set(`settings:${key}`, value);
}
}
return { success: true };
},
},
},
分頁列表
從儲存查詢回傳基於游標的分頁 — 回應形式與 EmDash 其餘部分使用的一致:
routes: {
list: {
input: z.object({
limit: z.number().min(1).max(100).default(50),
cursor: z.string().optional(),
status: z.string().optional(),
}),
handler: async (routeCtx, ctx) => {
const { limit, cursor, status } = routeCtx.input;
const result = await ctx.storage.items.query({
where: status ? { status } : undefined,
orderBy: { createdAt: "desc" },
limit,
cursor,
});
return {
items: result.items.map((item) => ({ id: item.id, ...item.data })),
cursor: result.cursor,
hasMore: result.hasMore,
};
},
},
},
外部 API 代理
透過 ctx.http 將請求代理到外部服務(需要 network:request 能力和 allowedHosts 中的項目):
routes: {
forecast: {
input: z.object({ city: z.string() }),
handler: async (routeCtx, ctx) => {
if (!ctx.http) throw new Error("Network capability not granted");
const apiKey = await ctx.kv.get<string>("settings:apiKey");
if (!apiKey) throw new Error("API key not configured");
const response = await ctx.http.fetch(
`https://api.weather.example.com/forecast?city=${routeCtx.input.city}`,
{ headers: { "X-API-Key": apiKey } },
);
if (!response.ok) {
throw new Error(`Weather API error: ${response.status}`);
}
return response.json();
},
},
},
從管理 UI 呼叫路由
使用 admin 套件中的 usePluginAPI() — 它自動加入 X-EmDash-Request CSRF 標頭和外掛 ID 前綴:
import { usePluginAPI } from "@emdash-cms/admin";
function SettingsPage() {
const api = usePluginAPI();
const handleSave = async (settings) => {
await api.post("settings/save", settings);
};
const loadSettings = async () => {
return api.get("settings");
};
}
從佇列和排程處理器呼叫路由
平台事件處理器(Cloudflare Queue 消費者、自訂 scheduled() 處理器)沒有 HTTP 請求,因此也沒有 locals.emdash。使用 emdash/middleware 的 withEmDashRuntime() 直接取得執行時期,無需請求即可呼叫外掛路由:
import { withEmDashRuntime } from "emdash/middleware";
export default {
// ... 來自 @emdash-cms/cloudflare/worker 的 fetch/scheduled
async queue(batch: MessageBatch) {
await withEmDashRuntime(async (runtime) => {
for (const message of batch.messages) {
const result = await runtime.handlePluginApiRoute(
"my-plugin",
"POST",
"/finishJob",
new Request("https://internal/", {
method: "POST",
body: JSON.stringify(message.body),
}),
);
if (result.success) message.ack();
else message.retry();
}
});
},
};
這解析了請求處理器使用的相同快取執行時期,因此外掛儲存、鉤子和媒體存取的行為與請求期間完全相同。在基於連線的資料庫適配器(例如透過 Hyperdrive 的 Postgres)上,回呼在事件範圍的連線下執行,回傳時提交並關閉。
外部呼叫路由
公開路由可以直接呼叫:
curl -X POST https://your-site.com/_emdash/api/plugins/forms/track \
-H "Content-Type: application/json" \
-d '{"event": "pageview"}'
私有路由需要工作階段憑證或具有 admin 作用域的 API 權杖:
curl -X POST https://your-site.com/_emdash/api/plugins/forms/create \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"title": "Hello", "email": "user@example.com"}'
路由上下文參考
// 沙盒路由處理器作為兩個引數接收的內容
interface SandboxedRequest {
url: string;
method: string;
headers: Record<string, string>; // 小寫鍵
}
interface SandboxedRouteContext {
input: unknown; // 使用路由層級的 `input` Zod 綱要縮窄
request: SandboxedRequest;
requestMeta?: unknown;
}
interface PluginContext {
plugin: { id: string; version: string };
storage: PluginStorage;
kv: KVAccess;
log: LogAccess;
site: SiteInfo;
url(path: string): string;
cron?: CronAccess;
content?: ContentAccess; // 當宣告了 content:read 或 content:write
taxonomies?: TaxonomyAccess; // 當宣告了 taxonomies:read
media?: MediaAccess; // 當宣告了 media:read 或 media:write
http?: HttpAccess; // 當宣告了 network:request
users?: UserAccess; // 當宣告了 users:read
email?: EmailAccess; // 當宣告了 email:send 且設定了提供者
}
原生外掛接收一個組合了兩者的單一 RouteContext 引數 — 如果走那條路,請參見建立原生外掛。