Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .claude/skills/add-endpoint/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ Follow the layers in order. Look at `src/modules/elements/` as the reference mod
2. **Service** — `<m>.service.ts`: the business rule. Read and write through `TemplateStore` (`store.read()` / `store.update()`). Throw `NotFoundError`, `ConflictError` or `AppError(status, "CODE", message)`; never touch `req`/`res`.
3. **Controller** — `<m>.controller.ts`: arrow-function methods that read the validated `req`, call the service and set the status (`201` + body for create, `204` for update/delete).
4. **Router** — `<m>.router.ts`: `validate({ body, params })` before the controller method.
5. **Wire it** — new module: construct it in `src/routes.ts`.
6. **Contract** — add the operation to `buildOpenApiDocument()` in `src/openapi.ts` (register new named schemas in `components`), then `npm run openapi` to regenerate `openapi.json`.
- Template-scoped route (under `/templates/:templateId`): `Router({ mergeParams: true })`, validate `templateParamsSchema` (or a schema that extends it) on every route, and in the service get the template with `findTemplate(data, templateId)` and call `touch(template)` after changing it.
5. **Wire it** — new module: construct it in `src/routes.ts` (template-scoped routers mount at `/templates/:templateId/<m>`).
6. **Contract** — add the operation to `buildOpenApiDocument()` in `src/openapi.ts` (register new named schemas in `components`; path params via `templateIdParam`, `keyParam()` or `idParam()`), then `npm run openapi` to regenerate `openapi.json`. A new path placeholder also needs a substitute value in `test/openapi.test.ts`.
7. **Tests**
- HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply, and that `db.json` changed as expected.
- HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply (template-scoped routes: add them to the "unknown template" table), and that `db.json` changed as expected. The seed is one template `t1` (`T1 = "/templates/t1"`).
- Pure logic (helpers): `*.test.ts` next to the code.
- `test/openapi.test.ts` fails until `openapi.json` is regenerated, catches documented routes that do not exist, and catches routes missing from `buildOpenApiDocument()`.
8. **Docs** — the endpoint table in `README.md`.
Expand Down
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ body:
label: Request
description: Method, path and body (a curl command is ideal).
placeholder: |
curl -X PATCH localhost:9000/tree/nodes/abc -H 'content-type: application/json' -d '{"title":"x"}'
curl -X PATCH localhost:9000/templates/<templateId>/tree/nodes/abc -H 'content-type: application/json' -d '{"title":"x"}'
validations:
required: true
- type: textarea
Expand Down
10 changes: 9 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
> **Audience:** AI coding agents (Claude Code, Cursor, Copilot, Codex) and people working on this repository.
> **Purpose:** enough context to make safe, consistent changes without rediscovering the layout.

REST API for the [email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs). It stores a tree of template parts and a library of reusable elements, and renders the tree into one HTML email. Read [`README.md`](README.md) for configuration, the endpoint table and Docker.
REST API for the [email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs). It stores email templates (each with its own tree of template parts and its own library of reusable elements), renders a template into one HTML email and keeps a log of sent emails (logged only; nothing is delivered yet). Read [`README.md`](README.md) for configuration, the endpoint table and Docker.

**Stack:** Node 24 (`.nvmrc`), TypeScript 6 (strict, ESM, `NodeNext`), Express 5, zod 4, pino, Vitest + Supertest, ESLint 10 + typescript-eslint, Prettier.

Expand Down Expand Up @@ -34,6 +34,14 @@ request → helmet → cors → request-id → pino-http → json → static
- `src/openapi.ts` builds the OpenAPI 3.1 document from the same zod schemas the routers use.
- `src/config/env.ts` validates environment variables with zod; invalid config stops the server at startup.

## Data and modules

- `db.json` is `{ templates: Template[], sentEmails: SentEmail[] }` (types in `src/storage/db.types.ts`). A `Template` is `{ id, name, tree, elements, createdAt, updatedAt }`. `normalize()` in `src/storage/json-file-store.ts` migrates the v2 `recipeTemplate: { tree, options }` into one "Default template" on load.
- Modules: `templates` (CRUD), `tree`, `elements`, `generate` and `sent-emails`.
- Template-scoped routers (`tree`, `elements`, `generate`, the `send` router of `sent-emails`) are mounted under `/templates/:templateId/...` in `src/routes.ts`. They use `Router({ mergeParams: true })` and validate `templateId` with `templateParamsSchema` (extend it for routes with more params, e.g. `nodeParamsSchema`).
- Services look the template up with `findTemplate(data, templateId)` from `src/modules/templates/templates.helpers.ts` (404 NOT_FOUND if unknown) and call `touch(template)` after every change to its name, tree or elements. Node and element keys are unique within a template.
- `generate` writes `<PUBLIC_DIR>/generated/<templateId>.html`; deleting a template deletes it. Sent-email entries keep a snapshot of the HTML and the template name and survive template deletion.

## API contract

- **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale, documents a route the app does not have, or misses a route the app has.
Expand Down
99 changes: 69 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# email-template-editor-nodejs

