'use strict'; /* * Builds docs/openapi.json from the route table (server/routes/*) and the error table (server/errors.js). * node tools/gen-openapi.js write docs/openapi.json * node tools/gen-openapi.js --check exit 1 if the file on disk differs (test/openapi.test.js does the same) */ const fs = require('fs'); const path = require('path'); const { Router } = require('../server/http'); const routes = require('../server/routes'); const { schemas } = require('../server/routes/schemas'); const { CODES } = require('../server/errors'); const FILE = path.join(__dirname, '..', 'docs', 'openapi.json'); // $ref: 'Name' -> '#/components/schemas/Name'; type: ['x','null'] -> nullable function conv(s) { if (Array.isArray(s)) return s.map(conv); if (!s || typeof s !== 'object') return s; if (s.$ref) return { $ref: '#/components/schemas/' + s.$ref }; const out = {}; for (const k of Object.keys(s)) { if (k === 'type' && Array.isArray(s.type)) { out.type = s.type.find((t) => t !== 'null'); out.nullable = true; } else if (k === 'additionalProperties' && s[k] === true) out[k] = true; else out[k] = conv(s[k]); } return out; } function build() { const router = new Router(); routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null, apply: () => null }) })); const paths = {}; for (const r of router.routes) { const p = r.path.replace(/:([A-Za-z]+)/g, '{$1}'); const m = r.meta; const op = { summary: m.summary, tags: [m.tag || 'misc'], operationId: r.method.toLowerCase() + r.path.replace(/[/:]+([a-zA-Z])/g, (x, c) => c.toUpperCase()).replace(/[^a-zA-Z0-9]/g, '') }; op.parameters = r.names.map((n) => ({ name: n, in: 'path', required: true, schema: { type: /id$/i.test(n) ? 'integer' : 'string' } })); if (m.query) for (const [k, sch] of Object.entries(m.query.properties || {})) op.parameters.push({ name: k, in: 'query', required: (m.query.required || []).includes(k), schema: conv(sch) }); if (m.body) op.requestBody = { required: true, content: { 'application/json': { schema: conv(m.body) } } }; op.security = m.auth === false ? [] : [{ bearer: [] }]; const okStatus = String(m.status || 200); op.responses = { [okStatus]: { description: 'OK', content: { 'application/json': { schema: conv(m.response || { $ref: 'Ok' }) } } } }; const errs = new Set(['internal_error'].concat(m.errors || [])); if (m.auth !== false) errs.add('unauthorized'); if (r.method === 'POST') errs.add('idempotency_key_reuse'); const byStatus = {}; for (const code of errs) { const def = CODES[code]; if (!def) throw new Error('route ' + r.method + ' ' + r.path + ' lists unknown error code ' + code); (byStatus[def[0]] = byStatus[def[0]] || []).push(code); } for (const st of Object.keys(byStatus).sort()) { op.responses[st] = { description: 'Error codes: ' + byStatus[st].sort().join(', '), content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } } }; } (paths[p] = paths[p] || {})[r.method.toLowerCase()] = op; } const components = { schemas: {}, securitySchemes: { bearer: { type: 'http', scheme: 'bearer', description: 'Opaque device token from /auth/login or /auth/signup' } } }; for (const k of Object.keys(schemas)) components.schemas[k] = conv(schemas[k]); return { openapi: '3.0.3', info: { title: 'UPSTREAM API', version: '1.0.0', description: 'Generated by tools/gen-openapi.js from server/routes. Every response carries serverTime; errors use the { error: { code, message, details } } envelope. Codes: ' + Object.keys(CODES).join(', ') }, servers: [{ url: '/api/v1' }], paths: Object.fromEntries(Object.keys(paths).sort().map((k) => [k, paths[k]])), components, 'x-error-codes': Object.fromEntries(Object.entries(CODES).map(([c, [status, msg]]) => [c, { status, description: msg }])), }; } function render() { return JSON.stringify(build(), null, 2) + '\n'; } if (require.main === module) { const text = render(); if (process.argv.includes('--check')) { const cur = fs.existsSync(FILE) ? fs.readFileSync(FILE, 'utf8') : ''; if (cur !== text) { console.error('docs/openapi.json is out of date: run npm run openapi'); process.exit(1); } console.log('openapi.json is up to date'); } else { fs.writeFileSync(FILE, text); console.log('wrote ' + FILE); } } module.exports = { build, render, FILE };