フックリファレンス
このページで分かること
- すべてのフックの一覧(実行のきっかけ、変更できるもの、排他かどうか)
- コンテンツ・メディア・ライフサイクル・cron・メール・コメント・ページのフックごとの、必要な権限、イベントの内容、戻り値
- フックの設定、プラグインのコンテキスト、エラーの扱い、実行順
このページの目次
フックを使うと、プラグインは、コンテンツ、メディア、メール、コメント、ページのライフサイクルの決まった時点で、EmDashの動作に割り込んで変更できます。
フックの概要
次の表は、すべてのフックと、それぞれの実行のきっかけ、変更できるもの、排他かどうかの一覧です。
| フック | 実行のきっかけ | 変更できるもの | 排他 |
|---|---|---|---|
content:beforeSave |
コンテンツの保存前 | コンテンツのデータ | いいえ |
content:afterSave |
コンテンツの保存後 | なし | いいえ |
content:beforeDelete |
コンテンツの削除前 | 取り消しできる | いいえ |
content:afterDelete |
コンテンツの削除後 | なし | いいえ |
content:afterPublish |
コンテンツの公開後 | なし | いいえ |
content:afterUnpublish |
コンテンツの非公開後 | なし | いいえ |
content:afterRestore |
コンテンツを元に戻したあと | なし | いいえ |
content:afterSchedule |
コンテンツの予約公開の設定後 | なし | いいえ |
content:afterUnschedule |
コンテンツの予約公開の解除後 | なし | いいえ |
media:beforeUpload |
ファイルのアップロード前 | ファイルのメタデータ | いいえ |
media:afterUpload |
ファイルのアップロード後 | なし | いいえ |
cron |
スケジュールしたタスクの実行時 | なし | いいえ |
email:beforeSend |
メールの配信前 | メッセージ。取り消しできる | いいえ |
email:deliver |
トランスポートを通したメールの配信 | なし | はい |
email:afterSend |
メールの配信に成功したあと | なし | いいえ |
comment:beforeCreate |
コメントの保存前 | コメント。取り消しできる | いいえ |
comment:moderate |
コメントの承認状態の決定 | ステータス | はい |
comment:afterCreate |
コメントの保存後 | なし | いいえ |
comment:afterModerate |
管理者がコメントのステータスを変更したあと | なし | いいえ |
page:metadata |
公開ページのheadの描画 | タグを追加できる | いいえ |
page:fragments |
公開ページのbodyの描画 | スクリプトを挿入できる | いいえ |
plugin:install |
プラグインを最初にインストールしたとき | なし | いいえ |
plugin:activate |
プラグインを有効にしたとき | なし | いいえ |
plugin:deactivate |
プラグインを無効にしたとき | なし | いいえ |
plugin:uninstall |
プラグインを削除したとき | なし | いいえ |
やさしい解説:やさしい解説
WordPressのプラグインがアクションフックやフィルターフックで処理を差し込むのと同じように、EmDashのプラグインも「保存の前」「公開のあと」などの決まった時点に処理を登録します。名前が before で始まるフックは、処理の前に動き、データを書き換えたり、処理を取り消したりできます。after で始まるフックは、処理が終わったあとに動き、通知や外部サービスとの同期に使います。「排他」が「はい」のフックは、メールの配信やコメントの承認判定のように、1つのプラグインだけが担当できるものです。
コンテンツのフック
content:beforeSave
権限(Capability): content:write
コンテンツをデータベースに保存する前に実行されます。コンテンツの検証、変換、情報の追加に使います。サンドボックス型のフックで保存を拒否するには、SAVE_REJECTED エラーと、1〜500文字のプレーンテキストの reason を含む、バージョン1のフックの結果を返します。APIは SAVE_REJECTED を返し、管理画面はプラグインを特定して理由をテキストで表示します。空、長すぎる、形式が不正、または不明なエラーの結果は、一般的な CONTENT_HOOK_ERROR のレスポンスで保存を失敗させます。
ホストのプロセスでは、保存を拒否するには ContentSaveRejectedError(emdash からエクスポートされています)を投げます。どちらの実行方式でも、それ以外の例外は、例外のメッセージを表に出さない一般的なレスポンスで保存を失敗させます。
import { definePlugin } from "emdash";
export default definePlugin({
id: "my-plugin",
version: "1.0.0",
hooks: {
"content:beforeSave": async (event, ctx) => {
const { content, collection, isNew } = event;
// Add timestamps
if (isNew) {
content.createdBy = "system";
}
content.modifiedAt = new Date().toISOString();
// Return modified content
return content;
},
},
});
イベント
interface ActorInfo {
readonly id: string;
readonly role: number;
}
interface ContentHookEvent {
content: Record<string, unknown>; // Content data
collection: string; // Collection slug
isNew: boolean; // True for creates, false for updates
id?: string; // ID of the existing item on updates; absent on creates
actor?: ActorInfo; // Authenticated user that initiated the save
}
更新の場合、content には送信されたフィールドの値だけが入ります。保存済みのアイテムと比べる必要がある場合は、ctx.content.get(event.collection, event.id) で読み込みます。認証済みのREST、ビジュアル編集、MCPからの保存には actor が含まれます。認証済みのユーザーがいない内部の書き込みでは省かれます。
戻り値
- 変更を適用するには、変更したコンテンツのオブジェクトを返します
- 長さに上限のあるプレーンテキストの理由とともに保存を拒否するには、サンドボックスのフックのエラーの包みを返します
- 変更せずにそのまま通すには、
voidを返します
サンドボックス型のフックで保存を拒否するには、次の包み全体を返します。
return {
__emdashSandboxHookResult: true,
version: 1,
error: {
code: "SAVE_REJECTED",
reason: "Add a summary before saving.",
},
};
ホストは reason の前後の空白を取り除き、1〜500文字を受け付けます。
content:afterSave
権限: content:read
コンテンツの保存後に実行されます。通知、キャッシュの無効化、外部との同期などの副作用に使います。
hooks: {
"content:afterSave": async (event, ctx) => {
const { content, collection, isNew } = event;
if (collection === "posts" && content.status === "published") {
// Notify external service
await ctx.http?.fetch("https://api.example.com/notify", {
method: "POST",
body: JSON.stringify({ postId: content.id }),
});
}
},
}
イベント
content:afterSave は、content、collection、isNew と、任意の認証済みの actor を受け取ります。content は保存されたエントリー全体で、データベースのIDは content.id、コレクションのフィールドは content.data の下にあります。content:beforeSave の更新で使われる別の任意の id は、保存後にはありません。
戻り値
戻り値は必要ありません。
content:beforeDelete
権限: content:read
コンテンツの削除前に実行されます。削除の検証や、削除の阻止に使います。
hooks: {
"content:beforeDelete": async (event, ctx) => {
const { id, collection } = event;
// Prevent deletion of protected content
const item = await ctx.content?.get(collection, id);
if (item?.data.protected) {
return false; // Cancel deletion
}
// Allow deletion
return true;
},
}
イベント
interface ContentDeleteEvent {
id: string; // Entry ID
collection: string; // Collection slug
permanent?: false; // Present for native plugins; omitted in the sandbox runtime
}
content:beforeDelete は、エントリーがゴミ箱に移動するときだけ実行されます。ネイティブ型プラグインは permanent: false を受け取り、サンドボックスのランタイムは id と collection だけを送ります。サンドボックス型のフックの中で、このフィールドを使って処理を分けません。完全な削除は content:beforeDelete を通らないため、このフックでは、すでにゴミ箱にあるエントリーを管理者が完全に削除することを防げません。
戻り値
- 削除を取り消すには、
falseを返します - 許可するには、
trueまたはvoidを返します
content:afterDelete
権限: content:read
コンテンツの削除後に実行されます。後片付けの処理に使います。
hooks: {
"content:afterDelete": async (event, ctx) => {
const { id, collection, permanent } = event;
if (permanent) {
await ctx.storage.relatedItems.delete(`${collection}:${id}`);
}
},
}
イベントには id、collection、permanent が含まれます。permanent は、エントリーがゴミ箱に移動したときは false、完全に削除されたときは true です。ゴミ箱から元に戻したエントリーが引き続き必要とするデータを削除する前に、この値を確認します。このフックに戻り値はありません。
content:afterPublish
エントリーの公開に成功したあとに実行されます。予約した日時にEmDashが自動的に公開したエントリーも含みます。別のサービスへの通知や、外部の検索インデックスの更新など、公開されたエントリーに依存する処理に使います。
hooks: {
"content:afterPublish": async (event, ctx) => {
ctx.log.info(`Published ${event.collection}/${event.content.id}`);
},
}
このフックには content:read の権限が必要です。EmDashは公開のレスポンスのあとにこのフックを実行するため、戻り値でエントリーを変更したり、公開を取り消したりはできません。エラーはログに記録されます。errorPolicy: "abort" の場合、後続の公開のフックは実行されません。
content:afterUnpublish
エントリーの非公開に成功したあとに実行されます。外部のシステムが持っているコンテンツのコピーを削除または更新するのに使います。
hooks: {
"content:afterUnpublish": async (event, ctx) => {
ctx.log.info(`Unpublished ${event.collection}/${event.content.id}`);
},
}
このフックの content:read の権限の要件、遅れて実行されること、イベントの形、戻り値がないことは、content:afterPublish と同じです。
content:afterRestore
ゴミ箱に入れたコンテンツを元に戻したあとに実行されます。content:read の権限が必要です。
hooks: {
"content:afterRestore": async (event, ctx) => {
ctx.log.info(`Restored ${event.collection}/${event.content.id}`);
},
}
content:afterSchedule
コンテンツの予約公開を設定したあとに実行されます。content:read の権限が必要です。
hooks: {
"content:afterSchedule": async (event, ctx) => {
ctx.log.info(`Scheduled ${event.collection}/${event.content.id}`);
},
}
content:afterUnschedule
予約公開したコンテンツの予約を解除したあとに実行されます。content:read の権限が必要です。
hooks: {
"content:afterUnschedule": async (event, ctx) => {
ctx.log.info(`Unscheduled ${event.collection}/${event.content.id}`);
},
}
イベント
interface ContentStateChangeEvent {
content: Record<string, unknown>;
collection: string;
}
このイベントの形は、content:afterPublish、content:afterUnpublish、content:afterRestore、content:afterSchedule、content:afterUnschedule で共通です。content は状態が変わったあとのエントリー全体で、id、slug、ステータスを含みます。コレクションのフィールドは content.data の下にあります。
戻り値
戻り値は必要ありません。
メディアのフック
media:beforeUpload
権限: media:write
ファイルのアップロード前に実行されます。ファイルの検証、名前の変更、拒否に使います。
hooks: {
"media:beforeUpload": async (event, ctx) => {
const { file } = event;
// Reject files over 10MB
if (file.size > 10 * 1024 * 1024) {
throw new Error("File too large");
}
// Rename file
return {
name: `${Date.now()}-${file.name}`,
type: file.type,
size: file.size,
};
},
}
イベント
interface MediaUploadEvent {
file: {
name: string; // Original filename
type: string; // MIME type
size: number; // Size in bytes
};
}
戻り値
- 変更を適用するには、変更したファイルのメタデータを返します
- 変更せずにそのまま通すには、
voidを返します - アップロードを拒否するには、例外を投げます
media:afterUpload
権限: media:read
ファイルのアップロード後に実行されます。加工、サムネイルの作成、メタデータの抽出に使います。
hooks: {
"media:afterUpload": async (event, ctx) => {
const { media } = event;
if (media.mimeType.startsWith("image/")) {
// Store image metadata
await ctx.kv.set(`media:${media.id}:analyzed`, {
processedAt: new Date().toISOString(),
});
}
},
}
イベント
interface MediaAfterUploadEvent {
media: {
id: string;
filename: string;
mimeType: string;
size: number | null;
url: string;
createdAt: string;
};
}
戻り値
戻り値は必要ありません。
ライフサイクルのフック
ライフサイクルのフックを登録するのに、権限は必要ありません。
plugin:install
プラグインを最初にインストールしたときに実行されます。初期設定、ストレージのコレクションの作成、データの投入に使います。
hooks: {
"plugin:install": async (event, ctx) => {
// Initialize default settings
await ctx.kv.set("settings:enabled", true);
await ctx.kv.set("settings:threshold", 100);
ctx.log.info("Plugin installed successfully");
},
}
plugin:activate
プラグインを有効にしたとき(インストール後、または再び有効にしたとき)に実行されます。
hooks: {
"plugin:activate": async (event, ctx) => {
ctx.log.info("Plugin activated");
},
}
plugin:deactivate
プラグインを無効にしたときに実行されます。
hooks: {
"plugin:deactivate": async (event, ctx) => {
ctx.log.info("Plugin deactivated");
},
}
plugin:install、plugin:activate、plugin:deactivate は、空のイベントのオブジェクトを受け取ります。戻り値はありません。
plugin:uninstall
プラグインを削除したときに実行されます。後片付けに使います。
hooks: {
"plugin:uninstall": async (event, ctx) => {
const { deleteData } = event;
if (deleteData) {
// Clean up all plugin data
const items = await ctx.kv.list("settings:");
for (const { key } of items) {
await ctx.kv.delete(key);
}
}
ctx.log.info("Plugin uninstalled");
},
}
イベント
interface UninstallEvent {
deleteData: boolean; // User chose to delete data
}
アンインストールのフックに戻り値はありません。
cronのフック
cron
権限: 必要ありません
スケジュールしたタスクが実行されるときに呼び出されます。タスクは ctx.cron.schedule() でスケジュールします。
hooks: {
"cron": async (event, ctx) => {
if (event.name === "daily-sync") {
const data = await ctx.http?.fetch("https://api.example.com/data");
ctx.log.info("Sync complete");
}
},
}
イベント
interface CronEvent {
name: string;
data?: Record<string, unknown>;
scheduledAt: string;
}
cronのフックに戻り値はありません。
メールのフック
プラグインが送信するメッセージでは、メールのフックは email:beforeSend、email:deliver、email:afterSend の順に実行されます。システムの認証用のメッセージは直接 email:deliver に渡され、email:beforeSend と email:afterSend は通りません。
email:beforeSend
権限: hooks.email-events:register
配信の前に実行されるミドルウェアのフックです。メッセージを変換したり、配信を取り消したりします。
hooks: {
"email:beforeSend": async (event, ctx) => {
// Add footer to all emails
return {
...event.message,
text: event.message.text + "\n\n—Sent from My Site",
};
// Or return false to cancel delivery
},
}
イベント
interface EmailBeforeSendEvent {
message: { to: string; subject: string; text: string; html?: string };
source: string;
}
戻り値
- 変換するには、変更したメッセージを返します
- 配信を取り消すには、
falseを返します
email:deliver
権限: hooks.email-transport:register | 排他: はい
トランスポートのプロバイダーです。メールを配信できるのは1つのプラグインだけです。メールのサービスを通して、実際にメッセージを送信する役割を持ちます。
hooks: {
"email:deliver": {
exclusive: true,
handler: async (event, ctx) => {
await sendViaSES(event.message);
},
},
}
イベントと戻り値
interface EmailDeliverEvent {
message: { to: string; subject: string; text: string; html?: string };
source: string;
}
このフックに戻り値はありません。source は、EmDashの認証用のメッセージでは "system"、プラグインが送信したメッセージではそのプラグインのIDです。
email:afterSend
権限: hooks.email-events:register
配信に成功したあとに実行される、結果を待たないフックです。エラーはログに記録されますが、呼び出し元には伝わりません。
hooks: {
"email:afterSend": async (event, ctx) => {
await ctx.kv.set(`email:log:${Date.now()}`, {
to: event.message.to,
subject: event.message.subject,
});
},
}
イベントと戻り値
email:afterSend は、email:deliver と同じ message と source のフィールドを受け取ります。戻り値はありません。
コメントのフック
コメントのフックは、comment:beforeCreate、comment:moderate、comment:afterCreate の順に実行されます。comment:afterModerate フックは、管理者がコメントのステータスを変更したときに別に呼び出されます。
コメントが保存されたあと、フックは次の形のレコードを受け取ります。
interface StoredComment {
id: string;
collection: string;
contentId: string;
parentId: string | null;
authorName: string;
authorEmail: string;
authorUserId: string | null;
body: string;
status: string;
moderationMetadata: Record<string, unknown> | null;
createdAt: string;
updatedAt: string;
}
comment:beforeCreate
権限: users:read
コメントの保存前に実行されるミドルウェアのフックです。コメントに情報を加えたり、検証したり、拒否したりします。
hooks: {
"comment:beforeCreate": async (event, ctx) => {
// Reject comments with links
if (event.comment.body.includes("http")) {
return false;
}
},
}
イベント
interface CommentBeforeCreateEvent {
comment: {
collection: string;
contentId: string;
parentId: string | null;
authorName: string;
authorEmail: string;
authorUserId: string | null;
body: string;
ipHash: string | null;
userAgent: string | null;
};
metadata: Record<string, unknown>;
}
戻り値
- 変換するには、変更したイベントを返します
- 拒否するには、
falseを返します - そのまま通すには、
voidを返します
comment:moderate
権限: users:read | 排他: はい
コメントを承認(approved)、保留(pending)、スパム(spam)のどれにするかを決めます。有効にできるモデレーションのプロバイダーは1つだけです。
hooks: {
"comment:moderate": {
exclusive: true,
handler: async (event, ctx) => {
const score = await checkSpam(event.comment);
return {
status: score > 0.8 ? "spam" : score > 0.5 ? "pending" : "approved",
reason: `Spam score: ${score}`,
};
},
},
}
イベント
interface CommentModerateEvent {
comment: { /* same as beforeCreate */ };
metadata: Record<string, unknown>;
collectionSettings: {
commentsEnabled: boolean;
commentsModeration: "all" | "first_time" | "none";
commentsClosedAfterDays: number;
commentsAutoApproveUsers: boolean;
};
priorApprovedCount: number;
}
戻り値
{ status: "approved" | "pending" | "spam"; reason?: string }
comment:afterCreate
権限: users:read
コメントの保存後に実行される、結果を待たないフックです。通知に使います。メールを送信するには、email:send の権限と、設定済みの email:deliver のプロバイダーも必要です。どちらかがない場合、ctx.email は未定義です。
hooks: {
"comment:afterCreate": async (event, ctx) => {
const recipient = event.contentAuthor?.email;
if (event.comment.status === "approved" && recipient && ctx.email) {
await ctx.email.send({
to: recipient,
subject: `New comment on "${event.content.title}"`,
text: `${event.comment.authorName} commented: ${event.comment.body}`,
});
}
},
}
イベントと戻り値
interface CommentAfterCreateEvent {
comment: StoredComment;
metadata: Record<string, unknown>;
content: { id: string; collection: string; slug: string; title?: string };
contentAuthor?: { id: string; name: string | null; email: string };
}
このフックに戻り値はありません。
comment:afterModerate
権限: users:read
管理者がコメントのステータスを手動で変更したときに実行される、結果を待たないフックです。
イベント
interface CommentAfterModerateEvent {
comment: StoredComment;
previousStatus: string;
newStatus: string;
moderator: { id: string; name: string | null };
}
このフックに戻り値はありません。
ページのフック
ページのフックは、公開ページの描画時に実行されます。プラグインは、これを使ってメタデータやスクリプトを挿入できます。
どちらのページのフックも、現在の公開ページのコンテキストを受け取ります。
interface PublicPageContext {
url: string;
path: string;
locale: string | null;
kind: "content" | "custom";
pageType: string;
title: string | null;
pageTitle?: string | null;
description: string | null;
canonical: string | null;
image: string | null;
content?: { collection: string; id: string; slug: string | null };
seo?: {
ogTitle?: string | null;
ogDescription?: string | null;
ogImage?: string | null;
robots?: string | null;
};
articleMeta?: {
publishedTime?: string | null;
modifiedTime?: string | null;
author?: string | null;
};
siteName?: string;
breadcrumbs?: Array<{ name: string; url: string }>;
siteUrl?: string;
}
interface PageMetadataEvent { page: PublicPageContext }
interface PageFragmentEvent { page: PublicPageContext }
page:metadata
権限: 必要ありません
ページのheadに、metaタグ、Open Graphのプロパティ、JSON-LDの構造化データ、linkタグを追加します。
hooks: {
"page:metadata": async (event, ctx) => {
return [
{ kind: "meta", name: "generator", content: "EmDash" },
{ kind: "property", property: "og:site_name", content: event.page.siteName ?? "My Site" },
{ kind: "jsonld", graph: { "@type": "WebSite", name: event.page.siteName } },
];
},
}
追加できるものの種類
type PageMetadataContribution =
| { kind: "meta"; name: string; content: string; key?: string }
| { kind: "property"; property: string; content: string; key?: string }
| {
kind: "link";
rel: "canonical" | "alternate" | "author" | "license" | "nlweb" | "site.standard.document";
href: string;
hreflang?: string;
key?: string;
}
| {
kind: "jsonld";
id?: string;
graph: Record<string, unknown> | Array<Record<string, unknown>>;
};
key フィールドは、追加する項目の重複をなくします。同じキーを持つ項目は、最後のものだけが使われます。
1つの項目、項目の配列、またはプラグインが追加するものがない場合は null を返します。
page:fragments
権限: hooks.page-fragments:register
ページにスクリプトやHTMLを挿入します。ネイティブ型プラグインだけが使えます。
hooks: {
"page:fragments": async (event, ctx) => {
return [
{
kind: "external-script",
placement: "body:end",
src: "https://analytics.example.com/script.js",
async: true,
},
{
kind: "inline-script",
placement: "head",
code: `window.siteId = "abc123";`,
},
];
},
}
追加できるものの種類
type PageFragmentContribution =
| {
kind: "external-script";
placement: "head" | "body:start" | "body:end";
src: string;
async?: boolean;
defer?: boolean;
attributes?: Record<string, string>;
key?: string;
}
| {
kind: "inline-script";
placement: "head" | "body:start" | "body:end";
code: string;
attributes?: Record<string, string>;
key?: string;
}
| {
kind: "html";
placement: "head" | "body:start" | "body:end";
html: string;
key?: string;
};
1つのフラグメントの項目、項目の配列、またはプラグインが追加するものがない場合は null を返します。
フックの設定
フックには、ハンドラーの関数か、設定のオブジェクトのどちらかを指定できます。
hooks: {
// Simple handler
"content:afterSave": async (event, ctx) => { ... },
// With configuration
"content:beforeSave": {
priority: 50, // Lower runs first (default: 100)
timeout: 10000, // Max execution time in ms (default: 5000)
dependencies: [], // Run after these plugins
errorPolicy: "abort", // "continue" or "abort" (default)
handler: async (event, ctx) => { ... },
},
}
設定のオプション
| オプション | 型 | 既定値 | 説明 |
|---|---|---|---|
priority |
number |
100 |
実行順(小さいほど先に実行) |
timeout |
number |
5000 |
最大の実行時間(ミリ秒) |
dependencies |
string[] |
[] |
先に実行する必要があるプラグインのID |
errorPolicy |
string |
"abort" |
エラーを無視するには "continue" |
exclusive |
boolean |
false |
1つのプラグインだけが有効なプロバイダーになれます(email:deliver、comment:moderate のようなプロバイダー型のフックで使います) |
プラグインのコンテキスト
すべてのフックは、プラグインのAPIを使えるコンテキストのオブジェクトを受け取ります。
interface PluginContext {
plugin: { id: string; version: string };
storage: PluginStorage;
kv: KVAccess;
content?: ContentAccess;
media?: MediaAccess;
http?: HttpAccess;
log: LogAccess;
site: { name: string; url: string; locale: string };
url(path: string): string;
users?: UserAccess;
cron?: CronAccess;
email?: EmailAccess;
}
それぞれのコンテキストのAPIに必要な権限は、権限(Capabilities)とセキュリティを参照してください。
エラーの扱い
フックの中のエラーはログに記録され、errorPolicy に従って扱われます。
"abort"(既定値):実行を止め、該当する場合はトランザクションをロールバックします"continue":エラーをログに記録し、次のフックに進みます
hooks: {
"content:beforeSave": {
errorPolicy: "continue", // Don't block save if this fails
handler: async (event, ctx) => {
try {
await ctx.http?.fetch("https://api.example.com/validate");
} catch (error) {
ctx.log.warn("Validation service unavailable", error);
}
},
},
}
実行順
フックは次の順番で実行されます。
priorityの昇順に並べますdependenciesを持つプラグインは、依存先のあとに実行されます- 同じ
priorityの中の順番は、毎回同じですが、どの順番かは規定されていません
// This runs first (priority 10)
{ priority: 10, handler: ... }
// This runs second (priority 50)
{ priority: 50, handler: ... }
// This runs last (default priority 100)
{ handler: ... }