# Plugin & Extension Development Guide

Demeter is extended in two ways: **Fastify plugins** (cross-cutting API
behaviour) and **domain libraries** (`libs/demeter/*`). This guide shows how to
add each.

## Adding a Fastify plugin

Plugins live in `apps/demeter/api/src/plugins/` and are composed in
`buildServer()` (`src/app.ts`).

1. Create `src/plugins/my-plugin.ts`:

   ```ts
   import fp from 'fastify-plugin';
   import type { FastifyPluginAsync } from 'fastify';

   const impl: FastifyPluginAsync<MyOpts> = async (fastify, opts) => {
     fastify.decorate('myThing', makeThing(opts));
     fastify.addHook('onClose', async () => {
       /* clean up */
     });
   };

   export const myPlugin = fp(impl, {
     name: 'demeter-my-plugin',
     fastify: '5.x',
   });
   ```

2. Register it in `buildServer()` **in the right order** — cross-cutting plugins
   go before routes so routes inherit them. Respect existing ordering (request
   context → error handler → security headers → CORS → rate limit → database →
   redis → auth → swagger → routes).
3. Pin `fastify: '5.x'` so a version mismatch fails fast at boot (see
   [ADR-0002](../architecture/adr/0002-fastify-plugin-architecture.md)).

## Adding a domain library

New domain logic belongs in a library under `libs/demeter/<name>`:

1. Scaffold `project.json`, `package.json` (`@demeter/<name>`), `tsconfig.json`
   - `tsconfig.lib.json` + `tsconfig.spec.json`, `vitest.config.ts`, and
     `src/index.ts`. Add the path mapping to the root `tsconfig.base.json`.
2. Implement **real domain algorithms** with comprehensive types and tests — no
   CRUD-only stubs (see [contributing](contributing.md)).
3. Add a `typedoc.json` (entryPoints `src/index.ts`, scoped to
   `tsconfig.lib.json`) so the library joins the
   [API reference](../library-api-docs.md).
4. Export the public surface from `src/index.ts`; consume it elsewhere via
   `@demeter/<name>`.

> **Check for an existing home first.** Before scaffolding, search
> `libs/demeter` — the 14 existing libraries (core, sensors, automation, plants,
> intelligence, …) likely already own your domain.

## New API resource (route group)

To expose a new resource over HTTP: add `routes/<resource>.ts` (Zod + Fastify
`schema` with tags/summary/responses), a `db/<resource>-store.ts` if it
persists, register it under `/v1` in `routes/index.ts`, and add a
`test/integration/<resource>.integration.spec.ts`. The OpenAPI spec and its
completeness test pick it up automatically.
