6# Creating EmDash Plugins
7
8EmDash plugins extend the CMS with hooks, storage, settings, admin UI, API routes, and custom Portable Text block types. All plugins are TypeScript packages.
9
10## Plugin Types
11
12EmDash has two plugin formats:
13
14| Type | Format | Admin UI | Where it runs |
15| ------------ | ------------------------------------------------------- | ------------------ | ------------------------------------------- |
16| **Standard** | definePlugin({ hooks, routes }) | Block Kit | Isolate on Cloudflare, in-process elsewhere |
17| **Native** | createPlugin() / definePlugin() with id+version | React or Block Kit | Always in host isolate |
18
19**Standard is the default.** Most plugins should use it. Standard plugins can be published to the marketplace and work in both trusted and sandboxed modes.
20
21**Native is an escape hatch** for plugins that need React admin components, direct DB access, or custom Astro components. Native plugins can only run in plugins: [] -- they cannot be sandboxed or published to the marketplace.
22
23## Plugin Anatomy
24
25Every plugin has two parts that **run in different contexts**:
26
271. **Plugin descriptor** (PluginDescriptor) — returned by the factory function in index.ts. Declares metadata (id, version, capabilities, storage). **Runs at build time in Vite** (imported in astro.config.mjs). Must be side-effect-free.
282. **Plugin definition** (definePlugin()) — contains the runtime logic (hooks, routes). **Runs at request time on the deployed server.** Has access to the full plugin context (ctx). Lives in a separate file (typically sandbox-entry.ts).
29
30These must be in **separate entrypoints** because they execute in completely different environments:
31
32```
33my-plugin/
34├── src/
35│ ├── index.ts # Descriptor factory (runs in Vite at build time)
36│ ├── sandbox-entry.ts # Plugin definition with definePlugin() (runs at deploy time)
37│ ├── admin.tsx # Admin UI exports (React) — optional, native only
38│ └── astro/ # Site-side rendering components — optional, native only
39│ └── index.ts # Must export blockComponents
40├── package.json
41└── tsconfig.json
42```
43
44## Minimal Plugin (Standard Format)
45
46The simplest possible plugin -- just hooks:
47
48```typescript
49// src/index.ts — descriptor factory, runs in Vite at build time
50import type { PluginDescriptor } from "emdash";
51
52export function myPlugin(): PluginDescriptor {
53 return {
54 id: "my-plugin",
55 version: "1.0.0",
56 format: "standard",
57 entrypoint: "@my-org/my-plugin/sandbox",
58 options: {},
59 };
60}
61```
62
63```typescript
64// src/sandbox-entry.ts — plugin definition, runs at request time
65import { definePlugin } from "emdash";
66import type { PluginContext } from "emdash";
67
68export default definePlugin({
69 hooks: {
70 "content:afterSave": {
71 handler: async (event: any, ctx: PluginContext) => {
72 ctx.log.info(Saved ${event.collection}/${event.content.id});
73 },
74 },
75 },
76});
77```
78
79The descriptor is what gets imported in astro.config.mjs. The entrypoint field points to the module containing the definePlugin() default export. For standard plugins, this is the ./sandbox export from package.json.
80
81Key differences from native format:
82
83- No id, version, or capabilities in definePlugin() -- those live in the descriptor
84- definePlugin() is an identity function providing type inference
85- Hook handlers use (event, ctx) two-arg pattern
86- Route handlers use (routeCtx, ctx) two-arg pattern
87- Exported as default (not a factory function)
88
89## Plugin ID Rules
90
91- Lowercase alphanumeric + hyphens only
92- Simple (my-plugin) or scoped (@my-org/my-plugin)
93- Unique across all installed plugins
94
95## Registration
96
97The descriptor is imported in astro.config.mjs (Vite context):
98
99```typescript
100import { myPlugin } from "@my-org/my-plugin";
101
102export default defineConfig({
103 integrations: [
104 emdash({
105 plugins: [myPlugin()], // runs in-process
106 // OR
107 sandboxed: [myPlugin()], // runs in isolate on Cloudflare
108 }),
109 ],
110});
111```
112
113Standard plugins work in either array. Native plugins only work in plugins: [].
114
115## Trusted vs Sandboxed Plugins
116
117EmDash has two execution modes. Plugin code is identical in both — only the enforcement changes.
118
119| | Trusted | Sandboxed |
120| ------------------- | ----------------------------------------- | ------------------------------------------------------ |
121| **Runs in** | Main process | Isolated V8 isolate (Dynamic Worker Loader) |
122| **Install method** | astro.config.mjs (code change + deploy) | Admin UI (one-click from marketplace) |
123| **Capabilities** | Advisory (not enforced) | Enforced at runtime via RPC bridge |
124| **Resource limits** | None | CPU 50ms, 10 subrequests, 30s wall-time, ~128MB memory |
125| **Network access** | Unrestricted | Blocked; only via ctx.http with allowedHosts |
126| **Data access** | Full database access | Scoped to declared capabilities |
127| **Node.js APIs** | Full access | Not available (V8 isolate only) |
128| **Available on** | All platforms | Cloudflare Workers only |
129| **Best for** | First-party code, reviewed npm packages | Third-party extensions, marketplace plugins |
130
131### Trusted Mode
132
133Trusted plugins are npm packages or local files added in astro.config.mjs. They run in-process with your Astro site.
134
135- **Capabilities are documentation only.** Declaring ["content:read"] documents intent but isn't enforced — the plugin has full process access.
136- Only install from sources you trust. A malicious trusted plugin has the same access as your application code.
137
138### Sandboxed Mode
139
140Sandboxed plugins run in isolated V8 isolates on Cloudflare Workers via [Dynamic Worker Loader](https://developers.cloudflare.com/workers/runtime-apis/bindings/worker-loader/). Each plugin gets its own isolate.
141
142- **Capabilities are enforced.** If a plugin declares ["content:read"], it can only call ctx.content.get() and ctx.content.list(). Attempting ctx.content.create() throws a permission error.
143- **Network is blocked by default.** Direct fetch() calls fail. Plugins must use ctx.http.fetch(), which validates against allowedHosts.
144- **Storage is scoped.** A plugin can only access its own KV and storage collections.
145- **Admin UI uses Block Kit.** Sandboxed plugins describe their UI as JSON blocks -- no plugin JavaScript runs in the browser. See [Block Kit reference](./references/block-kit.md).
146- **No Portable Text block types.** PT blocks require Astro components for site-side rendering (componentsEntry), which are loaded at build time from npm. Sandboxed plugins are installed at runtime and can't ship components. PT blocks are a native-plugin-only feature.
147- **Routes work.** Standard plugin routes are available in both trusted and sandboxed modes via the sandbox runner's invokeRoute() RPC.
148
149Sandboxing is not available on Node.js. All plugins run in trusted mode on non-Cloudflare platforms.
150
151### Developing for Both Modes
152
153Write the same code. Develop locally in trusted mode (faster iteration, easier debugging). Deploy to sandboxed mode in production without code changes. With the standard format, the same entrypoint serves both modes -- no separate sandbox entry needed.
154
155```typescript
156// src/sandbox-entry.ts -- works in both trusted and sandboxed modes
157import { definePlugin } from "emdash";
158import type { PluginContext } from "emdash";
159
160export default definePlugin({
161 hooks: {
162 "content:afterSave": {
163 handler: async (event: any, ctx: PluginContext) => {
164 // Trusted: ctx.http present because descriptor declares network:request
165 // Sandboxed: ctx.http present and enforced via RPC bridge
166 if (!ctx.http) return;
167 await ctx.http.fetch("https://api.analytics.example.com/track", {
168 method: "POST",
169 body: JSON.stringify({ contentId: event.content.id }),
170 });
171 },
172 },
173 },
174});
175```
176
177Key constraint for sandbox compatibility: **no Node.js built-ins** (fs, path, child_process, etc.) in backend code. Use Web APIs instead.
178
179## Capabilities
180
181Capabilities control what APIs are available on ctx. Always declare what your plugin needs — even in trusted mode, they document intent and are required for sandboxed execution.
182
183| Capability | Grants | ctx property |
184| -------------------------------- | ---------------------------------------------------------------------- | -------------- |
185| content:read | ctx.content.get(), ctx.content.list() | content |
186| content:write | ctx.content.create(), ctx.content.update(), ctx.content.delete() | content |
187| media:read | ctx.media.get(), ctx.media.list() | media |
188| media:write | ctx.media.getUploadUrl(), ctx.media.delete() | media |
189| network:request | ctx.http.fetch() (restricted to allowedHosts) | http |
190| network:request:unrestricted | ctx.http.fetch() (unrestricted — for user-configured URLs) | http |
191| users:read | ctx.users.get(), ctx.users.list(), ctx.users.getByEmail() | users |
192| email:send | ctx.email.send() — send email through the pipeline | email |
193| hooks.email-transport:register | Can register email:deliver exclusive hook (transport provider) | — |
194| hooks.email-events:register | Can register email:beforeSend / email:afterSend hooks | — |
195| hooks.page-fragments:register | Can register page:fragments hook (inject scripts/styles into pages) | — |
196
197Storage (ctx.storage) and KV (ctx.kv) are **always available** — no capability needed. They're automatically scoped to the plugin.
198
199**Email capabilities are distinct:**
200
201- email:send — for plugins that _consume_ email (call ctx.email.send())
202- hooks.email-transport:register — for plugins that _deliver_ email (implement the transport, e.g. Resend, SMTP)
203- hooks.email-events:register — for plugins that _observe or transform_ email (middleware hooks)
204
205```typescript
206// In the descriptor (index.ts)
207export function myPlugin(): PluginDescriptor {
208 return {
209 id: "my-plugin",
210 version: "1.0.0",
211 format: "standard",
212 entrypoint: "@my-org/my-plugin/sandbox",
213 options: {},
214 capabilities: ["content:read", "network:request"],
215 allowedHosts: ["api.example.com", "*.googleapis.com"], // Wildcards supported
216 };
217}
218```
219
220When a marketplace plugin is installed, the admin sees a capability consent dialog listing what the plugin can access. Users must approve before installation.
221
222## Publishing to the Marketplace
223
224Standard plugins can be published to the EmDash Marketplace for one-click installation:
225
226```bash
227emdash plugin bundle --dir packages/plugins/my-plugin # creates .tar.gz
228emdash plugin login # authenticate via GitHub
229emdash plugin publish --tarball dist/my-plugin-1.0.0.tar.gz
230```
231
232See [Publishing Reference](./references/publishing.md) for bundle format, validation, and security audit details.
233
234## Package Exports
235
236Configure package.json exports so EmDash can load each entry point:
237
238```json
239{
240 "name": "@my-org/my-plugin",
241 "type": "module",
242 "exports": {
243 ".": "./src/index.ts",
244 "./sandbox": "./src/sandbox-entry.ts",
245 "./admin": "./src/admin.tsx"
246 },
247 "peerDependencies": {
248 "emdash": "^0.1.0"
249 }
250}
251```
252
253| Export | Context | Purpose |
254| ------------- | ----------------- | ---------------------------------------------------------------------- |
255| "." | Vite (build time) | Descriptor factory -- imported in astro.config.mjs |
256| "./sandbox" | Server (runtime) | definePlugin({ hooks, routes }) -- loaded by entrypoint at runtime |
257| "./admin" | Browser | React components for admin pages/widgets (native plugins only) |
258| "./astro" | Server (SSR) | Astro components for site-side block rendering (native plugins only) |
259
260The "." export has the descriptor. The "./sandbox" export has the implementation. The descriptor's entrypoint field points to "./sandbox". Only include ./admin and ./astro exports for native-format plugins.
261
262## Plugin Features
263
264Each feature is optional. Add only what your plugin needs:
265
266| Feature | Where | Standard | Native | Purpose |
267| ------------------- | ---------------------------- | -------- | ------ | ----------------------------------------------------- |
268| **Hooks** | definePlugin({ hooks }) | Yes | Yes | React to content/media/lifecycle events |
269| **Storage** | descriptor storage | Yes | Yes | Document collections with indexed queries |
270| **KV** | ctx.kv in hooks/routes | Yes | Yes | Key-value store for internal state |
271| **API Routes** | definePlugin({ routes }) | Yes | Yes | REST endpoints at /_emdash/api/plugins/<id>/<route> |
272| **Admin Pages** | Block Kit admin route | Yes | Yes | Admin pages via Block Kit (JSON blocks) |
273| **Widgets** | Block Kit admin route | Yes | Yes | Dashboard cards via Block Kit |
274| **React Admin** | admin.entry + React export | No | Yes | React-based admin pages and widgets (native only) |
275| **PT Blocks** | admin.portableTextBlocks | No | Yes | Custom block types in the Portable Text editor |
276| **Site Components** | componentsEntry | No | Yes | Astro components for rendering blocks on the site |
277
278See the reference files for detailed syntax:
279
280- **[Hooks Reference](./references/hooks.md)** — All hook types, signatures, configuration
281- **[Storage & Settings](./references/storage.md)** — Collections, KV, settings schema
282- **[Admin UI](./references/admin-ui.md)** — Pages, widgets, entry point structure
283- **[API Routes](./references/api-routes.md)** — Route handlers, validation, context
284- **[Block Kit](./references/block-kit.md)** — Declarative UI for sandboxed plugins (similar to Slack Block Kit but not identical)
285- **[Portable Text Blocks](./references/portable-text-blocks.md)** — Custom block types + frontend rendering
286- **[Publishing](./references/publishing.md)** — Bundle format, validation, marketplace publishing
287
288## Complete Example: Standard Plugin with Hooks, Routes, and Storage
289
290```typescript
291// src/index.ts — descriptor factory, runs in Vite at build time
292import type { PluginDescriptor } from "emdash";
293
294export function submissionsPlugin(): PluginDescriptor {
295 return {
296 id: "submissions",
297 version: "1.0.0",
298 format: "standard",
299 entrypoint: "@my-org/plugin-submissions/sandbox",
300 options: {},
301 capabilities: ["content:read"],
302 storage: {
303 submissions: {
304 indexes: ["formId", "status", "createdAt"],
305 },
306 },
307 adminPages: [{ path: "/submissions", label: "Submissions", icon: "list" }],
308 adminWidgets: [{ id: "recent-submissions", title: "Recent Submissions", size: "half" }],
309 };
310}
311```
312
313```typescript
314// src/sandbox-entry.ts — plugin definition, runs at request time
315import { definePlugin } from "emdash";
316import type { PluginContext } from "emdash";
317
318export default definePlugin({
319 hooks: {
320 "plugin:install": {
321 handler: async (_event: any, ctx: PluginContext) => {
322 ctx.log.info("Submissions plugin installed");
323 await ctx.kv.set("settings:maxSubmissions", 1000);
324 },
325 },
326 },
327
328 routes: {
329 submit: {
330 public: true, // No auth required
331 handler: async (routeCtx: any, ctx: PluginContext) => {
332 const { formId, ...data } = routeCtx.input as Record<string, unknown>;
333
334 const count = await ctx.storage.submissions.count({ formId });
335 const max = (await ctx.kv.get<number>("settings:maxSubmissions")) ?? 1000;
336
337 if (count >= max) {
338 return { success: false, error: "Submission limit reached" };
339 }
340
341 const id = ${Date.now()}-${Math.random().toString(36).slice(2)};
342 await ctx.storage.submissions.put(id, {
343 formId,
344 data,
345 status: "pending",
346 createdAt: new Date().toISOString(),
347 });
348
349 return { success: true, id };
350 },
351 },
352
353 list: {
354 handler: async (routeCtx: any, ctx: PluginContext) => {
355 const url = new URL(routeCtx.request.url);
356 const limit = Math.max(
357 1,
358 Math.min(parseInt(url.searchParams.get("limit") || "50", 10) || 50, 100),
359 );
360 const cursor = url.searchParams.get("cursor") || undefined;
361
362 const result = await ctx.storage.submissions.query({
363 orderBy: { createdAt: "desc" },
364 limit,
365 cursor,
366 });
367
368 return {
369 items: result.items.map((item: any) => ({ id: item.id, ...item.data })),
370 cursor: result.cursor,
371 hasMore: result.hasMore,
372 };
373 },
374 },
375
376 // Block Kit admin handler for pages and widgets
377 admin: {
378 handler: async (routeCtx: any, ctx: PluginContext) => {
379 const interaction = routeCtx.input as { type: string; page?: string };
380
381 if (interaction.type === "page_load" && interaction.page === "/submissions") {
382 const result = await ctx.storage.submissions.query({
383 orderBy: { createdAt: "desc" },
384 limit: 50,
385 });
386 return {
387 blocks: [
388 { type: "header", text: "Submissions" },
389 {
390 type: "table",
391 blockId: "submissions-table",
392 columns: [
393 { key: "formId", label: "Form", format: "text" },
394 { key: "status", label: "Status", format: "badge" },
395 { key: "createdAt", label: "Date", format: "relative_time" },
396 ],
397 rows: result.items.map((item: any) => item.data),
398 },
399 ],
400 };
401 }
402
403 return { blocks: [] };
404 },
405 },
406 },
407});
408```
409
410## Plugin Context
411
412All hooks and routes receive ctx (PluginContext):
413
414```typescript
415interface PluginContext {
416 plugin: { id: string; version: string };
417 storage: Record<string, StorageCollection>; // Declared collections
418 kv: KVAccess; // Key-value store
419 log: LogAccess; // Structured logger
420 content?: ContentAccess; // If "content:read" capability
421 media?: MediaAccess; // If "media:read" capability
422 http?: HttpAccess; // If "network:request" capability
423 users?: UserAccess; // If "users:read" capability
424 cron?: CronAccess; // Always available — scoped to plugin
425 email?: EmailAccess; // If "email:send" capability AND a provider is configured
426}
427```
428
429Capabilities are declared in the **descriptor** (not in definePlugin() for standard format):
430
431```typescript
432// In the descriptor
433export function myPlugin(): PluginDescriptor {
434 return {
435 id: "my-plugin",
436 version: "1.0.0",
437 format: "standard",
438 entrypoint: "@my-org/my-plugin/sandbox",
439 options: {},
440 capabilities: ["content:read", "network:request"],
441 allowedHosts: ["api.example.com"],
442 storage: { events: { indexes: ["timestamp"] } },
443 };
444}
445```
446
447## Output Checklist
448
449When creating a standard-format plugin, provide:
450
4511. **src/index.ts** -- Descriptor factory (runs in Vite at build time)
4522. **src/sandbox-entry.ts** -- definePlugin({ hooks, routes }) as default export (runs at request time)
4533. **package.json** -- With exports "." (descriptor) and "./sandbox" (implementation)
4544. **tsconfig.json** -- Standard TypeScript config
455
456For native-format plugins (React admin, PT blocks, Astro components), also provide:
457
4585. **src/admin.tsx** -- Admin entry point with React components
4596. **src/astro/index.ts** -- Block components export (if PT blocks)
460