APIルート

このページ

プラグインは管理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 SandboxedPluginrouteCtxctx を推論します — パラメータアノテーションは不要です。サンドボックスルートハンドラは2つの引数を取ります:(routeCtx, ctx)

  • routeCtx はリクエスト関連のデータを持ちます:{ input, request, requestMeta }
  • ctx はフックで取得するのと同じ PluginContext です — ctx.storagectx.kvctx.contentctx.httpctx.log など。

ルートURL

ルートは /_emdash/api/plugins/<slug>/<route-name> にマウントされます。ルート名にはネストされたパス用のスラッシュを含めることができます。

プラグインIDルート名URL
formsstatus/_emdash/api/plugins/forms/status
formssubmissions/_emdash/api/plugins/forms/submissions
seosettings/save/_emdash/api/plugins/seo/settings/save
analyticsevents/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はこれを自動的に送信します。トークン認証リクエストは免除されます。

ルートをauthと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.requestSandboxedRequest です:プロセス内とアイソレート内で同一に動作するポータブルな { 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/middlewarewithEmDashRuntime() を使用してランタイムを直接取得し、リクエストなしでプラグインルートを呼び出します:

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"}'

ルートコンテキストリファレンス

// サンドボックスルートハンドラが2つの引数として受け取るもの

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が宣言されてプロバイダが設定されている場合
}

ネイティブプラグインは2つを組み合わせた単一の RouteContext 引数を受け取ります — その道を進む場合はネイティブプラグインの作成を参照してください。