From 954babe91b2d29df4df8465772d065a2af4a7b4b Mon Sep 17 00:00:00 2001 From: Vadim Date: Tue, 17 Nov 2026 11:36:36 +0000 Subject: [PATCH] Add an OpenAPI contract, agent guide and Claude Code setup; move to Node 24 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - openapi.json (OpenAPI 3.1) is built from the zod schemas the routers validate with (src/openapi.ts, z.toJSONSchema), served at GET /openapi.json and regenerated with `npm run openapi`. test/openapi.test.ts fails when the committed file is stale or documents a route the app does not have. - AGENTS.md: stack, layers, rules, the contract and the workflow. - .claude/settings.json (common checks without a prompt, .env unreadable), a PostToolUse format-and-lint hook, and an add-endpoint skill with the schema → service → controller → router → openapi → tests checklist. - Node 24 (Active LTS): .nvmrc, engines, @types/node 24, Dockerfile, docker-compose. CI: checkout/setup-node v7, Node from .nvmrc, read-only token, cancel superseded runs. - PR template, issue forms and CODEOWNERS. --- .claude/hooks/format-and-lint.sh | 35 ++ .claude/settings.json | 39 ++ .claude/skills/add-endpoint/SKILL.md | 27 ++ .github/CODEOWNERS | 2 + .github/ISSUE_TEMPLATE/bug.yml | 31 ++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature.yml | 31 ++ .github/pull_request_template.md | 19 + .github/workflows/ci.yml | 15 +- .gitignore | 3 + .nvmrc | 1 + .prettierignore | 2 + AGENTS.md | 71 ++++ Dockerfile | 4 +- README.md | 5 +- docker-compose.yml | 2 +- openapi.json | 596 +++++++++++++++++++++++++++ package-lock.json | 37 +- package.json | 5 +- scripts/write-openapi.ts | 8 + src/openapi.ts | 207 ++++++++++ src/routes.ts | 6 + test/openapi.test.ts | 68 +++ tsconfig.json | 2 +- 24 files changed, 1193 insertions(+), 28 deletions(-) create mode 100755 .claude/hooks/format-and-lint.sh create mode 100644 .claude/settings.json create mode 100644 .claude/skills/add-endpoint/SKILL.md create mode 100644 .github/CODEOWNERS create mode 100644 .github/ISSUE_TEMPLATE/bug.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature.yml create mode 100644 .github/pull_request_template.md create mode 100644 .nvmrc create mode 100644 AGENTS.md create mode 100644 openapi.json create mode 100644 scripts/write-openapi.ts create mode 100644 src/openapi.ts create mode 100644 test/openapi.test.ts diff --git a/.claude/hooks/format-and-lint.sh b/.claude/hooks/format-and-lint.sh new file mode 100755 index 0000000..3aa2d54 --- /dev/null +++ b/.claude/hooks/format-and-lint.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# PostToolUse hook: format the file Claude just edited and report lint errors back to it. +# Input: the hook JSON on stdin (tool_input.file_path). Exit 2 sends stderr to Claude. +set -euo pipefail + +file=$(jq -r '.tool_input.file_path // empty') +[[ -z "$file" || ! -f "$file" ]] && exit 0 + +cd "$CLAUDE_PROJECT_DIR" + +# Only files inside this repository. +case "$(realpath "$file")" in + "$(realpath "$CLAUDE_PROJECT_DIR")"/*) ;; + *) exit 0 ;; +esac + +case "$file" in + *.ts | *.js | *.mjs | *.cjs | *.json | *.md | *.yml | *.yaml) ;; + *) exit 0 ;; +esac + +# Respects .prettierignore; unknown file types are skipped. +npx --no-install prettier --write --ignore-unknown --log-level warn "$file" >/dev/null + +case "$file" in + *.ts | *.js | *.mjs | *.cjs) + if ! out=$(npx --no-install eslint --fix --no-warn-ignored "$file" 2>&1); then + echo "ESLint errors in $file (fix them before finishing):" >&2 + echo "$out" >&2 + exit 2 + fi + ;; +esac + +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..dd96955 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,39 @@ +{ + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "permissions": { + "allow": [ + "Bash(npm run lint:*)", + "Bash(npm run typecheck:*)", + "Bash(npm run format:*)", + "Bash(npm test:*)", + "Bash(npm run test:*)", + "Bash(npm run build:*)", + "Bash(npm run openapi:*)", + "Bash(npx vitest:*)", + "Bash(npx eslint:*)", + "Bash(npx prettier:*)", + "Bash(git status:*)", + "Bash(git diff:*)", + "Bash(git log:*)", + "Bash(git show:*)", + "Bash(gh pr view:*)", + "Bash(gh pr list:*)", + "Bash(gh pr checks:*)" + ], + "deny": ["Read(./.env)", "Read(./.env.local)", "Read(./.env.production)"] + }, + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-and-lint.sh", + "timeout": 60 + } + ] + } + ] + } +} diff --git a/.claude/skills/add-endpoint/SKILL.md b/.claude/skills/add-endpoint/SKILL.md new file mode 100644 index 0000000..b168ef9 --- /dev/null +++ b/.claude/skills/add-endpoint/SKILL.md @@ -0,0 +1,27 @@ +--- +name: add-endpoint +description: "Add or change a REST endpoint of the email template editor API. Use when adding a route, changing a request or response shape, or adding a feature module under src/modules." +--- + +# Add or change an endpoint + +Follow the layers in order. Look at `src/modules/elements/` as the reference module. + +1. **Schema** — `src/modules//.schemas.ts`: zod schemas for the body and path params, plus `z.infer` types. Trim and require keys (`z.string().trim().min(1)`). +2. **Service** — `.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** — `.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** — `.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`. +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. + - Pure logic (helpers): `*.test.ts` next to the code. + - `test/openapi.test.ts` fails until `openapi.json` is regenerated and catches documented routes that do not exist. +8. **Docs** — the endpoint table in `README.md`. +9. **Frontend** — if the shape or path changed, the frontend's `src/api/main.ts` and `main.types.ts` need a matching PR in `email-template-editor-reactjs`. + +## Check + +```bash +npm run lint && npm run typecheck && npm run format:check && npm test && npm run build +``` diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..92e6141 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Reviewers requested automatically for every pull request. +* @vadim9999 diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..e80d133 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,31 @@ +name: Bug report +description: An endpoint does not behave as documented in openapi.json. +labels: [bug] +body: + - type: textarea + id: request + attributes: + 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"}' + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected response + validations: + required: true + - type: textarea + id: actual + attributes: + label: Actual response + description: Status, body and the requestId from the error, if any. + validations: + required: true + - type: textarea + id: environment + attributes: + label: Environment + description: Commit or image tag, how it runs (npm run dev, Docker), relevant env vars. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..413fd18 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Editor UI issue + url: https://github.com/LLazyEmail/email-template-editor-reactjs/issues + about: Problems in the editor interface belong to the frontend repository. diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000..de93b02 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,31 @@ +name: Feature request +description: A new endpoint or a change to an existing one. +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: Problem + description: What the editor (or another client) cannot do today. + validations: + required: true + - type: textarea + id: api + attributes: + label: Proposed API + description: Method, path, request and response bodies, error cases. + validations: + required: true + - type: textarea + id: acceptance + attributes: + label: Acceptance criteria + description: Checkable statements that define "done". They become the tests. + validations: + required: true + - type: checkboxes + id: frontend + attributes: + label: Frontend impact + options: + - label: Needs a matching change in email-template-editor-reactjs diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..aea6039 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,19 @@ +## What + + + +## Why + + + +## How to verify + + + +## Checklist + +- [ ] One concern per PR +- [ ] `npm run lint`, `npm run typecheck`, `npm run format:check` pass +- [ ] `npm test` passes; new behavior has a test +- [ ] Routes or schemas changed → `npm run openapi` run, `openapi.json` and the README endpoint table updated +- [ ] Breaking API change → matching PR in email-template-editor-reactjs linked diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 560cbbd..3f745c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,14 +6,21 @@ on: pull_request: branches: [main] +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 with: - node-version: 22 + node-version-file: .nvmrc cache: npm - run: npm ci - run: npm run lint @@ -25,5 +32,5 @@ jobs: docker: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - run: docker build -t email-template-editor-nodejs . diff --git a/.gitignore b/.gitignore index 6f317a0..1a59153 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ dist coverage .env *.tmp + +# Claude Code: personal overrides (shared settings are in .claude/settings.json) +.claude/settings.local.json diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..a45fd52 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24 diff --git a/.prettierignore b/.prettierignore index c981a07..0ff556e 100644 --- a/.prettierignore +++ b/.prettierignore @@ -5,3 +5,5 @@ public db.json package-lock.json test/fixtures +# generated by `npm run openapi` +openapi.json diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d296355 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,71 @@ +# AI Agent Guide — email-template-editor-nodejs + +> **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. + +**Stack:** Node 24 (`.nvmrc`), TypeScript 6 (strict, ESM, `NodeNext`), Express 5, zod 4, pino, Vitest + Supertest, ESLint 10 + typescript-eslint, Prettier. + +## Commands + +```bash +npm run dev # http://localhost:9000, hot reload (tsx) +npm run lint # ESLint +npm run typecheck # tsc --noEmit +npm run format # Prettier (format:check runs in CI) +npm test # unit + HTTP integration tests +npm run build # compile to dist/ +npm run openapi # regenerate openapi.json after changing a route or schema +``` + +## Architecture + +``` +request → helmet → cors → request-id → pino-http → json → static + → router src/modules//.router.ts routes + validate({ body, params }) with zod + → controller src/modules//.controller.ts HTTP only: read req, write res + → service src/modules//.service.ts business rules, throws AppError + → store src/storage/template-store.ts interface; JsonFileStore (db.json) + → not-found → error-handler one JSON error shape for everything +``` + +- `src/routes.ts` is the composition root: it wires store → services → controllers → routers and serves `/health` and `/openapi.json`. +- `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. + +## 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 or documents a route the app does not have. +- The frontend's request types (`src/api/main.types.ts` in the frontend repo) must match it. A breaking change here needs a matching frontend PR. +- Errors are always `{ error: { code, message, details?, requestId } }` (see `src/common/middleware/error-handler.ts`). +- Keys in paths are URL-encoded by the client. + +## Rules + +- Validate every body and path parameter with a zod schema in `.schemas.ts` through `validate()`. Controllers trust `req.body` / `req.params` after that. +- Services throw `AppError` subclasses (`ValidationError`, `NotFoundError`, `ConflictError`, or `AppError(status, CODE, message)`); never write responses from a service. +- Persistence only through the `TemplateStore` interface. Do not read or write `db.json` elsewhere. +- No `console.*` (ESLint `no-console`); log with the request logger `req.log` or the injected `logger`. +- ESM with `.js` extensions in relative imports (`NodeNext`). `import type` for types (`consistent-type-imports`). +- Tests: HTTP behavior in `test/*.test.ts` with Supertest against `createApp()` and a temp `db.json`; pure logic next to the code (`*.test.ts`). Never touch the real `db.json` from tests. +- Keep `README.md`'s endpoint table in sync with `openapi.json`. + +## Agent tooling + +- `.claude/settings.json`: common checks run without a prompt; `.env` is not readable. Personal overrides go to `.claude/settings.local.json` (git-ignored). +- PostToolUse hook `.claude/hooks/format-and-lint.sh`: Prettier and `eslint --fix` after each edit; remaining ESLint errors go back to the agent. +- Skill `add-endpoint`: the full checklist for a new or changed route. + +## Workflow + +1. Branch from `main`. One concern per PR. +2. Make the change and add or update tests. +3. `npm run lint && npm run typecheck && npm run format:check && npm test && npm run build`; `npm run openapi` if routes or schemas changed. +4. Open a PR using `.github/pull_request_template.md`. + +## Things to avoid + +- Do not commit `.env` or real data in `db.json` (it is sample data that seeds the Docker image). +- Do not add routes without schemas, tests and an `openapi.json` update. +- Do not change the error shape or route paths without a matching frontend change. diff --git a/Dockerfile b/Dockerfile index aace759..4c389ca 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # syntax=docker/dockerfile:1 -FROM node:22-alpine AS build +FROM node:24-alpine AS build WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci @@ -8,7 +8,7 @@ COPY tsconfig.json tsconfig.build.json ./ COPY src ./src RUN npm run build -FROM node:22-alpine AS runtime +FROM node:24-alpine AS runtime ENV NODE_ENV=production \ PORT=9000 \ DB_FILE=/app/data/db.json \ diff --git a/README.md b/README.md index 241b5ee..a3c538e 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ 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. -Stack: Node 22, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest. +Stack: Node 24, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest. ## Quick start @@ -22,6 +22,7 @@ npm run dev # http://localhost:9000, hot reload, pretty logs | `npm run typecheck` | `tsc --noEmit` | | `npm run lint` | ESLint | | `npm run format` | Prettier (`format:check` is used in CI) | +| `npm run openapi` | Regenerate `openapi.json` from the schemas | ## Architecture @@ -69,6 +70,8 @@ Invalid values stop the server at startup with a clear message. ## API +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" }` | | diff --git a/docker-compose.yml b/docker-compose.yml index 0b9333e..19ccd4b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ # Development: runs the API with hot reload against the local db.json services: api: - image: node:22-alpine + image: node:24-alpine command: sh -c "npm ci && npm run dev" working_dir: /app environment: diff --git a/openapi.json b/openapi.json new file mode 100644 index 0000000..0874792 --- /dev/null +++ b/openapi.json @@ -0,0 +1,596 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Email template editor API", + "version": "2.0.0", + "description": "Stores the template tree and the library of reusable elements, and renders the tree into one HTML email. Errors always have the ErrorResponse shape." + }, + "servers": [ + { + "url": "http://localhost:9000", + "description": "Local development" + } + ], + "paths": { + "/health": { + "get": { + "summary": "Liveness check", + "responses": { + "200": { + "description": "Up", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + } + } + } + }, + "/openapi.json": { + "get": { + "summary": "This document", + "responses": { + "200": { + "description": "OpenAPI 3.1 document" + } + } + } + }, + "/tree": { + "get": { + "summary": "Get the whole template tree", + "responses": { + "200": { + "description": "Root nodes", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TreeNode" + } + } + } + } + } + } + }, + "put": { + "summary": "Replace the whole template tree", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SaveTreeBody" + } + } + } + }, + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "409": { + "description": "Key already exists (CONFLICT)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/tree/nodes": { + "post": { + "summary": "Add a node under a parent", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AddNodeBody" + } + } + } + }, + "responses": { + "201": { + "description": "The added node", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TreeNode" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "409": { + "description": "Key already exists (CONFLICT)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/tree/nodes/{key}": { + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "description": "Tree node key, URL-encoded", + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "patch": { + "summary": "Change a node's title and/or value", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateNodeBody" + } + } + } + }, + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "delete": { + "summary": "Delete a node and its children", + "responses": { + "204": { + "description": "Done" + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/elements": { + "get": { + "summary": "List library elements", + "responses": { + "200": { + "description": "All elements", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Element" + } + } + } + } + } + } + }, + "post": { + "summary": "Add a library element", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateElementBody" + } + } + } + }, + "responses": { + "201": { + "description": "The added element", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Element" + } + } + } + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "409": { + "description": "Key already exists (CONFLICT)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "413": { + "description": "Body too large (PAYLOAD_TOO_LARGE)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/elements/{key}": { + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "description": "Element key, URL-encoded", + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "patch": { + "summary": "Change an element's title and/or value", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateElementBody" + } + } + } + }, + "responses": { + "204": { + "description": "Done" + }, + "400": { + "description": "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + }, + "delete": { + "summary": "Delete an element", + "responses": { + "204": { + "description": "Done" + }, + "404": { + "description": "Not found (NOT_FOUND)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + }, + "/generate": { + "post": { + "summary": "Render the tree into an HTML file and return its URL", + "responses": { + "200": { + "description": "Link to the generated file", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GenerateResponse" + } + } + } + }, + "422": { + "description": "Template tree is empty (TREE_EMPTY)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "TreeNode": { + "type": "object", + "properties": { + "key": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string" + }, + "value": { + "default": "", + "type": "string" + }, + "children": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TreeNode" + } + } + }, + "required": [ + "key", + "title" + ] + }, + "Element": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "title": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": [ + "key", + "title", + "value" + ] + }, + "SaveTreeBody": { + "type": "object", + "properties": { + "treeData": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TreeNode" + } + } + }, + "required": [ + "treeData" + ] + }, + "AddNodeBody": { + "type": "object", + "properties": { + "parentKey": { + "type": "string", + "minLength": 1 + }, + "item": { + "$ref": "#/components/schemas/TreeNode" + } + }, + "required": [ + "parentKey", + "item" + ] + }, + "UpdateNodeBody": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "CreateElementBody": { + "type": "object", + "properties": { + "key": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string" + }, + "value": { + "default": "", + "type": "string" + } + }, + "required": [ + "key", + "title" + ] + }, + "UpdateElementBody": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "GenerateResponse": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "Absolute URL of the generated HTML file" + } + }, + "required": [ + "url" + ] + }, + "ErrorResponse": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "Machine-readable code, e.g. VALIDATION_ERROR, NOT_FOUND" + }, + "message": { + "type": "string" + }, + "details": { + "description": "Validation issues for VALIDATION_ERROR" + }, + "requestId": { + "description": "Same as the X-Request-Id response header", + "type": "string" + } + }, + "required": [ + "code", + "message" + ] + } + }, + "required": [ + "error" + ] + }, + "Health": { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "ok" + } + }, + "required": [ + "status" + ] + } + } + } +} diff --git a/package-lock.json b/package-lock.json index 04294ae..0dbc9e5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "email-template-editor-nodejs", - "version": "1.0.0", + "version": "2.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "email-template-editor-nodejs", - "version": "1.0.0", + "version": "2.0.0", "license": "ISC", "dependencies": { "cors": "^2.8.6", @@ -20,7 +20,7 @@ "@eslint/js": "^10.0.1", "@types/cors": "^2.8.19", "@types/express": "^5.0.6", - "@types/node": "^22.20.5", + "@types/node": "^24.19.2", "@types/supertest": "^7.2.1", "eslint": "^10.14.0", "pino-pretty": "^13.2.0", @@ -30,6 +30,9 @@ "typescript": "^6.0.3", "typescript-eslint": "^8.72.2", "vitest": "^5.1.0" + }, + "engines": { + "node": ">=24" } }, "node_modules/@cacheable/memory": { @@ -1271,13 +1274,13 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "22.20.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", - "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": "~6.21.0" + "undici-types": ">=7.24.0 <7.24.7" } }, "node_modules/@types/qs": { @@ -4309,9 +4312,9 @@ } }, "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", "dev": true, "license": "MIT" }, @@ -5255,12 +5258,12 @@ "dev": true }, "@types/node": { - "version": "22.20.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", - "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", "dev": true, "requires": { - "undici-types": "~6.21.0" + "undici-types": ">=7.24.0 <7.24.7" } }, "@types/qs": { @@ -7120,9 +7123,9 @@ } }, "undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", "dev": true }, "unpipe": { diff --git a/package.json b/package.json index 74d8a3e..658b5a2 100644 --- a/package.json +++ b/package.json @@ -6,13 +6,14 @@ "type": "module", "main": "dist/server.js", "engines": { - "node": ">=22" + "node": ">=24" }, "scripts": { "dev": "tsx watch --clear-screen=false src/server.ts", "build": "tsc -p tsconfig.build.json", "start": "node dist/server.js", "typecheck": "tsc --noEmit", + "openapi": "tsx scripts/write-openapi.ts", "lint": "eslint .", "format": "prettier --write .", "format:check": "prettier --check .", @@ -41,7 +42,7 @@ "@eslint/js": "^10.0.1", "@types/cors": "^2.8.19", "@types/express": "^5.0.6", - "@types/node": "^22.20.5", + "@types/node": "^24.19.2", "@types/supertest": "^7.2.1", "eslint": "^10.14.0", "pino-pretty": "^13.2.0", diff --git a/scripts/write-openapi.ts b/scripts/write-openapi.ts new file mode 100644 index 0000000..696353c --- /dev/null +++ b/scripts/write-openapi.ts @@ -0,0 +1,8 @@ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { buildOpenApiDocument } from "../src/openapi.js"; + +// Regenerates openapi.json from the zod schemas. Run after changing a route or a schema. +const file = path.join(import.meta.dirname, "..", "openapi.json"); +await writeFile(file, `${JSON.stringify(buildOpenApiDocument(), null, 2)}\n`); +process.stdout.write(`Wrote ${path.relative(process.cwd(), file)}\n`); diff --git a/src/openapi.ts b/src/openapi.ts new file mode 100644 index 0000000..7332f0f --- /dev/null +++ b/src/openapi.ts @@ -0,0 +1,207 @@ +import { z } from "zod"; +import { + createElementBodySchema, + updateElementBodySchema, +} from "./modules/elements/elements.schemas.js"; +import { + addNodeBodySchema, + saveTreeBodySchema, + treeNodeSchema, + updateNodeBodySchema, +} from "./modules/tree/tree.schemas.js"; + +/** + * OpenAPI 3.1 description of the REST API, built from the same zod schemas the routers validate + * with, so the contract cannot drift from the code. Served at GET /openapi.json and committed as + * openapi.json (`npm run openapi`); a test fails when the committed file is out of date. + */ + +const elementSchema = z.object({ key: z.string(), title: z.string(), value: z.string() }); + +const generateResponseSchema = z.object({ + url: z.string().describe("Absolute URL of the generated HTML file"), +}); + +const errorResponseSchema = z.object({ + error: z.object({ + code: z.string().describe("Machine-readable code, e.g. VALIDATION_ERROR, NOT_FOUND"), + message: z.string(), + details: z.unknown().optional().describe("Validation issues for VALIDATION_ERROR"), + requestId: z.string().optional().describe("Same as the X-Request-Id response header"), + }), +}); + +const healthSchema = z.object({ status: z.literal("ok") }); + +/** Named schemas; each becomes #/components/schemas/. */ +const components = { + TreeNode: treeNodeSchema, + Element: elementSchema, + SaveTreeBody: saveTreeBodySchema, + AddNodeBody: addNodeBodySchema, + UpdateNodeBody: updateNodeBodySchema, + CreateElementBody: createElementBodySchema, + UpdateElementBody: updateElementBodySchema, + GenerateResponse: generateResponseSchema, + ErrorResponse: errorResponseSchema, + Health: healthSchema, +} satisfies Record; + +type SchemaName = keyof typeof components; + +const ref = (name: SchemaName) => ({ $ref: `#/components/schemas/${name}` }); +const json = (schema: object) => ({ content: { "application/json": { schema } } }); + +const ERROR_TEXT = { + 400: "Invalid request (VALIDATION_ERROR, INVALID_JSON)", + 404: "Not found (NOT_FOUND)", + 409: "Key already exists (CONFLICT)", + 413: "Body too large (PAYLOAD_TOO_LARGE)", + 422: "Template tree is empty (TREE_EMPTY)", +} as const; + +const errors = (...statuses: (keyof typeof ERROR_TEXT)[]) => + Object.fromEntries( + statuses.map((status) => [ + String(status), + { description: ERROR_TEXT[status], ...json(ref("ErrorResponse")) }, + ]), + ); + +const body = (name: SchemaName) => ({ required: true, ...json(ref(name)) }); +const noContent = { "204": { description: "Done" } }; + +const keyParam = (what: string) => ({ + name: "key", + in: "path", + required: true, + description: `${what} key, URL-encoded`, + schema: { type: "string", minLength: 1 }, +}); + +function componentSchemas(): Record { + const registry = z.registry<{ id: string }>(); + for (const [id, schema] of Object.entries(components)) registry.add(schema, { id }); + + const { schemas } = z.toJSONSchema(registry, { + // Request bodies are the main use; fields with defaults (value: "") are optional on input. + io: "input", + uri: (id) => `#/components/schemas/${id}`, + }); + + // OpenAPI component schemas do not carry their own $schema / $id. + return Object.fromEntries( + Object.entries(schemas).map(([id, schema]) => { + const rest: Record = { ...schema }; + delete rest.$schema; + delete rest.$id; + return [id, rest]; + }), + ); +} + +export function buildOpenApiDocument() { + return { + openapi: "3.1.0", + info: { + title: "Email template editor API", + version: "2.0.0", + description: + "Stores the template tree and the library of reusable elements, and renders the tree into one HTML email. Errors always have the ErrorResponse shape.", + }, + servers: [{ url: "http://localhost:9000", description: "Local development" }], + paths: { + "/health": { + get: { + summary: "Liveness check", + responses: { "200": { description: "Up", ...json(ref("Health")) } }, + }, + }, + "/openapi.json": { + get: { + summary: "This document", + responses: { "200": { description: "OpenAPI 3.1 document" } }, + }, + }, + "/tree": { + get: { + summary: "Get the whole template tree", + responses: { + "200": { + description: "Root nodes", + ...json({ type: "array", items: ref("TreeNode") }), + }, + }, + }, + put: { + summary: "Replace the whole template tree", + requestBody: body("SaveTreeBody"), + responses: { ...noContent, ...errors(400, 409, 413) }, + }, + }, + "/tree/nodes": { + post: { + summary: "Add a node under a parent", + requestBody: body("AddNodeBody"), + responses: { + "201": { description: "The added node", ...json(ref("TreeNode")) }, + ...errors(400, 404, 409, 413), + }, + }, + }, + "/tree/nodes/{key}": { + parameters: [keyParam("Tree node")], + patch: { + summary: "Change a node's title and/or value", + requestBody: body("UpdateNodeBody"), + responses: { ...noContent, ...errors(400, 404) }, + }, + delete: { + summary: "Delete a node and its children", + responses: { ...noContent, ...errors(404) }, + }, + }, + "/elements": { + get: { + summary: "List library elements", + responses: { + "200": { + description: "All elements", + ...json({ type: "array", items: ref("Element") }), + }, + }, + }, + post: { + summary: "Add a library element", + requestBody: body("CreateElementBody"), + responses: { + "201": { description: "The added element", ...json(ref("Element")) }, + ...errors(400, 409, 413), + }, + }, + }, + "/elements/{key}": { + parameters: [keyParam("Element")], + patch: { + summary: "Change an element's title and/or value", + requestBody: body("UpdateElementBody"), + responses: { ...noContent, ...errors(400, 404) }, + }, + delete: { + summary: "Delete an element", + responses: { ...noContent, ...errors(404) }, + }, + }, + "/generate": { + post: { + summary: "Render the tree into an HTML file and return its URL", + responses: { + "200": { description: "Link to the generated file", ...json(ref("GenerateResponse")) }, + ...errors(422), + }, + }, + }, + }, + components: { schemas: componentSchemas() }, + }; +} diff --git a/src/routes.ts b/src/routes.ts index b1475cc..a187ab5 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -8,6 +8,7 @@ import { GenerateService } from "./modules/generate/generate.service.js"; import { TreeController } from "./modules/tree/tree.controller.js"; import { createTreeRouter } from "./modules/tree/tree.router.js"; import { TreeService } from "./modules/tree/tree.service.js"; +import { buildOpenApiDocument } from "./openapi.js"; import type { TemplateStore } from "./storage/template-store.js"; export interface RouteDeps { @@ -23,6 +24,11 @@ export function createRoutes({ store, publicDir }: RouteDeps): Router { res.json({ status: "ok" }); }); + const openApiDocument = buildOpenApiDocument(); + router.get("/openapi.json", (_req, res) => { + res.json(openApiDocument); + }); + router.use("/tree", createTreeRouter(new TreeController(new TreeService(store)))); router.use("/elements", createElementsRouter(new ElementsController(new ElementsService(store)))); router.use( diff --git a/test/openapi.test.ts b/test/openapi.test.ts new file mode 100644 index 0000000..97920c1 --- /dev/null +++ b/test/openapi.test.ts @@ -0,0 +1,68 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Express } from "express"; +import request from "supertest"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { createApp } from "../src/app.js"; +import { createLogger } from "../src/common/logger.js"; +import { loadConfig } from "../src/config/env.js"; +import { buildOpenApiDocument } from "../src/openapi.js"; +import { createEmptyDb } from "../src/storage/db.types.js"; +import { JsonFileStore } from "../src/storage/json-file-store.js"; + +const METHODS = ["get", "post", "put", "patch", "delete"] as const; + +let dir: string; +let app: Express; + +beforeAll(async () => { + dir = await mkdtemp(path.join(tmpdir(), "openapi-test-")); + const dbFile = path.join(dir, "db.json"); + await writeFile(dbFile, JSON.stringify(createEmptyDb())); + const config = loadConfig({ + NODE_ENV: "test", + LOG_LEVEL: "silent", + DB_FILE: dbFile, + PUBLIC_DIR: dir, + }); + app = createApp({ config, store: new JsonFileStore(dbFile), logger: createLogger(config) }); +}); + +afterAll(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +describe("OpenAPI contract", () => { + it("committed openapi.json is up to date (run `npm run openapi` after changing routes)", async () => { + const committed = JSON.parse( + await readFile(path.join(import.meta.dirname, "..", "openapi.json"), "utf8"), + ) as unknown; + + expect(committed).toEqual(buildOpenApiDocument()); + }); + + it("is served at GET /openapi.json", async () => { + const res = await request(app).get("/openapi.json").expect(200); + + expect(res.body).toEqual(buildOpenApiDocument()); + }); + + it("documents only operations the app actually has", async () => { + const { paths } = buildOpenApiDocument(); + + for (const [route, item] of Object.entries(paths)) { + for (const method of METHODS.filter((m) => m in item)) { + const url = route.replace("{key}", "missing-key"); + const res = await request(app)[method](url).send({}); + const routeMissing = + res.status === 404 && + String((res.body as { error?: { message?: string } }).error?.message).startsWith( + "Route ", + ); + + expect(routeMissing, `${method.toUpperCase()} ${route}`).toBe(false); + } + } + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 8dde0f3..073933b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -20,5 +20,5 @@ "outDir": "dist", "sourceMap": true }, - "include": ["src", "test", "vitest.config.ts", "eslint.config.js"] + "include": ["src", "test", "scripts", "vitest.config.ts", "eslint.config.js"] }