REST API for the [LLazyEmail email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs).
It stores a tree of template parts and reusable elements, and renders the tree into a single HTML email.
It stores email templates (each one a tree of template parts plus its own library of reusable elements), renders a template into a single HTML email and keeps a log of sent emails.

Stack: Node 24, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest.

Expand Down Expand Up @@ -46,9 +46,11 @@ src/
common/ errors, logger, middleware (request-id, validate, not-found, error-handler)
storage/ TemplateStore interface + JsonFileStore
modules/
tree/ template tree CRUD
elements/ reusable elements CRUD
templates/ templates CRUD + findTemplate() used by the template-scoped modules
tree/ a template's tree CRUD
elements/ a template's reusable elements CRUD
generate/ tree → HTML rendering
sent-emails/ "send" (log only, no delivery yet) and the sent-emails log
test/ HTTP integration tests + fixtures
```

Expand All @@ -72,23 +74,41 @@ Invalid values stop the server at startup with a clear message.

The machine-readable contract is [`openapi.json`](openapi.json) (OpenAPI 3.1, generated from the zod schemas, also served at `GET /openapi.json`). Agents and contributors: see [`AGENTS.md`](AGENTS.md).

| Method | Path | Body | Success | Errors |
| ------ | ------------------ | -------------------------- | --------------------------- | ------------- |
| GET | `/health` | – | 200 `{ "status": "ok" }` | |
| GET | `/tree` | – | 200 `TreeNode[]` | |
| PUT | `/tree` | `{ treeData: TreeNode[] }` | 204 | 400, 409 |
| POST | `/tree/nodes` | `{ parentKey, item }` | 201 `TreeNode` | 400, 404, 409 |
| PATCH | `/tree/nodes/:key` | `{ title?, value? }` | 204 | 400, 404 |
| DELETE | `/tree/nodes/:key` | – | 204 | 404 |
| GET | `/elements` | – | 200 `Element[]` | |
| POST | `/elements` | `{ key, title, value }` | 201 `Element` | 400, 409 |
| PATCH | `/elements/:key` | `{ title?, value? }` | 204 | 400, 404 |
| DELETE | `/elements/:key` | – | 204 | 404 |
| POST | `/generate` | – | 200 `{ "url": "http://…" }` | 422 |

`TreeNode` is `{ key, title, value, children?: TreeNode[] }` and `Element` is `{ key, title, value }`. All fields are strings. Keys in paths must be URL-encoded.

`POST /generate` renders the tree (each child's `title` placeholder inside its parent's `value` is replaced with the child's rendered value), writes it to `<PUBLIC_DIR>/generated/nmtgTemplate.html` and returns its URL.
Everything except `/health`, `/openapi.json` and `/sent-emails` belongs to one template, so paths start with `/templates/:templateId`.

| Method | Path | Body | Success | Errors |
| ------ | ---------------------------------------- | --------------------------- | --------------------------- | ------------- |
| GET | `/health` | – | 200 `{ "status": "ok" }` | |
| GET | `/templates` | – | 200 `TemplateSummary[]` | |
| POST | `/templates` | `{ name }` | 201 `TemplateSummary` | 400 |
| GET | `/templates/:templateId` | – | 200 `TemplateSummary` | 400, 404 |
| PATCH | `/templates/:templateId` | `{ name }` | 204 | 400, 404 |
| DELETE | `/templates/:templateId` | – | 204 | 400, 404 |
| GET | `/templates/:templateId/tree` | – | 200 `TreeNode[]` | 400, 404 |
| PUT | `/templates/:templateId/tree` | `{ treeData: TreeNode[] }` | 204 | 400, 404, 409 |
| POST | `/templates/:templateId/tree/nodes` | `{ parentKey, item }` | 201 `TreeNode` | 400, 404, 409 |
| PATCH | `/templates/:templateId/tree/nodes/:key` | `{ title?, value? }` | 204 | 400, 404 |
| DELETE | `/templates/:templateId/tree/nodes/:key` | – | 204 | 400, 404 |
| GET | `/templates/:templateId/elements` | – | 200 `Element[]` | 400, 404 |
| POST | `/templates/:templateId/elements` | `{ key, title, value }` | 201 `Element` | 400, 404, 409 |
| PATCH | `/templates/:templateId/elements/:key` | `{ title?, value? }` | 204 | 400, 404 |
| DELETE | `/templates/:templateId/elements/:key` | – | 204 | 400, 404 |
| POST | `/templates/:templateId/generate` | – | 200 `{ "url": "http://…" }` | 400, 404, 422 |
| POST | `/templates/:templateId/send` | `{ to: string[], subject }` | 201 `SentEmailSummary` | 400, 404, 422 |
| GET | `/sent-emails` | – | 200 `SentEmailSummary[]` | |
| GET | `/sent-emails/:id` | – | 200 `SentEmail` | 400, 404 |

All values are strings (or arrays of strings); timestamps are ISO 8601.

- `TemplateSummary` is `{ id, name, createdAt, updatedAt }`. `GET /templates` returns the most recently changed first; any change to a template's name, tree or elements updates `updatedAt`. Template names are 1–200 characters.
- `TreeNode` is `{ key, title, value, children?: TreeNode[] }` and `Element` is `{ key, title, value }`. Node and element keys are unique within a template; two templates can use the same keys.
- `SentEmailSummary` is `{ id, templateId, templateName, to, subject, status: "logged", createdAt }`; `SentEmail` adds `html`.

Template ids are generated by the server (`[A-Za-z0-9_-]`, up to 128 characters; anything else is a 400). Element and node keys in paths must be URL-encoded.

`POST /templates/:templateId/generate` renders the tree (each child's `title` placeholder inside its parent's `value` is replaced with the child's rendered value), writes it to `<PUBLIC_DIR>/generated/<templateId>.html` and returns its URL. Deleting the template deletes that file.

`POST /templates/:templateId/send` takes 1–50 email addresses in `to` and a 1–300 character `subject`. **It does not deliver anything yet:** it renders the template and stores a log entry with a snapshot of the HTML and `status: "logged"`. `GET /sent-emails` lists entries newest first without the HTML; `GET /sent-emails/:id` includes it. Log entries stay after their template is deleted.

### Errors

Expand All @@ -111,14 +131,33 @@ Every error uses the same shape. `requestId` matches the `X-Request-Id` response
}
```

