From f464b26178a3dd0b9ce2464c20907b4262464b52 Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:13:37 +0700 Subject: [PATCH 1/9] docs(spec): add REST API + Docker design for light-ocr Design a standalone Express server under server/ that wraps the published @arcships/light-ocr npm package and a single-stage Dockerfile that runs it, so the OCR engine can be called over HTTP. Co-Authored-By: Claude Sonnet 5 --- .../2026-07-21-rest-api-docker-design.md | 193 ++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-21-rest-api-docker-design.md diff --git a/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md b/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md new file mode 100644 index 0000000..e0542bb --- /dev/null +++ b/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md @@ -0,0 +1,193 @@ +# REST API + Docker for light-ocr — Design + +## Goal + +Expose the existing `@arcships/light-ocr` OCR engine over HTTP so it can be called +from any language/environment, and package it as a Docker image for easy +deployment. This is additive: it does not change `bindings/node` or the C++ +core. + +## Non-goals + +- No changes to the native addon, CMake build, or model bundling. +- No async job-queue API (out of scope for v1; the engine's own + `queueCapacity` provides backpressure for a synchronous API). +- No GPU-specific Docker image variant — a single image supports both CPU and + WebGPU via a runtime env var, since the Linux x64 glibc npm package already + ships a WebGPU-capable native binary. + +## Architecture + +New top-level directory `server/`, a standalone Node.js/Express app that +depends on the published `@arcships/light-ocr` npm package (not the in-repo +`bindings/node` source — no C++ compilation needed to build or run it). + +``` +server/ +├── package.json # express, multer, @arcships/light-ocr +├── src/ +│ ├── server.js # Express app entry point, graceful shutdown +│ ├── engine.js # createEngine() wrapper, startup init +│ ├── routes/ +│ │ ├── ocr.js # POST /ocr +│ │ ├── health.js # GET /health +│ │ └── info.js # GET /info +│ └── errors.js # OcrError -> HTTP status mapping +├── test/ +│ └── ocr.test.js # node --test end-to-end tests +├── Dockerfile +└── .dockerignore +``` + +Design decisions: +- One `engine` instance is created at process startup and shared across all + requests; `queueCapacity` bounds in-flight + queued recognition calls. + Express does not add its own queue on top. +- Routes are thin handlers; engine lifecycle and recognition logic live in + `engine.js`. + +## Endpoints + +### `GET /health` +```json +200 OK +{ "status": "ok" } +``` +Lightweight liveness check — confirms the engine finished initializing. + +### `GET /info` +```json +200 OK +{ + "execution": { "provider": "cpu", "sessions": { ... } }, + "version": "0.3.0" +} +``` +Returns `engine.info.execution` verbatim plus the server's own version, useful +for confirming which provider (cpu/webgpu) is actually active in a given +container. + +### `POST /ocr` +`multipart/form-data`, file field name `image`. + +```bash +curl -F "image=@sample.jpg" http://localhost:3000/ocr +``` + +Success: +```json +200 OK +{ + "lines": [ + { "text": "HELLO 123", "confidence": 0.98, "box": [[x, y], ...] } + ] +} +``` + +Validation: +- Missing/empty `image` field → `400 Bad Request` +- File exceeds size limit (default 20MB, via `multer` `limits.fileSize`) → + `413 Payload Too Large` +- Data that fails JPEG/PNG decode in `recognizeEncoded` → `422 Unprocessable + Entity` + +## Execution mode + +Controlled by an env var at container run time, not baked into the image +build — the same image works for both CPU and WebGPU: + +```bash +# CPU only (default) +docker run -p 3000:3000 light-ocr-api + +# WebGPU (host must expose the GPU/driver to the container, e.g. --gpus all) +docker run -p 3000:3000 -e EXECUTION_MODE=auto --gpus all light-ocr-api +``` + +```js +const provider = process.env.EXECUTION_MODE ?? 'cpu'; // 'cpu' | 'auto' | 'webgpu' +const engine = await createEngine({ + queueCapacity: Number(process.env.QUEUE_CAPACITY ?? 4), + execution: { provider }, +}); +``` + +Default is `cpu` so the image runs anywhere without depending on GPU drivers +being present. + +## Error handling + +`errors.js` maps `OcrError.code` to HTTP status: + +| OcrError code | HTTP status | +|---|---| +| `queue_full` | 429 Too Many Requests | +| `resource_limit_exceeded` | 413 Payload Too Large | +| `invalid_argument` | 400 Bad Request | +| other/unexpected | 500 Internal Server Error | + +## Graceful shutdown + +```js +process.on('SIGTERM', async () => { + server.close(); // stop accepting new connections + await engine.close(); // drain in-flight/queued requests (FIFO) + process.exit(0); +}); +``` +Required because `docker stop` sends `SIGTERM`; without this the engine could +be killed mid-request. + +## Dockerfile + +Single-stage — no compilation needed since the npm package ships prebuilt +native binaries + model bundle for the target platform: + +```dockerfile +FROM node:22-slim + +WORKDIR /app + +COPY server/package.json server/package-lock.json ./ +RUN npm ci --omit=dev + +COPY server/src ./src + +RUN groupadd -r ocr && useradd -r -g ocr ocr +USER ocr + +EXPOSE 3000 +ENV EXECUTION_MODE=cpu +ENV QUEUE_CAPACITY=4 + +CMD ["node", "src/server.js"] +``` + +- `node:22-slim` matches `engines.node: "^22.0.0 || ^24.0.0"` and is + glibc-based, matching the target platform of the prebuilt native package. +- Runs as non-root user `ocr`. +- `.dockerignore` excludes `node_modules`, `test/`, `*.md`. + +Optional `docker-compose.yml` for local dev convenience: +```yaml +services: + light-ocr-api: + build: + context: . + dockerfile: server/Dockerfile + ports: + - "3000:3000" + environment: + - EXECUTION_MODE=cpu +``` + +## Testing plan + +- `server/test/ocr.test.js` using `node --test` (matches the convention in + `bindings/node/test/`). +- POST /ocr with a real sample image (reuse a `corpus/fixtures` image if + suitable) and assert the response contains sensible `lines`. +- Validation tests: missing file → 400, non-image data → 422. +- /health and /info return 200 with expected fields. +- Manual verification: `docker build` + `docker run` + `curl` against the + running container, not just unit tests on the dev machine. From 86fc66c483583f64f8192edbcc7c51bc42329255 Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:20:01 +0700 Subject: [PATCH 2/9] docs(spec): add version management section to REST API design Pin @arcships/light-ocr to an exact version, tag Docker images by the server's own version, and document the manual update process. Co-Authored-By: Claude Sonnet 5 --- .../2026-07-21-rest-api-docker-design.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md b/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md index e0542bb..ef0fa8c 100644 --- a/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md +++ b/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md @@ -181,6 +181,28 @@ services: - EXECUTION_MODE=cpu ``` +## Version management + +`@arcships/light-ocr` is pinned to an **exact version** in +`server/package.json` (e.g. `"0.3.0"`, not `"^0.3.0"`), matching this repo's +existing lockfile-driven convention (`corpus/*.lock.json`, `models/*.lock.json`, +`oracle.lock.json`). Updates are manual, never auto-tracked, since a silent +minor/patch bump could change OCR behavior without review. + +Update process when a new `@arcships/light-ocr` version is released: +1. Bump the pinned version in `server/package.json`, run `npm install` to + regenerate `server/package-lock.json`, open a PR. +2. `docker build` the image and re-run `server/test/ocr.test.js` against it to + check for regressions. +3. Record the change in `CHANGELOG.md`, following the existing repo + convention. + +Docker image tags track the **server's own version** (e.g. +`light-ocr-api:1.0.0`), not the wrapped `@arcships/light-ocr` version — the +active engine version is discoverable at runtime via `GET /info`. `latest` is +for local development only; production deployments should pin an explicit +tag. + ## Testing plan - `server/test/ocr.test.js` using `node --test` (matches the convention in From a739d0f58bd6b2b429486a6d7a2c92f92dc5fb83 Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:42:19 +0700 Subject: [PATCH 3/9] docs(plan): add implementation plan for light-ocr REST API + Docker Six-task TDD plan: error mapping, engine lifecycle wrapper, health/info endpoints, POST /ocr, graceful shutdown, and Dockerfile/compose/docs. Co-Authored-By: Claude Sonnet 5 --- .../plans/2026-07-21-rest-api-docker.md | 909 ++++++++++++++++++ 1 file changed, 909 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-21-rest-api-docker.md diff --git a/docs/superpowers/plans/2026-07-21-rest-api-docker.md b/docs/superpowers/plans/2026-07-21-rest-api-docker.md new file mode 100644 index 0000000..4f33c6b --- /dev/null +++ b/docs/superpowers/plans/2026-07-21-rest-api-docker.md @@ -0,0 +1,909 @@ +# REST API + Docker for light-ocr Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add a standalone Node.js/Express REST API server (`server/`) that wraps the published `@arcships/light-ocr` npm package, plus a Dockerfile to run it as a container. + +**Architecture:** A single Express app with three routes (`GET /health`, `GET /info`, `POST /ocr`) backed by one shared `OcrEngine` instance created at process startup. The engine's own `queueCapacity` provides backpressure; Express adds no extra queue. A single-stage `node:22-slim` Dockerfile installs the npm package (which ships prebuilt native binaries + model bundle) — no C++ compilation in the image. + +**Tech Stack:** Node.js (`^22.0.0 || ^24.0.0`), Express 5, Multer 2, `@arcships/light-ocr` (pinned exact version), `node:test` for tests, Docker. + +**Spec:** `docs/superpowers/specs/2026-07-21-rest-api-docker-design.md` + +## Global Constraints + +- Node engines: `^22.0.0 || ^24.0.0` (matches `bindings/node/package.json`). +- `@arcships/light-ocr` pinned to the exact version `0.3.0` (verified via `npm view @arcships/light-ocr version`) — never a caret range. +- Docker base image: `node:22-slim`. +- Default env vars: `EXECUTION_MODE=cpu`, `QUEUE_CAPACITY=4`, `PORT=3000`. +- `POST /ocr` accepts `multipart/form-data` with file field name `image`, max size `20 * 1024 * 1024` bytes (20MB). +- Docker container runs as non-root user `ocr`. +- Test runner: `node --test`, files named `test/*.test.js`, style matches `bindings/node/test/adapter.test.cjs` (`'use strict'`, `node:assert/strict`, `node:test`). +- OcrError codes come from `bindings/node/js/index.d.ts` (`CoreErrorCode` / `AdapterErrorCode`) — do not invent new codes. + +--- + +## File Structure + +``` +server/ +├── package.json +├── package-lock.json # generated by npm install +├── .dockerignore +├── Dockerfile +├── README.md +├── src/ +│ ├── app.js # createApp(engine) -> Express app (routes + error handler) +│ ├── server.js # entry point: initEngine, createApp, listen, graceful shutdown +│ ├── engine.js # initEngine()/getEngine() wrapping @arcships/light-ocr createEngine() +│ ├── errors.js # statusForOcrError(), errorHandler() Express middleware +│ └── routes/ +│ ├── health.js # router: GET /health +│ ├── info.js # router: GET /info +│ └── ocr.js # router: POST /ocr (multer + engine.recognizeEncoded) +└── test/ + ├── errors.test.js + ├── engine.test.js + ├── app.test.js # health + info (Task 3), extended with /ocr tests (Task 4) + └── server.test.js +docker-compose.yml # repo root, references server/Dockerfile +``` + +Root `.gitignore` gets one new line (`node_modules/`) since this is the first npm-dependency-bearing package in the repo. + +--- + +### Task 1: Project scaffolding + error mapping module + +**Files:** +- Create: `server/package.json` +- Create: `server/src/errors.js` +- Test: `server/test/errors.test.js` + +**Interfaces:** +- Produces: `statusForOcrError(code: string): number`, `errorHandler(err, req, res, next): void` (Express 4-arg error middleware). + +- [ ] **Step 1: Create `server/package.json`** + +```json +{ + "name": "light-ocr-api", + "version": "1.0.0", + "private": true, + "description": "REST API server wrapping the light-ocr OCR engine", + "license": "Apache-2.0", + "type": "commonjs", + "main": "src/server.js", + "engines": { + "node": "^22.0.0 || ^24.0.0" + }, + "scripts": { + "start": "node src/server.js", + "test": "node --test test/*.test.js" + }, + "dependencies": { + "@arcships/light-ocr": "0.3.0", + "express": "^5.2.1", + "multer": "^2.2.0" + } +} +``` + +- [ ] **Step 2: Install dependencies** + +Run (from `server/`): `npm install` + +Expected: exits 0, creates `server/node_modules/` and `server/package-lock.json`, prints something like `added 70 packages`. + +- [ ] **Step 3: Add `node_modules/` to root `.gitignore`** + +Modify `.gitignore` (repo root), append: + +``` +node_modules/ +``` + +- [ ] **Step 4: Write the failing test** + +Create `server/test/errors.test.js`: + +```js +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { statusForOcrError, errorHandler } = require('../src/errors'); + +test('statusForOcrError maps known OcrError codes', () => { + assert.equal(statusForOcrError('queue_full'), 429); + assert.equal(statusForOcrError('resource_limit_exceeded'), 413); + assert.equal(statusForOcrError('invalid_argument'), 400); + assert.equal(statusForOcrError('invalid_image'), 422); + assert.equal(statusForOcrError('unsupported_pixel_format'), 400); +}); + +test('statusForOcrError defaults unknown codes to 500', () => { + assert.equal(statusForOcrError('internal_error'), 500); + assert.equal(statusForOcrError('something_new'), 500); +}); + +test('errorHandler responds with mapped status and code for an OcrError', () => { + const err = Object.assign(new Error('boom'), { name: 'OcrError', code: 'invalid_argument' }); + let statusCode; + let body; + const res = { + status(code) { + statusCode = code; + return this; + }, + json(payload) { + body = payload; + }, + }; + errorHandler(err, {}, res, () => {}); + assert.equal(statusCode, 400); + assert.deepEqual(body, { error: 'invalid_argument', message: 'boom' }); +}); + +test('errorHandler responds 413 for multer file-size errors', () => { + const multer = require('multer'); + const err = new multer.MulterError('LIMIT_FILE_SIZE'); + let statusCode; + let body; + const res = { + status(code) { + statusCode = code; + return this; + }, + json(payload) { + body = payload; + }, + }; + errorHandler(err, {}, res, () => {}); + assert.equal(statusCode, 413); + assert.deepEqual(body, { error: 'file_too_large' }); +}); + +test('errorHandler responds 500 for unknown errors', () => { + const err = new Error('unexpected'); + let statusCode; + let body; + const res = { + status(code) { + statusCode = code; + return this; + }, + json(payload) { + body = payload; + }, + }; + errorHandler(err, {}, res, () => {}); + assert.equal(statusCode, 500); + assert.deepEqual(body, { error: 'internal_error' }); +}); +``` + +- [ ] **Step 5: Run test to verify it fails** + +Run (from `server/`): `node --test test/errors.test.js` + +Expected: FAIL — `Cannot find module '../src/errors'`. + +- [ ] **Step 6: Implement `server/src/errors.js`** + +```js +'use strict'; + +const multer = require('multer'); + +const STATUS_BY_CODE = { + queue_full: 429, + resource_limit_exceeded: 413, + invalid_argument: 400, + invalid_image: 422, + unsupported_pixel_format: 400, +}; + +function statusForOcrError(code) { + return STATUS_BY_CODE[code] ?? 500; +} + +function errorHandler(err, req, res, next) { + if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') { + res.status(413).json({ error: 'file_too_large' }); + return; + } + if (err && err.name === 'OcrError') { + res.status(statusForOcrError(err.code)).json({ error: err.code, message: err.message }); + return; + } + res.status(500).json({ error: 'internal_error' }); +} + +module.exports = { statusForOcrError, errorHandler }; +``` + +- [ ] **Step 7: Run test to verify it passes** + +Run (from `server/`): `node --test test/errors.test.js` + +Expected: PASS — `# pass 5`, `# fail 0`. + +- [ ] **Step 8: Commit** + +```bash +git add .gitignore server/package.json server/package-lock.json server/src/errors.js server/test/errors.test.js +git commit -m "feat(server): scaffold REST API package and OcrError status mapping" +``` + +--- + +### Task 2: Engine lifecycle wrapper + +**Files:** +- Create: `server/src/engine.js` +- Test: `server/test/engine.test.js` + +**Interfaces:** +- Consumes: `@arcships/light-ocr`'s `createEngine(options): Promise` (from Task 1's dependency). +- Produces: `initEngine(): Promise` (idempotent — repeat calls return the same promise), `getEngine(): Promise` (throws synchronously if `initEngine()` was never called). + +- [ ] **Step 1: Write the failing test** + +Create `server/test/engine.test.js`: + +```js +'use strict'; + +const assert = require('node:assert/strict'); +const { after, test } = require('node:test'); + +const { initEngine, getEngine } = require('../src/engine'); + +after(async () => { + const engine = await getEngine(); + await engine.close(); +}); + +test('getEngine throws before initEngine has been called', () => { + assert.throws(() => getEngine(), /Engine not initialized/); +}); + +test('initEngine resolves an engine using the cpu provider by default', async () => { + delete process.env.EXECUTION_MODE; + const engine = await initEngine(); + assert.equal(engine.info.execution.requestedProvider, 'cpu'); +}); + +test('getEngine returns the same promise as initEngine after initialization', async () => { + const first = await initEngine(); + const second = await getEngine(); + assert.equal(first, second); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run (from `server/`): `node --test test/engine.test.js` + +Expected: FAIL — `Cannot find module '../src/engine'`. + +- [ ] **Step 3: Implement `server/src/engine.js`** + +```js +'use strict'; + +const { createEngine } = require('@arcships/light-ocr'); + +let enginePromise = null; + +function initEngine() { + if (!enginePromise) { + enginePromise = createEngine({ + queueCapacity: Number(process.env.QUEUE_CAPACITY ?? 4), + execution: { provider: process.env.EXECUTION_MODE ?? 'cpu' }, + }); + } + return enginePromise; +} + +function getEngine() { + if (!enginePromise) { + throw new Error('Engine not initialized; call initEngine() first'); + } + return enginePromise; +} + +module.exports = { initEngine, getEngine }; +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run (from `server/`): `node --test test/engine.test.js` + +Expected: PASS — `# pass 3`, `# fail 0`. This test loads a real model, so it may take several seconds. + +- [ ] **Step 5: Commit** + +```bash +git add server/src/engine.js server/test/engine.test.js +git commit -m "feat(server): add engine lifecycle wrapper around createEngine" +``` + +--- + +### Task 3: Health & info endpoints + app assembly + +**Files:** +- Create: `server/src/routes/health.js` +- Create: `server/src/routes/info.js` +- Create: `server/src/app.js` +- Test: `server/test/app.test.js` + +**Interfaces:** +- Consumes: `initEngine()` from Task 2 (`server/src/engine.js`), `errorHandler` from Task 1 (`server/src/errors.js`). +- Produces: `createApp(engine: OcrEngine): express.Express` — later tasks (Task 4) extend this by adding more routers inside it. + +- [ ] **Step 1: Write the failing test** + +Create `server/test/app.test.js`: + +```js +'use strict'; + +const assert = require('node:assert/strict'); +const { after, before, test } = require('node:test'); + +const { initEngine } = require('../src/engine'); +const { createApp } = require('../src/app'); + +let engine; +let server; +let baseUrl; + +before(async () => { + engine = await initEngine(); + const app = createApp(engine); + server = app.listen(0); + await new Promise((resolve) => server.once('listening', resolve)); + baseUrl = `http://127.0.0.1:${server.address().port}`; +}); + +after(async () => { + await new Promise((resolve) => server.close(resolve)); + await engine.close(); +}); + +test('GET /health returns 200 ok', async () => { + const response = await fetch(`${baseUrl}/health`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.deepEqual(body, { status: 'ok' }); +}); + +test('GET /info returns execution info and version', async () => { + const response = await fetch(`${baseUrl}/info`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.execution.requestedProvider, 'cpu'); + assert.equal(typeof body.version, 'string'); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run (from `server/`): `node --test test/app.test.js` + +Expected: FAIL — `Cannot find module '../src/app'`. + +- [ ] **Step 3: Implement `server/src/routes/health.js`** + +```js +'use strict'; + +const express = require('express'); + +function healthRouter() { + const router = express.Router(); + router.get('/health', (req, res) => { + res.status(200).json({ status: 'ok' }); + }); + return router; +} + +module.exports = healthRouter; +``` + +- [ ] **Step 4: Implement `server/src/routes/info.js`** + +```js +'use strict'; + +const express = require('express'); + +const packageJson = require('../../package.json'); + +function infoRouter(engine) { + const router = express.Router(); + router.get('/info', (req, res) => { + res.status(200).json({ + execution: engine.info.execution, + version: packageJson.version, + }); + }); + return router; +} + +module.exports = infoRouter; +``` + +- [ ] **Step 5: Implement `server/src/app.js`** + +```js +'use strict'; + +const express = require('express'); + +const healthRouter = require('./routes/health'); +const infoRouter = require('./routes/info'); +const { errorHandler } = require('./errors'); + +function createApp(engine) { + const app = express(); + app.use(healthRouter()); + app.use(infoRouter(engine)); + app.use(errorHandler); + return app; +} + +module.exports = { createApp }; +``` + +- [ ] **Step 6: Run test to verify it passes** + +Run (from `server/`): `node --test test/app.test.js` + +Expected: PASS — `# pass 2`, `# fail 0`. + +- [ ] **Step 7: Commit** + +```bash +git add server/src/routes/health.js server/src/routes/info.js server/src/app.js server/test/app.test.js +git commit -m "feat(server): add GET /health and GET /info endpoints" +``` + +--- + +### Task 4: POST /ocr endpoint + +**Files:** +- Create: `server/src/routes/ocr.js` +- Modify: `server/src/app.js` (mount the new router) +- Modify: `server/test/app.test.js` (add `/ocr` tests) + +**Interfaces:** +- Consumes: `engine.recognizeEncoded(buffer: Buffer): Promise` (from `@arcships/light-ocr`, `OcrResult.lines: OcrLine[]` where `OcrLine = { text: string, confidence: number, box: [Point, Point, Point, Point] }`), `errorHandler` from Task 1. +- Produces: nothing new consumed by later tasks — this is the last route. + +- [ ] **Step 1: Modify `server/test/app.test.js` to add `/ocr` tests** + +Replace the full file contents with: + +```js +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { after, before, test } = require('node:test'); + +const { initEngine } = require('../src/engine'); +const { createApp } = require('../src/app'); + +let engine; +let server; +let baseUrl; + +before(async () => { + engine = await initEngine(); + const app = createApp(engine); + server = app.listen(0); + await new Promise((resolve) => server.once('listening', resolve)); + baseUrl = `http://127.0.0.1:${server.address().port}`; +}); + +after(async () => { + await new Promise((resolve) => server.close(resolve)); + await engine.close(); +}); + +test('GET /health returns 200 ok', async () => { + const response = await fetch(`${baseUrl}/health`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.deepEqual(body, { status: 'ok' }); +}); + +test('GET /info returns execution info and version', async () => { + const response = await fetch(`${baseUrl}/info`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.execution.requestedProvider, 'cpu'); + assert.equal(typeof body.version, 'string'); +}); + +test('POST /ocr recognizes text in a real image', async () => { + const imagePath = path.resolve(__dirname, '../../docs/assets/benchmark-generated-hello-123.png'); + const imageBuffer = fs.readFileSync(imagePath); + const form = new FormData(); + form.set('image', new Blob([imageBuffer], { type: 'image/png' }), 'hello-123.png'); + + const response = await fetch(`${baseUrl}/ocr`, { method: 'POST', body: form }); + assert.equal(response.status, 200); + const body = await response.json(); + assert.ok(Array.isArray(body.lines)); + assert.ok(body.lines.some((line) => /HELLO/i.test(line.text))); +}); + +test('POST /ocr without a file returns 400', async () => { + const form = new FormData(); + const response = await fetch(`${baseUrl}/ocr`, { method: 'POST', body: form }); + assert.equal(response.status, 400); + const body = await response.json(); + assert.equal(body.error, 'missing_image'); +}); + +test('POST /ocr with non-image data returns 422', async () => { + const form = new FormData(); + form.set('image', new Blob([Buffer.from('not an image')], { type: 'application/octet-stream' }), 'garbage.bin'); + + const response = await fetch(`${baseUrl}/ocr`, { method: 'POST', body: form }); + assert.equal(response.status, 422); +}); +``` + +- [ ] **Step 2: Run test to verify the new tests fail** + +Run (from `server/`): `node --test test/app.test.js` + +Expected: the two existing tests still PASS; the three new `POST /ocr` tests FAIL with 404 (no route registered yet). + +- [ ] **Step 3: Implement `server/src/routes/ocr.js`** + +```js +'use strict'; + +const express = require('express'); +const multer = require('multer'); + +const MAX_FILE_BYTES = 20 * 1024 * 1024; + +const upload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: MAX_FILE_BYTES }, +}); + +function ocrRouter(engine) { + const router = express.Router(); + router.post('/ocr', upload.single('image'), async (req, res, next) => { + if (!req.file || req.file.buffer.length === 0) { + res.status(400).json({ error: 'missing_image' }); + return; + } + try { + const result = await engine.recognizeEncoded(req.file.buffer); + res.status(200).json({ lines: result.lines }); + } catch (error) { + next(error); + } + }); + return router; +} + +module.exports = ocrRouter; +``` + +- [ ] **Step 4: Modify `server/src/app.js` to mount the new router** + +Replace the full file contents with: + +```js +'use strict'; + +const express = require('express'); + +const healthRouter = require('./routes/health'); +const infoRouter = require('./routes/info'); +const ocrRouter = require('./routes/ocr'); +const { errorHandler } = require('./errors'); + +function createApp(engine) { + const app = express(); + app.use(healthRouter()); + app.use(infoRouter(engine)); + app.use(ocrRouter(engine)); + app.use(errorHandler); + return app; +} + +module.exports = { createApp }; +``` + +- [ ] **Step 5: Run test to verify all pass** + +Run (from `server/`): `node --test test/app.test.js` + +Expected: PASS — `# pass 5`, `# fail 0`. + +- [ ] **Step 6: Commit** + +```bash +git add server/src/routes/ocr.js server/src/app.js server/test/app.test.js +git commit -m "feat(server): add POST /ocr endpoint" +``` + +--- + +### Task 5: Server entry point + graceful shutdown + +**Files:** +- Create: `server/src/server.js` +- Test: `server/test/server.test.js` + +**Interfaces:** +- Consumes: `initEngine()` from Task 2, `createApp()` from Task 3/4. +- Produces: `createShutdownHandler(server, engine, exit?): () => Promise` (exported for tests), `main(): Promise` (starts the real server when run directly). + +- [ ] **Step 1: Write the failing test** + +Create `server/test/server.test.js`: + +```js +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { createShutdownHandler } = require('../src/server'); + +test('shutdown handler closes the server, closes the engine, then exits', async () => { + const calls = []; + const fakeServer = { close: () => calls.push('server.close') }; + const fakeEngine = { + close: async () => { + calls.push('engine.close'); + }, + }; + const fakeExit = (code) => calls.push(`exit(${code})`); + + const shutdown = createShutdownHandler(fakeServer, fakeEngine, fakeExit); + await shutdown(); + + assert.deepEqual(calls, ['server.close', 'engine.close', 'exit(0)']); +}); + +test('shutdown handler only runs once when called twice concurrently', async () => { + const calls = []; + const fakeServer = { close: () => calls.push('server.close') }; + const fakeEngine = { close: async () => calls.push('engine.close') }; + const fakeExit = (code) => calls.push(`exit(${code})`); + + const shutdown = createShutdownHandler(fakeServer, fakeEngine, fakeExit); + await Promise.all([shutdown(), shutdown()]); + + assert.deepEqual(calls, ['server.close', 'engine.close', 'exit(0)']); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run (from `server/`): `node --test test/server.test.js` + +Expected: FAIL — `Cannot find module '../src/server'`. + +- [ ] **Step 3: Implement `server/src/server.js`** + +```js +'use strict'; + +const { initEngine } = require('./engine'); +const { createApp } = require('./app'); + +const PORT = Number(process.env.PORT ?? 3000); + +function createShutdownHandler(server, engine, exit = process.exit) { + let shuttingDown = false; + return async function shutdown() { + if (shuttingDown) return; + shuttingDown = true; + server.close(); + await engine.close(); + exit(0); + }; +} + +async function main() { + const engine = await initEngine(); + const app = createApp(engine); + const server = app.listen(PORT, () => { + console.log(`light-ocr-api listening on port ${PORT}`); + }); + + const shutdown = createShutdownHandler(server, engine); + process.on('SIGTERM', shutdown); + process.on('SIGINT', shutdown); +} + +if (require.main === module) { + main().catch((error) => { + console.error(error); + process.exit(1); + }); +} + +module.exports = { createShutdownHandler, main }; +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run (from `server/`): `node --test test/server.test.js` + +Expected: PASS — `# pass 2`, `# fail 0`. + +- [ ] **Step 5: Run the full test suite** + +Run (from `server/`): `npm test` + +Expected: PASS — all files (`errors`, `engine`, `app`, `server`) report `# fail 0`. + +- [ ] **Step 6: Commit** + +```bash +git add server/src/server.js server/test/server.test.js +git commit -m "feat(server): add entry point with graceful shutdown" +``` + +--- + +### Task 6: Dockerfile, docker-compose, and docs + +**Files:** +- Create: `server/Dockerfile` +- Create: `server/.dockerignore` +- Create: `docker-compose.yml` (repo root) +- Create: `server/README.md` + +**Interfaces:** +- Consumes: `server/package.json` (Task 1), `server/src/server.js` (Task 5) as the container's `CMD` target. +- Produces: a runnable Docker image; nothing consumed by other tasks. + +- [ ] **Step 1: Create `server/Dockerfile`** + +```dockerfile +FROM node:22-slim + +WORKDIR /app + +COPY server/package.json server/package-lock.json ./ +RUN npm ci --omit=dev + +COPY server/src ./src + +RUN groupadd -r ocr && useradd -r -g ocr ocr +USER ocr + +EXPOSE 3000 +ENV EXECUTION_MODE=cpu +ENV QUEUE_CAPACITY=4 + +CMD ["node", "src/server.js"] +``` + +- [ ] **Step 2: Create `server/.dockerignore`** + +``` +node_modules +test +*.md +.git +Dockerfile +.dockerignore +``` + +- [ ] **Step 3: Create `docker-compose.yml` at the repo root** + +```yaml +services: + light-ocr-api: + build: + context: . + dockerfile: server/Dockerfile + ports: + - "3000:3000" + environment: + - EXECUTION_MODE=cpu +``` + +- [ ] **Step 4: Create `server/README.md`** + +```markdown +# light-ocr REST API + +HTTP wrapper around the `@arcships/light-ocr` OCR engine. + +## Run locally + + cd server + npm install + npm start + +Server listens on `PORT` (default `3000`). + +## Run with Docker + + docker build -f server/Dockerfile -t light-ocr-api . + docker run --rm -p 3000:3000 light-ocr-api + +Or with Docker Compose (from the repo root): + + docker compose up --build + +## Endpoints + +- `GET /health` - liveness check, returns `{ "status": "ok" }` +- `GET /info` - current engine execution info and server version +- `POST /ocr` - `multipart/form-data` with a file field named `image` (JPEG or PNG, up to 20MB) + +Example: + + curl -F "image=@sample.jpg" http://localhost:3000/ocr + +## Environment variables + +| Variable | Default | Description | +| ----------------- | ------- | ------------------------------------------------ | +| `PORT` | `3000` | HTTP port | +| `EXECUTION_MODE` | `cpu` | `cpu`, `auto`, or `webgpu` | +| `QUEUE_CAPACITY` | `4` | Max concurrent + queued recognition requests | + +WebGPU requires the host to expose a compatible GPU/driver to the container +(e.g. `docker run --gpus all`); the same image works for both modes. +``` + +- [ ] **Step 5: Build the Docker image** + +Run (from repo root): `docker build -f server/Dockerfile -t light-ocr-api:test .` + +Expected: build completes with exit code 0 and prints `Successfully tagged light-ocr-api:test` (or the equivalent BuildKit success summary). If Docker is not installed in the current environment, skip this step and note it explicitly when reporting task completion. + +- [ ] **Step 6: Run the container and verify it responds** + +Run: `docker run --rm -d -p 3000:3000 --name light-ocr-api-test light-ocr-api:test` + +Then: `curl http://localhost:3000/health` + +Expected: `{"status":"ok"}` + +Then: `curl -F "image=@docs/assets/benchmark-generated-hello-123.png" http://localhost:3000/ocr` + +Expected: JSON body with a `lines` array containing a line whose `text` matches `HELLO 123`. + +Then: `docker stop light-ocr-api-test` + +Expected: container stops within a few seconds (graceful shutdown from Task 5), exit code 0. + +- [ ] **Step 7: Commit** + +```bash +git add server/Dockerfile server/.dockerignore server/README.md docker-compose.yml +git commit -m "feat(server): add Dockerfile, docker-compose, and usage docs" +``` + +--- + +## Plan Self-Review Notes + +- **Spec coverage:** Architecture (Tasks 1-5), Endpoints `/health` `/info` `/ocr` (Tasks 3-4), Execution mode env vars (Task 2, 6), Error handling table (Task 1), Graceful shutdown (Task 5), Dockerfile (Task 6), Version management — exact-pin `@arcships/light-ocr` (Task 1) and image-tag-by-server-version convention (documented in `server/package.json`'s own version + `server/README.md`), Testing plan (all tasks use `node --test`; Task 6 covers the manual Docker verification called out in the spec). +- **Type consistency:** `initEngine`/`getEngine` (Task 2) are used identically in Tasks 3-5. `createApp(engine)` (Task 3) keeps the same signature through Task 4's modification. `createShutdownHandler(server, engine, exit)` (Task 5) matches its test calls exactly. +- **No API-key auth task** — explicitly deferred by the user during spec review; not included here. From e75b3277ea0de9acdbd13b94cc53b56d2c632580 Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:50:00 +0700 Subject: [PATCH 4/9] feat(server): scaffold REST API package and OcrError status mapping Co-Authored-By: Claude Sonnet 5 --- .gitignore | 1 + server/package-lock.json | 1121 ++++++++++++++++++++++++++++++++++++ server/package.json | 21 + server/src/errors.js | 29 + server/test/errors.test.js | 74 +++ 5 files changed, 1246 insertions(+) create mode 100644 server/package-lock.json create mode 100644 server/package.json create mode 100644 server/src/errors.js create mode 100644 server/test/errors.test.js diff --git a/.gitignore b/.gitignore index 8c31003..980684a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ .DS_Store __pycache__/ *.pyc +node_modules/ diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 0000000..4cb3840 --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,1121 @@ +{ + "name": "light-ocr-api", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "light-ocr-api", + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "@arcships/light-ocr": "0.3.0", + "express": "^5.2.1", + "multer": "^2.2.0" + }, + "engines": { + "node": "^22.0.0 || ^24.0.0" + } + }, + "node_modules/@arcships/light-ocr": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@arcships/light-ocr/-/light-ocr-0.3.0.tgz", + "integrity": "sha512-rTKUW08XHPxxRpPCxcyk4G4OOv/uPUu0VWVn2nzAs1PqDkLGQAvGdmiGGOrUAoc4CjbZwMcgwQsK+Zws4ARfXA==", + "license": "Apache-2.0", + "dependencies": { + "@arcships/light-ocr-model-ppocrv6-small": "0.3.0" + }, + "engines": { + "node": "^22.0.0 || ^24.0.0" + }, + "optionalDependencies": { + "@arcships/light-ocr-darwin-arm64": "0.3.0", + "@arcships/light-ocr-darwin-x64": "0.3.0", + "@arcships/light-ocr-linux-x64-gnu": "0.3.0", + "@arcships/light-ocr-win32-x64": "0.3.0" + } + }, + "node_modules/@arcships/light-ocr-darwin-arm64": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@arcships/light-ocr-darwin-arm64/-/light-ocr-darwin-arm64-0.3.0.tgz", + "integrity": "sha512-+rKbx8Du6V8t6xjCYLK6vYCdkYezFtxt3cQxfSn/+r6hw5Q8imsqNbyLqM4I7G4twfhKTJUOoadfauBm/hVm3Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^22.0.0 || ^24.0.0" + } + }, + "node_modules/@arcships/light-ocr-darwin-x64": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@arcships/light-ocr-darwin-x64/-/light-ocr-darwin-x64-0.3.0.tgz", + "integrity": "sha512-VJh+GeLGiNPIWQ1yOAvHBhPFVNd6GLORrG72Z0alNf79JAUx0RWD9N1phHifHmxcseT6VgXEbK6q/d1rktUjpw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^22.0.0 || ^24.0.0" + } + }, + "node_modules/@arcships/light-ocr-linux-x64-gnu": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@arcships/light-ocr-linux-x64-gnu/-/light-ocr-linux-x64-gnu-0.3.0.tgz", + "integrity": "sha512-oxvYcvENpdxxfMVoZQWXwoZ1i0DNFkIZoNJR18gAjm6JVK8loq7UzGpeAuvg1uyd89gQqjaWKlRABLP0DQb9wQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.0.0 || ^24.0.0" + } + }, + "node_modules/@arcships/light-ocr-model-ppocrv6-small": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@arcships/light-ocr-model-ppocrv6-small/-/light-ocr-model-ppocrv6-small-0.3.0.tgz", + "integrity": "sha512-vKUzIzsJSb8/nZ7pv9u9hS4lelaPubgmi/kINPMC1aCydBZovTUSV5NpbDkvVq1rmDww2Xg8rPE5ecCQqA1OVQ==", + "license": "Apache-2.0" + }, + "node_modules/@arcships/light-ocr-win32-x64": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@arcships/light-ocr-win32-x64/-/light-ocr-win32-x64-0.3.0.tgz", + "integrity": "sha512-1Aih7zeUNfmgLUGwWtJwAQ916QPQjOUS32i8s/v5ijhD38xQRJQ5+WuKiIAstZwsD5RQKxlXxwo6sWMMqv6H8w==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^22.0.0 || ^24.0.0" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz", + "integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..c11c9e6 --- /dev/null +++ b/server/package.json @@ -0,0 +1,21 @@ +{ + "name": "light-ocr-api", + "version": "1.0.0", + "private": true, + "description": "REST API server wrapping the light-ocr OCR engine", + "license": "Apache-2.0", + "type": "commonjs", + "main": "src/server.js", + "engines": { + "node": "^22.0.0 || ^24.0.0" + }, + "scripts": { + "start": "node src/server.js", + "test": "node --test test/*.test.js" + }, + "dependencies": { + "@arcships/light-ocr": "0.3.0", + "express": "^5.2.1", + "multer": "^2.2.0" + } +} diff --git a/server/src/errors.js b/server/src/errors.js new file mode 100644 index 0000000..efccfbe --- /dev/null +++ b/server/src/errors.js @@ -0,0 +1,29 @@ +'use strict'; + +const multer = require('multer'); + +const STATUS_BY_CODE = { + queue_full: 429, + resource_limit_exceeded: 413, + invalid_argument: 400, + invalid_image: 422, + unsupported_pixel_format: 400, +}; + +function statusForOcrError(code) { + return STATUS_BY_CODE[code] ?? 500; +} + +function errorHandler(err, req, res, next) { + if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') { + res.status(413).json({ error: 'file_too_large' }); + return; + } + if (err && err.name === 'OcrError') { + res.status(statusForOcrError(err.code)).json({ error: err.code, message: err.message }); + return; + } + res.status(500).json({ error: 'internal_error' }); +} + +module.exports = { statusForOcrError, errorHandler }; diff --git a/server/test/errors.test.js b/server/test/errors.test.js new file mode 100644 index 0000000..1a83684 --- /dev/null +++ b/server/test/errors.test.js @@ -0,0 +1,74 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { statusForOcrError, errorHandler } = require('../src/errors'); + +test('statusForOcrError maps known OcrError codes', () => { + assert.equal(statusForOcrError('queue_full'), 429); + assert.equal(statusForOcrError('resource_limit_exceeded'), 413); + assert.equal(statusForOcrError('invalid_argument'), 400); + assert.equal(statusForOcrError('invalid_image'), 422); + assert.equal(statusForOcrError('unsupported_pixel_format'), 400); +}); + +test('statusForOcrError defaults unknown codes to 500', () => { + assert.equal(statusForOcrError('internal_error'), 500); + assert.equal(statusForOcrError('something_new'), 500); +}); + +test('errorHandler responds with mapped status and code for an OcrError', () => { + const err = Object.assign(new Error('boom'), { name: 'OcrError', code: 'invalid_argument' }); + let statusCode; + let body; + const res = { + status(code) { + statusCode = code; + return this; + }, + json(payload) { + body = payload; + }, + }; + errorHandler(err, {}, res, () => {}); + assert.equal(statusCode, 400); + assert.deepEqual(body, { error: 'invalid_argument', message: 'boom' }); +}); + +test('errorHandler responds 413 for multer file-size errors', () => { + const multer = require('multer'); + const err = new multer.MulterError('LIMIT_FILE_SIZE'); + let statusCode; + let body; + const res = { + status(code) { + statusCode = code; + return this; + }, + json(payload) { + body = payload; + }, + }; + errorHandler(err, {}, res, () => {}); + assert.equal(statusCode, 413); + assert.deepEqual(body, { error: 'file_too_large' }); +}); + +test('errorHandler responds 500 for unknown errors', () => { + const err = new Error('unexpected'); + let statusCode; + let body; + const res = { + status(code) { + statusCode = code; + return this; + }, + json(payload) { + body = payload; + }, + }; + errorHandler(err, {}, res, () => {}); + assert.equal(statusCode, 500); + assert.deepEqual(body, { error: 'internal_error' }); +}); From 896d6bdef31d80bcb8d21b1ca99e5929c8184b7c Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:54:25 +0700 Subject: [PATCH 5/9] feat(server): add engine lifecycle wrapper around createEngine Co-Authored-By: Claude Sonnet 5 --- server/src/engine.js | 24 ++++++++++++++++++++++++ server/test/engine.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 server/src/engine.js create mode 100644 server/test/engine.test.js diff --git a/server/src/engine.js b/server/src/engine.js new file mode 100644 index 0000000..e94d569 --- /dev/null +++ b/server/src/engine.js @@ -0,0 +1,24 @@ +'use strict'; + +const { createEngine } = require('@arcships/light-ocr'); + +let enginePromise = null; + +function initEngine() { + if (!enginePromise) { + enginePromise = createEngine({ + queueCapacity: Number(process.env.QUEUE_CAPACITY ?? 4), + execution: { provider: process.env.EXECUTION_MODE ?? 'cpu' }, + }); + } + return enginePromise; +} + +function getEngine() { + if (!enginePromise) { + throw new Error('Engine not initialized; call initEngine() first'); + } + return enginePromise; +} + +module.exports = { initEngine, getEngine }; diff --git a/server/test/engine.test.js b/server/test/engine.test.js new file mode 100644 index 0000000..9192fa6 --- /dev/null +++ b/server/test/engine.test.js @@ -0,0 +1,27 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { after, test } = require('node:test'); + +const { initEngine, getEngine } = require('../src/engine'); + +after(async () => { + const engine = await getEngine(); + await engine.close(); +}); + +test('getEngine throws before initEngine has been called', () => { + assert.throws(() => getEngine(), /Engine not initialized/); +}); + +test('initEngine resolves an engine using the cpu provider by default', async () => { + delete process.env.EXECUTION_MODE; + const engine = await initEngine(); + assert.equal(engine.info.execution.requestedProvider, 'cpu'); +}); + +test('getEngine returns the same promise as initEngine after initialization', async () => { + const first = await initEngine(); + const second = await getEngine(); + assert.equal(first, second); +}); From 56bd0bc66bd9de43ec485f0685fd0b6061cd2ca1 Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:57:22 +0700 Subject: [PATCH 6/9] feat(server): add GET /health and GET /info endpoints Co-Authored-By: Claude Sonnet 5 --- server/src/app.js | 17 ++++++++++++++++ server/src/routes/health.js | 13 +++++++++++++ server/src/routes/info.js | 18 +++++++++++++++++ server/test/app.test.js | 39 +++++++++++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+) create mode 100644 server/src/app.js create mode 100644 server/src/routes/health.js create mode 100644 server/src/routes/info.js create mode 100644 server/test/app.test.js diff --git a/server/src/app.js b/server/src/app.js new file mode 100644 index 0000000..617343e --- /dev/null +++ b/server/src/app.js @@ -0,0 +1,17 @@ +'use strict'; + +const express = require('express'); + +const healthRouter = require('./routes/health'); +const infoRouter = require('./routes/info'); +const { errorHandler } = require('./errors'); + +function createApp(engine) { + const app = express(); + app.use(healthRouter()); + app.use(infoRouter(engine)); + app.use(errorHandler); + return app; +} + +module.exports = { createApp }; diff --git a/server/src/routes/health.js b/server/src/routes/health.js new file mode 100644 index 0000000..1d449fa --- /dev/null +++ b/server/src/routes/health.js @@ -0,0 +1,13 @@ +'use strict'; + +const express = require('express'); + +function healthRouter() { + const router = express.Router(); + router.get('/health', (req, res) => { + res.status(200).json({ status: 'ok' }); + }); + return router; +} + +module.exports = healthRouter; diff --git a/server/src/routes/info.js b/server/src/routes/info.js new file mode 100644 index 0000000..71cd515 --- /dev/null +++ b/server/src/routes/info.js @@ -0,0 +1,18 @@ +'use strict'; + +const express = require('express'); + +const packageJson = require('../../package.json'); + +function infoRouter(engine) { + const router = express.Router(); + router.get('/info', (req, res) => { + res.status(200).json({ + execution: engine.info.execution, + version: packageJson.version, + }); + }); + return router; +} + +module.exports = infoRouter; diff --git a/server/test/app.test.js b/server/test/app.test.js new file mode 100644 index 0000000..0aabdd6 --- /dev/null +++ b/server/test/app.test.js @@ -0,0 +1,39 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { after, before, test } = require('node:test'); + +const { initEngine } = require('../src/engine'); +const { createApp } = require('../src/app'); + +let engine; +let server; +let baseUrl; + +before(async () => { + engine = await initEngine(); + const app = createApp(engine); + server = app.listen(0); + await new Promise((resolve) => server.once('listening', resolve)); + baseUrl = `http://127.0.0.1:${server.address().port}`; +}); + +after(async () => { + await new Promise((resolve) => server.close(resolve)); + await engine.close(); +}); + +test('GET /health returns 200 ok', async () => { + const response = await fetch(`${baseUrl}/health`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.deepEqual(body, { status: 'ok' }); +}); + +test('GET /info returns execution info and version', async () => { + const response = await fetch(`${baseUrl}/info`); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.execution.requestedProvider, 'cpu'); + assert.equal(typeof body.version, 'string'); +}); From 58da4dc16e0e25cb2fa533c40a492ba08cbd5b60 Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 11:59:48 +0700 Subject: [PATCH 7/9] feat(server): add POST /ocr endpoint Co-Authored-By: Claude Sonnet 5 --- server/src/app.js | 2 ++ server/src/routes/ocr.js | 30 ++++++++++++++++++++++++++++++ server/test/app.test.js | 31 +++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 server/src/routes/ocr.js diff --git a/server/src/app.js b/server/src/app.js index 617343e..de51c15 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -4,12 +4,14 @@ const express = require('express'); const healthRouter = require('./routes/health'); const infoRouter = require('./routes/info'); +const ocrRouter = require('./routes/ocr'); const { errorHandler } = require('./errors'); function createApp(engine) { const app = express(); app.use(healthRouter()); app.use(infoRouter(engine)); + app.use(ocrRouter(engine)); app.use(errorHandler); return app; } diff --git a/server/src/routes/ocr.js b/server/src/routes/ocr.js new file mode 100644 index 0000000..d831831 --- /dev/null +++ b/server/src/routes/ocr.js @@ -0,0 +1,30 @@ +'use strict'; + +const express = require('express'); +const multer = require('multer'); + +const MAX_FILE_BYTES = 20 * 1024 * 1024; + +const upload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: MAX_FILE_BYTES }, +}); + +function ocrRouter(engine) { + const router = express.Router(); + router.post('/ocr', upload.single('image'), async (req, res, next) => { + if (!req.file || req.file.buffer.length === 0) { + res.status(400).json({ error: 'missing_image' }); + return; + } + try { + const result = await engine.recognizeEncoded(req.file.buffer); + res.status(200).json({ lines: result.lines }); + } catch (error) { + next(error); + } + }); + return router; +} + +module.exports = ocrRouter; diff --git a/server/test/app.test.js b/server/test/app.test.js index 0aabdd6..e70020e 100644 --- a/server/test/app.test.js +++ b/server/test/app.test.js @@ -1,6 +1,8 @@ 'use strict'; const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); const { after, before, test } = require('node:test'); const { initEngine } = require('../src/engine'); @@ -37,3 +39,32 @@ test('GET /info returns execution info and version', async () => { assert.equal(body.execution.requestedProvider, 'cpu'); assert.equal(typeof body.version, 'string'); }); + +test('POST /ocr recognizes text in a real image', async () => { + const imagePath = path.resolve(__dirname, '../../docs/assets/benchmark-generated-hello-123.png'); + const imageBuffer = fs.readFileSync(imagePath); + const form = new FormData(); + form.set('image', new Blob([imageBuffer], { type: 'image/png' }), 'hello-123.png'); + + const response = await fetch(`${baseUrl}/ocr`, { method: 'POST', body: form }); + assert.equal(response.status, 200); + const body = await response.json(); + assert.ok(Array.isArray(body.lines)); + assert.ok(body.lines.some((line) => /HELLO/i.test(line.text))); +}); + +test('POST /ocr without a file returns 400', async () => { + const form = new FormData(); + const response = await fetch(`${baseUrl}/ocr`, { method: 'POST', body: form }); + assert.equal(response.status, 400); + const body = await response.json(); + assert.equal(body.error, 'missing_image'); +}); + +test('POST /ocr with non-image data returns 422', async () => { + const form = new FormData(); + form.set('image', new Blob([Buffer.from('not an image')], { type: 'application/octet-stream' }), 'garbage.bin'); + + const response = await fetch(`${baseUrl}/ocr`, { method: 'POST', body: form }); + assert.equal(response.status, 422); +}); From 889e869e9852f3b8d14ea0a99410c62d65501bec Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 12:01:18 +0700 Subject: [PATCH 8/9] feat(server): add entry point with graceful shutdown Co-Authored-By: Claude Sonnet 5 --- server/src/server.js | 38 ++++++++++++++++++++++++++++++++++++++ server/test/server.test.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 server/src/server.js create mode 100644 server/test/server.test.js diff --git a/server/src/server.js b/server/src/server.js new file mode 100644 index 0000000..ab7e5e8 --- /dev/null +++ b/server/src/server.js @@ -0,0 +1,38 @@ +'use strict'; + +const { initEngine } = require('./engine'); +const { createApp } = require('./app'); + +const PORT = Number(process.env.PORT ?? 3000); + +function createShutdownHandler(server, engine, exit = process.exit) { + let shuttingDown = false; + return async function shutdown() { + if (shuttingDown) return; + shuttingDown = true; + server.close(); + await engine.close(); + exit(0); + }; +} + +async function main() { + const engine = await initEngine(); + const app = createApp(engine); + const server = app.listen(PORT, () => { + console.log(`light-ocr-api listening on port ${PORT}`); + }); + + const shutdown = createShutdownHandler(server, engine); + process.on('SIGTERM', shutdown); + process.on('SIGINT', shutdown); +} + +if (require.main === module) { + main().catch((error) => { + console.error(error); + process.exit(1); + }); +} + +module.exports = { createShutdownHandler, main }; diff --git a/server/test/server.test.js b/server/test/server.test.js new file mode 100644 index 0000000..1b80003 --- /dev/null +++ b/server/test/server.test.js @@ -0,0 +1,34 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { createShutdownHandler } = require('../src/server'); + +test('shutdown handler closes the server, closes the engine, then exits', async () => { + const calls = []; + const fakeServer = { close: () => calls.push('server.close') }; + const fakeEngine = { + close: async () => { + calls.push('engine.close'); + }, + }; + const fakeExit = (code) => calls.push(`exit(${code})`); + + const shutdown = createShutdownHandler(fakeServer, fakeEngine, fakeExit); + await shutdown(); + + assert.deepEqual(calls, ['server.close', 'engine.close', 'exit(0)']); +}); + +test('shutdown handler only runs once when called twice concurrently', async () => { + const calls = []; + const fakeServer = { close: () => calls.push('server.close') }; + const fakeEngine = { close: async () => calls.push('engine.close') }; + const fakeExit = (code) => calls.push(`exit(${code})`); + + const shutdown = createShutdownHandler(fakeServer, fakeEngine, fakeExit); + await Promise.all([shutdown(), shutdown()]); + + assert.deepEqual(calls, ['server.close', 'engine.close', 'exit(0)']); +}); From 16130d8874d46abb29c0909d3d2b5645ef58183f Mon Sep 17 00:00:00 2001 From: chatre7 Date: Tue, 21 Jul 2026 12:10:31 +0700 Subject: [PATCH 9/9] feat(server): add Dockerfile, docker-compose, and usage docs Verified with a real docker build/run/curl cycle: node:22-slim's glibc 2.36 is too old for the native addon (needs 2.38+), so the base image is node:22-trixie-slim instead. Spec and plan docs updated to match. Co-Authored-By: Claude Sonnet 5 --- docker-compose.yml | 9 ++++ .../plans/2026-07-21-rest-api-docker.md | 6 +-- .../2026-07-21-rest-api-docker-design.md | 4 +- server/.dockerignore | 6 +++ server/Dockerfile | 17 ++++++++ server/README.md | 41 +++++++++++++++++++ 6 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 docker-compose.yml create mode 100644 server/.dockerignore create mode 100644 server/Dockerfile create mode 100644 server/README.md diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..d102df7 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,9 @@ +services: + light-ocr-api: + build: + context: . + dockerfile: server/Dockerfile + ports: + - "3000:3000" + environment: + - EXECUTION_MODE=cpu diff --git a/docs/superpowers/plans/2026-07-21-rest-api-docker.md b/docs/superpowers/plans/2026-07-21-rest-api-docker.md index 4f33c6b..7bea156 100644 --- a/docs/superpowers/plans/2026-07-21-rest-api-docker.md +++ b/docs/superpowers/plans/2026-07-21-rest-api-docker.md @@ -4,7 +4,7 @@ **Goal:** Add a standalone Node.js/Express REST API server (`server/`) that wraps the published `@arcships/light-ocr` npm package, plus a Dockerfile to run it as a container. -**Architecture:** A single Express app with three routes (`GET /health`, `GET /info`, `POST /ocr`) backed by one shared `OcrEngine` instance created at process startup. The engine's own `queueCapacity` provides backpressure; Express adds no extra queue. A single-stage `node:22-slim` Dockerfile installs the npm package (which ships prebuilt native binaries + model bundle) — no C++ compilation in the image. +**Architecture:** A single Express app with three routes (`GET /health`, `GET /info`, `POST /ocr`) backed by one shared `OcrEngine` instance created at process startup. The engine's own `queueCapacity` provides backpressure; Express adds no extra queue. A single-stage `node:22-trixie-slim` Dockerfile installs the npm package (which ships prebuilt native binaries + model bundle) — no C++ compilation in the image. **Tech Stack:** Node.js (`^22.0.0 || ^24.0.0`), Express 5, Multer 2, `@arcships/light-ocr` (pinned exact version), `node:test` for tests, Docker. @@ -14,7 +14,7 @@ - Node engines: `^22.0.0 || ^24.0.0` (matches `bindings/node/package.json`). - `@arcships/light-ocr` pinned to the exact version `0.3.0` (verified via `npm view @arcships/light-ocr version`) — never a caret range. -- Docker base image: `node:22-slim`. +- Docker base image: `node:22-trixie-slim`. - Default env vars: `EXECUTION_MODE=cpu`, `QUEUE_CAPACITY=4`, `PORT=3000`. - `POST /ocr` accepts `multipart/form-data` with file field name `image`, max size `20 * 1024 * 1024` bytes (20MB). - Docker container runs as non-root user `ocr`. @@ -781,7 +781,7 @@ git commit -m "feat(server): add entry point with graceful shutdown" - [ ] **Step 1: Create `server/Dockerfile`** ```dockerfile -FROM node:22-slim +FROM node:22-trixie-slim WORKDIR /app diff --git a/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md b/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md index ef0fa8c..80966e3 100644 --- a/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md +++ b/docs/superpowers/specs/2026-07-21-rest-api-docker-design.md @@ -144,7 +144,7 @@ Single-stage — no compilation needed since the npm package ships prebuilt native binaries + model bundle for the target platform: ```dockerfile -FROM node:22-slim +FROM node:22-trixie-slim WORKDIR /app @@ -163,7 +163,7 @@ ENV QUEUE_CAPACITY=4 CMD ["node", "src/server.js"] ``` -- `node:22-slim` matches `engines.node: "^22.0.0 || ^24.0.0"` and is +- `node:22-trixie-slim` matches `engines.node: "^22.0.0 || ^24.0.0"` and is glibc-based, matching the target platform of the prebuilt native package. - Runs as non-root user `ocr`. - `.dockerignore` excludes `node_modules`, `test/`, `*.md`. diff --git a/server/.dockerignore b/server/.dockerignore new file mode 100644 index 0000000..db30c03 --- /dev/null +++ b/server/.dockerignore @@ -0,0 +1,6 @@ +node_modules +test +*.md +.git +Dockerfile +.dockerignore diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..da46d07 --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,17 @@ +FROM node:22-trixie-slim + +WORKDIR /app + +COPY server/package.json server/package-lock.json ./ +RUN npm ci --omit=dev + +COPY server/src ./src + +RUN groupadd -r ocr && useradd -r -g ocr ocr +USER ocr + +EXPOSE 3000 +ENV EXECUTION_MODE=cpu +ENV QUEUE_CAPACITY=4 + +CMD ["node", "src/server.js"] diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..76e0ccd --- /dev/null +++ b/server/README.md @@ -0,0 +1,41 @@ +# light-ocr REST API + +HTTP wrapper around the `@arcships/light-ocr` OCR engine. + +## Run locally + + cd server + npm install + npm start + +Server listens on `PORT` (default `3000`). + +## Run with Docker + + docker build -f server/Dockerfile -t light-ocr-api . + docker run --rm -p 3000:3000 light-ocr-api + +Or with Docker Compose (from the repo root): + + docker compose up --build + +## Endpoints + +- `GET /health` - liveness check, returns `{ "status": "ok" }` +- `GET /info` - current engine execution info and server version +- `POST /ocr` - `multipart/form-data` with a file field named `image` (JPEG or PNG, up to 20MB) + +Example: + + curl -F "image=@sample.jpg" http://localhost:3000/ocr + +## Environment variables + +| Variable | Default | Description | +| ----------------- | ------- | ------------------------------------------------ | +| `PORT` | `3000` | HTTP port | +| `EXECUTION_MODE` | `cpu` | `cpu`, `auto`, or `webgpu` | +| `QUEUE_CAPACITY` | `4` | Max concurrent + queued recognition requests | + +WebGPU requires the host to expose a compatible GPU/driver to the container +(e.g. `docker run --gpus all`); the same image works for both modes.