| Status | `code` |
| ------ | ------------------------------------------ |
| 400 | `VALIDATION_ERROR`, `INVALID_JSON` |
| 404 | `NOT_FOUND` (resource or route) |
| 409 | `CONFLICT` (duplicate key) |
| 413 | `PAYLOAD_TOO_LARGE` |
| 422 | `TREE_EMPTY` |
| 500 | `INTERNAL_ERROR` (details are only logged) |
| Status | `code` |
| ------ | ---------------------------------------------------------- |
| 400 | `VALIDATION_ERROR`, `INVALID_JSON` |
| 404 | `NOT_FOUND` (template, node, element, sent email or route) |
| 409 | `CONFLICT` (duplicate key within the template) |
| 413 | `PAYLOAD_TOO_LARGE` |
| 422 | `TREE_EMPTY` (generate or send with an empty tree) |
| 500 | `INTERNAL_ERROR` (details are only logged) |

### Migrating from v2 to v3

v3 keeps any number of templates. On first start the server converts an existing `db.json` from the v2 shape `{ recipeTemplate: { tree, options } }` to `{ templates, sentEmails }`: the old tree and elements become one template named "Default template". Get its id from `GET /templates`. Each template has its own elements.

| v2 | v3 |
| ------------------------- | ----------------------------------------------------------------- |
| `GET /tree` | `GET /templates/:templateId/tree` |
| `PUT /tree` | `PUT /templates/:templateId/tree` |
| `POST /tree/nodes` | `POST /templates/:templateId/tree/nodes` |
| `PATCH /tree/nodes/:key` | `PATCH /templates/:templateId/tree/nodes/:key` |
| `DELETE /tree/nodes/:key` | `DELETE /templates/:templateId/tree/nodes/:key` |
| `GET /elements` | `GET /templates/:templateId/elements` |
| `POST /elements` | `POST /templates/:templateId/elements` |
| `PATCH /elements/:key` | `PATCH /templates/:templateId/elements/:key` |
| `DELETE /elements/:key` | `DELETE /templates/:templateId/elements/:key` |
| `POST /generate` | `POST /templates/:templateId/generate` (file `<templateId>.html`) |

New in v3: `/templates` CRUD, `POST /templates/:templateId/send`, `GET /sent-emails`, `GET /sent-emails/:id`.

### Migrating from v1 routes

Expand Down Expand Up @@ -148,12 +187,12 @@ Data lives in `/app/data/db.json`. Mount a volume there so it survives container

### Sample data

The repository's `db.json` holds a complete example: a No More To-Go "Weekly Menu" issue.
The repository's `db.json` holds one template, "Default template": a complete No More To-Go "Weekly Menu" issue. The sent-emails log is empty.

- **Tree:** the root HTML has three slots (`{{items}}`, `{{items2}}`, `{{items3}}`). Each slot holds a two-column row with two recipe cards, six recipes in total. Each card's `{{link}}`, `{{image}}`, `{{title}}` and `{{subtitle}}` are filled.
- **Elements:** `{{twoBlocks}}` (two-column row), `{{recipeCard}}` (photo, title and subtitle) and `{{textBlock}}` (a paragraph).

Every child's title appears in its parent's HTML, and keys are unique. `POST /generate` renders the issue with no placeholders left over.
Every child's title appears in its parent's HTML, and keys are unique. `POST /templates/:templateId/generate` renders the issue with no placeholders left over.

Development with hot reload:

Expand Down
477 changes: 242 additions & 235 deletions db.json

Large diffs are not rendered by default.

Loading