@softistx/alxia-openapi 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +268 -2
- package/dist/api-docs-spec.d.ts +20 -0
- package/dist/api-docs-spec.d.ts.map +1 -0
- package/dist/api-docs-ui.d.ts +22 -0
- package/dist/api-docs-ui.d.ts.map +1 -0
- package/dist/api-docs.d.ts +34 -0
- package/dist/api-docs.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +255 -0
- package/dist/index.js.map +13 -0
- package/dist/routes.d.ts +61 -0
- package/dist/routes.d.ts.map +1 -0
- package/docs/README.md +24 -0
- package/docs/guide/api-docs.md +200 -0
- package/docs/guide/checks.md +238 -0
- package/docs/guide/matching.md +59 -0
- package/docs/guide/spec-first.md +335 -0
- package/docs/guide/testing.md +90 -0
- package/docs/roadmap.md +101 -0
- package/docs/troubleshooting.md +494 -0
- package/package.json +52 -5
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/api-docs.ts", "../src/api-docs-spec.ts", "../src/api-docs-ui.ts", "../src/routes.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n\talxia,\n\ttype BaseContext,\n\tmarkFactory,\n\ttype RouteDefinition,\n} from '@softistx/alxia';\nimport { type DocsServer, loadSpec } from './api-docs-spec';\nimport { type DocsUi, freshNonce, page, policy } from './api-docs-ui';\n\nexport type { DocsServer, DocsUi };\n\nexport interface ApiDocsOptions {\n\t/** The OpenAPI document: a path to a YAML or JSON file, read once at startup, or the object. */\n\treadonly spec: string | object;\n\t/** Where the page is served; the spec is at `${path}/openapi.yaml` and `.json`. Defaults to `/docs`. */\n\treadonly path?: `/${string}`;\n\t/** `'scalar'` (default) or `'swagger'`, loaded from a pinned CDN version. */\n\treadonly ui?: DocsUi;\n\t/** The page's title. Defaults to the document's `info.title`, else \"API documentation\". */\n\treadonly title?: string;\n\t/** Replaces the document's `servers`, in the page and in both files. */\n\treadonly servers?: readonly DocsServer[];\n\t/** `false` mounts nothing. Defaults to `true`. */\n\treadonly enabled?: boolean;\n}\n\ntype PageContext = Pick<BaseContext, 'url' | 'reply'>;\n\n/** The handlers `apiDocs()` declared: `matchesSpec` leaves their routes out. */\nconst declared = new WeakSet<RouteDefinition['handler']>();\n\n/**\n * Whether `apiDocs()` declared this route: the page and the two files.\n * `matchesSpec` already leaves them out; this is for a check of your own.\n */\nexport function isApiDocsRoute(\n\troute: Pick<RouteDefinition, 'handler'>,\n): boolean {\n\treturn declared.has(route.handler);\n}\n\n/**\n * An interactive page for the OpenAPI document, and the document itself:\n * `GET /docs`, `GET /docs/openapi.yaml` and `GET /docs/openapi.json`. The\n * page sets its own `Content-Security-Policy`, which `secureHeaders` keeps.\n *\n * ```ts\n * app.plugin(apiDocs({ spec: 'openapi.yaml' }));\n * ```\n */\nexport function apiDocs(options: ApiDocsOptions) {\n\tconst { path = '/docs', ui = 'scalar', enabled = true } = options;\n\tif (!/^\\/.*[^/]$/.test(path)) {\n\t\tthrow new TypeError(\n\t\t\t`apiDocs(): the path \"${path}\" must start with \"/\" and not end with one`,\n\t\t);\n\t}\n\tif (ui !== 'scalar' && ui !== 'swagger') {\n\t\tthrow new TypeError(`apiDocs(): ui \"${ui}\" is not \"scalar\" or \"swagger\"`);\n\t}\n\tconst app = alxia();\n\tif (!enabled) return app;\n\tconst spec = loadSpec(options.spec, options.servers);\n\tconst title = options.title ?? titleOf(spec.json);\n\n\tconst html = ({ url, reply }: PageContext) => {\n\t\tconst nonce = freshNonce();\n\t\tconst specUrl = `${url.pathname.replace(/\\/+$/, '')}/openapi.json`;\n\t\treturn reply.html(200, page(ui, { title, specUrl, nonce }), {\n\t\t\theaders: {\n\t\t\t\t'content-security-policy': policy(ui, nonce, spec.origins),\n\t\t\t},\n\t\t});\n\t};\n\tconst yaml = ({ reply }: PageContext) =>\n\t\treply(200, spec.yaml, { headers: { 'content-type': 'application/yaml' } });\n\tconst json = ({ reply }: PageContext) =>\n\t\treply(200, spec.json, { headers: { 'content-type': 'application/json' } });\n\tfor (const handler of [html, yaml, json]) declared.add(handler);\n\treturn app\n\t\t.get(path, html)\n\t\t.get(`${path}/openapi.yaml`, yaml)\n\t\t.get(`${path}/openapi.json`, json);\n}\n\nfunction titleOf(json: string): string {\n\tconst info = (JSON.parse(json) as { info?: { title?: unknown } }).info;\n\treturn typeof info?.title === 'string' && info.title !== ''\n\t\t? info.title\n\t\t: 'API documentation';\n}\n\nmarkFactory(apiDocs, 'plugin');\n",
|
|
6
|
+
"import { readFileSync } from 'node:fs';\n\n/** A server of the document, as OpenAPI declares it. */\nexport interface DocsServer {\n\treadonly url: string;\n\treadonly description?: string;\n}\n\n/** The document, parsed once, and as the two files serve it. */\nexport interface LoadedSpec {\n\treadonly json: string;\n\treadonly yaml: string;\n\t/** The origins of its absolute `servers`: what \"Try it out\" may call. */\n\treadonly origins: readonly string[];\n}\n\n/**\n * Reads `spec`: an object, or a path to a YAML or JSON file, read once,\n * relative to the working directory. `servers` replaces the document's.\n * Throws a `TypeError` naming `apiDocs()`, at startup, rather than serve a\n * page that shows nothing.\n */\nexport function loadSpec(\n\tspec: string | object,\n\tservers: readonly DocsServer[] | undefined,\n): LoadedSpec {\n\tlet text: string | undefined;\n\tlet document: unknown = spec;\n\tif (typeof spec === 'string') {\n\t\ttext = read(spec);\n\t\tdocument = parse(spec, text);\n\t}\n\tif (\n\t\ttypeof document !== 'object' ||\n\t\tdocument === null ||\n\t\tArray.isArray(document) ||\n\t\ttypeof (document as { openapi?: unknown }).openapi !== 'string'\n\t) {\n\t\tthrow new TypeError(\n\t\t\t`apiDocs(): ${typeof spec === 'string' ? `\"${spec}\"` : 'the spec'} is not an OpenAPI document: it has no \"openapi\" version`,\n\t\t);\n\t}\n\tconst final = servers ? { ...document, servers } : document;\n\tconst json = JSON.stringify(final, null, 2);\n\t// A file with its own servers kept is served as written, comments included.\n\tconst yaml =\n\t\ttext !== undefined && servers === undefined && !isJson(text)\n\t\t\t? text\n\t\t\t: Bun.YAML.stringify(final, null, 2);\n\treturn { json, yaml, origins: originsOf(final) };\n}\n\n/**\n * The origin of each server whose URL is absolute and plain `http(s)`: a\n * relative one is the page's own origin, and a template\n * (`https://{region}.example.com`) names no origin a policy can allow.\n */\nfunction originsOf(document: object): string[] {\n\tconst servers = (document as { servers?: unknown }).servers;\n\tif (!Array.isArray(servers)) return [];\n\tconst origins = new Set<string>();\n\tfor (const server of servers) {\n\t\tconst url = (server as { url?: unknown } | null)?.url;\n\t\tif (typeof url !== 'string' || url.includes('{')) continue;\n\t\tif (!/^https?:\\/\\//i.test(url)) continue;\n\t\ttry {\n\t\t\torigins.add(new URL(url).origin);\n\t\t} catch {\n\t\t\t// Not a URL: nothing to allow.\n\t\t}\n\t}\n\treturn [...origins];\n}\n\nfunction read(path: string): string {\n\ttry {\n\t\treturn readFileSync(path, 'utf8');\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\tthrow new TypeError(\n\t\t\t`apiDocs(): cannot read the spec \"${path}\" (${code ?? 'unreadable'}), looked up from the working directory ${process.cwd()}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nfunction isJson(text: string): boolean {\n\treturn /^\\s*[{[]/.test(text);\n}\n\nfunction parse(path: string, text: string): unknown {\n\ttry {\n\t\treturn isJson(text) ? JSON.parse(text) : Bun.YAML.parse(text);\n\t} catch (error) {\n\t\tthrow new TypeError(\n\t\t\t`apiDocs(): \"${path}\" is neither valid YAML nor valid JSON: ${(error as Error).message}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n",
|
|
7
|
+
"/** The two interactive pages, loaded from a CDN: pinned, and checked by SRI. */\n\nexport type DocsUi = 'scalar' | 'swagger';\n\nconst CDN = 'https://cdn.jsdelivr.net';\n\n/** Each UI's files: the one pinned version's folder, which its policy allows alone. */\nconst FILES = {\n\tscalar: `${CDN}/npm/@scalar/api-reference@1.72.4/`,\n\tswagger: `${CDN}/npm/swagger-ui-dist@5.33.1/`,\n} as const;\n\nconst SCALAR = {\n\tsrc: `${FILES.scalar}dist/browser/standalone.js`,\n\tintegrity:\n\t\t'sha384-omTRdD9MbjA1vm12DqRUVvqJlr3VzSixvAdF1Jruu9AJOiJKyTKraIB6DyX+m10M',\n} as const;\n\nconst SWAGGER = {\n\tscript: `${FILES.swagger}swagger-ui-bundle.js`,\n\tscriptIntegrity:\n\t\t'sha384-ZPehFMQommnnuaZ4rpxgkgTT2DKFVp4hZC/7pLit+9Lek9T1YGSo23eHFbvNkXkw',\n\tcss: `${FILES.swagger}swagger-ui.css`,\n\tcssIntegrity:\n\t\t'sha384-Ov4/wv3j2bmct8cDc5X4ngJZohVPzEmc6uDPH8WeljUxO5vtoykvMEfbu9Vh6RaW',\n} as const;\n\n/** Text in an HTML body or a quoted attribute. */\nexport function escapeHtml(text: string): string {\n\treturn text\n\t\t.replaceAll('&', '&')\n\t\t.replaceAll('<', '<')\n\t\t.replaceAll('>', '>')\n\t\t.replaceAll('\"', '"');\n}\n\n/** A fresh nonce for one page: 128 random bits. */\nexport function freshNonce(): string {\n\treturn Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString(\n\t\t'base64',\n\t);\n}\n\n/** Scalar's fonts, unless the app's own CSS replaces them. */\nconst SCALAR_FONTS = 'https://fonts.scalar.com';\n\n/**\n * The page's own policy, which `secureHeaders` keeps (a header a route set\n * is kept, as for `@softistx/alxia-graphql`'s IDE): the pinned version's scripts\n * and styles alone, the one inline script of Swagger UI by its nonce, and\n * nothing else. Requests go to this server — the spec — and to the\n * `origins` of the document's servers, which \"Try it out\" calls.\n */\nexport function policy(\n\tui: DocsUi,\n\tnonce: string,\n\torigins: readonly string[],\n): string {\n\tconst files = FILES[ui];\n\tconst fonts = ui === 'scalar' ? ` ${SCALAR_FONTS}` : '';\n\treturn [\n\t\t\"default-src 'none'\",\n\t\t`script-src ${files} 'nonce-${nonce}'`,\n\t\t`style-src ${files} 'unsafe-inline'`,\n\t\t'img-src https: data:',\n\t\t`font-src data:${fonts}`,\n\t\t[\"connect-src 'self'\", ...origins].join(' '),\n\t\t'worker-src blob:',\n\t\t\"base-uri 'none'\",\n\t\t\"form-action 'none'\",\n\t\t\"frame-ancestors 'none'\",\n\t].join('; ');\n}\n\n/**\n * Scalar's configuration: the document at `url`, and none of the services\n * it would reach beyond this server — its AI agent, its MCP generator,\n * the developer tools that share or deploy the document to scalar.com,\n * its telemetry.\n */\nfunction scalarConfiguration(url: string): string {\n\treturn JSON.stringify({\n\t\turl,\n\t\tagent: { disabled: true },\n\t\tmcp: { disabled: true },\n\t\tshowDeveloperTools: 'never',\n\t\ttelemetry: false,\n\t});\n}\n\nexport interface PageOptions {\n\treadonly title: string;\n\t/** Where the page reads the spec: a URL path, JSON. */\n\treadonly specUrl: string;\n\treadonly nonce: string;\n}\n\nexport function page(ui: DocsUi, options: PageOptions): string {\n\treturn ui === 'swagger' ? swaggerPage(options) : scalarPage(options);\n}\n\nfunction scalarPage({ title, specUrl }: PageOptions): string {\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(title)}</title>\n</head>\n<body>\n<script id=\"api-reference\" data-configuration=\"${escapeHtml(scalarConfiguration(specUrl))}\"></script>\n<script src=\"${SCALAR.src}\" integrity=\"${SCALAR.integrity}\" crossorigin=\"anonymous\"></script>\n</body>\n</html>\n`;\n}\n\nfunction swaggerPage({ title, specUrl, nonce }: PageOptions): string {\n\t// `<` escaped: a URL cannot close the script element\n\tconst url = JSON.stringify(specUrl).replaceAll('<', '\\\\u003c');\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(title)}</title>\n<link rel=\"stylesheet\" href=\"${SWAGGER.css}\" integrity=\"${SWAGGER.cssIntegrity}\" crossorigin=\"anonymous\">\n</head>\n<body>\n<div id=\"swagger-ui\"></div>\n<script src=\"${SWAGGER.script}\" integrity=\"${SWAGGER.scriptIntegrity}\" crossorigin=\"anonymous\"></script>\n<script nonce=\"${nonce}\">window.ui = SwaggerUIBundle({ url: ${url}, dom_id: '#swagger-ui' });</script>\n</body>\n</html>\n`;\n}\n",
|
|
8
|
+
"import {\n\tisHealthRoute,\n\tjoinPath,\n\ttype RouteDefinition,\n\ttype RouteOperation,\n\ttype RoutePath,\n\tshapeOf,\n} from '@softistx/alxia';\nimport { isApiDocsRoute } from './api-docs';\n\n/**\n * The operations to check: the `operations` object a code generator writes,\n * keyed by operation id, or a list of them.\n */\nexport type Operations =\n\t| { readonly [name: string]: RouteOperation }\n\t| readonly RouteOperation[];\n\nexport interface ImplementedOptions {\n\t/**\n\t * The prefix the app gave its routes, `'/api'` for `alxia({ prefix: '/api' })`:\n\t * each operation's path is looked up under it. Written as the app's: a\n\t * leading `/`, and no trailing one.\n\t */\n\treadonly prefix?: RoutePath;\n}\n\nexport interface MatchesSpecOptions extends ImplementedOptions {\n\t/**\n\t * Fail on each route no operation declares too, so the document is\n\t * exhaustive. Off by default: an app may serve routes the document does\n\t * not describe (a proxied one, a hand-written one) and still match it.\n\t */\n\treadonly strict?: boolean;\n\t/**\n\t * A route no operation has to declare: left out of `extra`, and of the\n\t * failure under `strict`. The routes of\n\t * `apiDocs()` and the probes of `@softistx/alxia`'s `health()` are left out\n\t * already.\n\t */\n\treadonly exclude?: (route: RouteDefinition) => boolean;\n}\n\n/** What `matchesSpec` returns when it passes. */\nexport interface MatchesSpecReport {\n\t/**\n\t * The routes of the app no operation declares, by method and full path,\n\t * `exclude`, `apiDocs()` and `health()` aside. Information by default;\n\t * under `strict` a failure, so it is always empty on return.\n\t */\n\treadonly extra: readonly { readonly method: string; readonly path: string }[];\n}\n\n/**\n * Any `alxia()` app: its routes, with their full paths. The public\n * signatures spell it out, so that `tsc` names the shape, not this alias.\n */\ntype Routed = { readonly routes: readonly RouteDefinition[] };\n\n/** An operation as looked up: its method, its full path, and its name. */\ninterface Wanted {\n\treadonly method: string;\n\treadonly path: string;\n\treadonly name: string | undefined;\n}\n\n/**\n * Throws a `TypeError` listing each operation that has no route on `app`, by\n * method and path. Call it in a test, or at startup, once every route is\n * declared.\n */\nexport function implemented(\n\tapp: { readonly routes: readonly RouteDefinition[] },\n\toperations: Operations,\n\toptions: ImplementedOptions = {},\n): void {\n\tconst missing = unrouted(\n\t\tapp,\n\t\twanted('implemented', operations, options.prefix),\n\t);\n\tif (missing.length > 0) {\n\t\tthrow new TypeError(`implemented(): ${noRoute(missing)}`);\n\t}\n}\n\n/**\n * Throws a `TypeError` listing each operation with no route, as\n * `implemented` does: a route of another method or path does not serve it.\n * A route no operation declares does not fail, and is returned as `extra`;\n * with `strict: true` it fails too, `exclude` aside.\n */\nexport function matchesSpec(\n\tapp: { readonly routes: readonly RouteDefinition[] },\n\toperations: Operations,\n\toptions: MatchesSpecOptions = {},\n): MatchesSpecReport {\n\treturn match('matchesSpec', app, operations, options);\n}\n\nfunction match(\n\tcheck: 'matchesSpec',\n\tapp: Routed,\n\toperations: Operations,\n\toptions: MatchesSpecOptions,\n): MatchesSpecReport {\n\tconst all = wanted(check, operations, options.prefix);\n\tconst missing = unrouted(app, all);\n\tconst declared = new Set(all.map(keyOf));\n\tconst undocumented = app.routes.filter(\n\t\t(route) =>\n\t\t\t!declared.has(keyOf(route)) &&\n\t\t\t!isApiDocsRoute(route) &&\n\t\t\t!isHealthRoute(route) &&\n\t\t\t!(options.exclude?.(route) ?? false),\n\t);\n\tconst extra = undocumented.map(({ method, path }) => ({ method, path }));\n\tconst parts: string[] = [];\n\tif (missing.length > 0) parts.push(noRoute(missing));\n\tif (options.strict === true && undocumented.length > 0) {\n\t\tparts.push(noOperation(undocumented));\n\t}\n\tif (parts.length > 0) throw new TypeError(`${check}(): ${parts.join('; ')}`);\n\treturn { extra };\n}\n\nfunction wanted(\n\tcheck: 'implemented' | 'matchesSpec',\n\toperations: Operations,\n\tprefix = '',\n): Wanted[] {\n\t// As the core refuses one: a typed prefix can still be '/api/'.\n\tif (prefix !== '' && !/^\\/.*[^/]$/.test(prefix)) {\n\t\tthrow new TypeError(\n\t\t\t`${check}(): the prefix \"${prefix}\" must start with \"/\" and not end with one`,\n\t\t);\n\t}\n\tconst named: [string | undefined, RouteOperation][] = Array.isArray(\n\t\toperations,\n\t)\n\t\t? operations.map((operation) => [\n\t\t\t\toperation.schema?.detail?.operationId,\n\t\t\t\toperation,\n\t\t\t])\n\t\t: Object.entries(operations);\n\treturn named.map(([name, operation]) => {\n\t\tconst path = joinPath(prefix, operation.path);\n\t\ttry {\n\t\t\tshapeOf(path);\n\t\t} catch (error) {\n\t\t\t// No route may be declared there: say so, named by the check.\n\t\t\tthrow new TypeError(`${check}(): ${(error as Error).message}`);\n\t\t}\n\t\treturn { method: operation.method, path, name };\n\t});\n}\n\n/**\n * The operations no route serves. `HEAD` is served by the `GET` route. An\n * `all` route (`ALL`) serves none: it answers every method, but declares no\n * operation's, so it is `extra`.\n */\nfunction unrouted(app: Routed, all: readonly Wanted[]): Wanted[] {\n\tconst routed = new Set(app.routes.map(keyOf));\n\treturn all.filter(\n\t\t(operation) =>\n\t\t\t!routed.has(keyOf(operation)) &&\n\t\t\t!(\n\t\t\t\toperation.method === 'HEAD' &&\n\t\t\t\trouted.has(keyOf({ ...operation, method: 'GET' }))\n\t\t\t),\n\t);\n}\n\n/**\n * A method and a path's shape: `/pets/:id` serves what `/pets/:petId`\n * declares, as the router matches them alike.\n */\nfunction keyOf(route: { readonly method: string; readonly path: string }) {\n\treturn `${route.method} ${shapeOf(route.path)}`;\n}\n\nfunction noRoute(missing: readonly Wanted[]): string {\n\tconst list = missing\n\t\t.map(({ method, path, name }) =>\n\t\t\tname === undefined ? `${method} ${path}` : `${method} ${path} (${name})`,\n\t\t)\n\t\t.join(', ');\n\treturn missing.length === 1\n\t\t? `1 operation has no route: ${list}`\n\t\t: `${missing.length} operations have no route: ${list}`;\n}\n\nfunction noOperation(extra: readonly RouteDefinition[]): string {\n\tconst list = extra.map(({ method, path }) => `${method} ${path}`).join(', ');\n\treturn extra.length === 1\n\t\t? `1 route has no operation: ${list}`\n\t\t: `${extra.length} routes have no operation: ${list}`;\n}\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": ";AAAA;AAAA;AAAA;AAAA;;;ACAA;AAsBO,SAAS,QAAQ,CACvB,MACA,SACa;AAAA,EACb,IAAI;AAAA,EACJ,IAAI,WAAoB;AAAA,EACxB,IAAI,OAAO,SAAS,UAAU;AAAA,IAC7B,OAAO,KAAK,IAAI;AAAA,IAChB,WAAW,MAAM,MAAM,IAAI;AAAA,EAC5B;AAAA,EACA,IACC,OAAO,aAAa,YACpB,aAAa,QACb,MAAM,QAAQ,QAAQ,KACtB,OAAQ,SAAmC,YAAY,UACtD;AAAA,IACD,MAAM,IAAI,UACT,cAAc,OAAO,SAAS,WAAW,IAAI,UAAU,oEACxD;AAAA,EACD;AAAA,EACA,MAAM,QAAQ,UAAU,KAAK,UAAU,QAAQ,IAAI;AAAA,EACnD,MAAM,OAAO,KAAK,UAAU,OAAO,MAAM,CAAC;AAAA,EAE1C,MAAM,OACL,SAAS,aAAa,YAAY,aAAa,CAAC,OAAO,IAAI,IACxD,OACA,IAAI,KAAK,UAAU,OAAO,MAAM,CAAC;AAAA,EACrC,OAAO,EAAE,MAAM,MAAM,SAAS,UAAU,KAAK,EAAE;AAAA;AAQhD,SAAS,SAAS,CAAC,UAA4B;AAAA,EAC9C,MAAM,UAAW,SAAmC;AAAA,EACpD,IAAI,CAAC,MAAM,QAAQ,OAAO;AAAA,IAAG,OAAO,CAAC;AAAA,EACrC,MAAM,UAAU,IAAI;AAAA,EACpB,WAAW,UAAU,SAAS;AAAA,IAC7B,MAAM,MAAO,QAAqC;AAAA,IAClD,IAAI,OAAO,QAAQ,Y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,QAAQ,MAAM,CAAC,CAAC,EAEpD;AAAA;AAOD,SAAS,KAAK,CAAC,OAA2D;AAAA,EACzE,OAAO,GAAG,MAAM,UAAU,QAAQ,MAAM,IAAI;AAAA;AAG7C,SAAS,OAAO,CAAC,SAAoC;AAAA,EACpD,MAAM,OAAO,QACX,IAAI,GAAG,QAAQ,MAAM,WACrB,SAAS,YAAY,GAAG,UAAU,SAAS,GAAG,UAAU,SAAS,OAClE,EACC,KAAK,IAAI;AAAA,EACX,OAAO,QAAQ,WAAW,IACvB,6BAA6B,SAC7B,GAAG,QAAQ,oCAAoC;AAAA;AAGnD,SAAS,WAAW,CAAC,OAA2C;AAAA,EAC/D,MAAM,OAAO,MAAM,IAAI,GAAG,QAAQ,WAAW,GAAG,UAAU,MAAM,EAAE,KAAK,IAAI;AAAA,EAC3E,OAAO,MAAM,WAAW,IACrB,6BAA6B,SAC7B,GAAG,MAAM,oCAAoC;AAAA;",
|
|
11
|
+
"debugId": "0D5EA892B6D0464864756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type RouteDefinition, type RouteOperation, type RoutePath } from '@softistx/alxia';
|
|
2
|
+
/**
|
|
3
|
+
* The operations to check: the `operations` object a code generator writes,
|
|
4
|
+
* keyed by operation id, or a list of them.
|
|
5
|
+
*/
|
|
6
|
+
export type Operations = {
|
|
7
|
+
readonly [name: string]: RouteOperation;
|
|
8
|
+
} | readonly RouteOperation[];
|
|
9
|
+
export interface ImplementedOptions {
|
|
10
|
+
/**
|
|
11
|
+
* The prefix the app gave its routes, `'/api'` for `alxia({ prefix: '/api' })`:
|
|
12
|
+
* each operation's path is looked up under it. Written as the app's: a
|
|
13
|
+
* leading `/`, and no trailing one.
|
|
14
|
+
*/
|
|
15
|
+
readonly prefix?: RoutePath;
|
|
16
|
+
}
|
|
17
|
+
export interface MatchesSpecOptions extends ImplementedOptions {
|
|
18
|
+
/**
|
|
19
|
+
* Fail on each route no operation declares too, so the document is
|
|
20
|
+
* exhaustive. Off by default: an app may serve routes the document does
|
|
21
|
+
* not describe (a proxied one, a hand-written one) and still match it.
|
|
22
|
+
*/
|
|
23
|
+
readonly strict?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* A route no operation has to declare: left out of `extra`, and of the
|
|
26
|
+
* failure under `strict`. The routes of
|
|
27
|
+
* `apiDocs()` and the probes of `@softistx/alxia`'s `health()` are left out
|
|
28
|
+
* already.
|
|
29
|
+
*/
|
|
30
|
+
readonly exclude?: (route: RouteDefinition) => boolean;
|
|
31
|
+
}
|
|
32
|
+
/** What `matchesSpec` returns when it passes. */
|
|
33
|
+
export interface MatchesSpecReport {
|
|
34
|
+
/**
|
|
35
|
+
* The routes of the app no operation declares, by method and full path,
|
|
36
|
+
* `exclude`, `apiDocs()` and `health()` aside. Information by default;
|
|
37
|
+
* under `strict` a failure, so it is always empty on return.
|
|
38
|
+
*/
|
|
39
|
+
readonly extra: readonly {
|
|
40
|
+
readonly method: string;
|
|
41
|
+
readonly path: string;
|
|
42
|
+
}[];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Throws a `TypeError` listing each operation that has no route on `app`, by
|
|
46
|
+
* method and path. Call it in a test, or at startup, once every route is
|
|
47
|
+
* declared.
|
|
48
|
+
*/
|
|
49
|
+
export declare function implemented(app: {
|
|
50
|
+
readonly routes: readonly RouteDefinition[];
|
|
51
|
+
}, operations: Operations, options?: ImplementedOptions): void;
|
|
52
|
+
/**
|
|
53
|
+
* Throws a `TypeError` listing each operation with no route, as
|
|
54
|
+
* `implemented` does: a route of another method or path does not serve it.
|
|
55
|
+
* A route no operation declares does not fail, and is returned as `extra`;
|
|
56
|
+
* with `strict: true` it fails too, `exclude` aside.
|
|
57
|
+
*/
|
|
58
|
+
export declare function matchesSpec(app: {
|
|
59
|
+
readonly routes: readonly RouteDefinition[];
|
|
60
|
+
}, operations: Operations, options?: MatchesSpecOptions): Mat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AAuB,GAC9B,iBAAiB,CAEnB"}
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# @softistx/alxia-openapi documentation
|
|
2
|
+
|
|
3
|
+
The [package README](../README.md) is the short version. This folder is
|
|
4
|
+
the long one: the spec-first workflow end to end, how the checks match an
|
|
5
|
+
operation to a route, and what to do with each message the checks and the
|
|
6
|
+
generator print.
|
|
7
|
+
|
|
8
|
+
| Page | Read it when |
|
|
9
|
+
| --- | --- |
|
|
10
|
+
| [Spec first](guide/spec-first.md) | starting an API from its OpenAPI document: configuring `@nxgt/openapi-codegen`, declaring alxia's 400, binding the generated operations with middlewares, committing the generated files, checking them in CI, and generating a client from the same document |
|
|
11
|
+
| [Testing with the generated client](guide/testing.md) | calling the app in a test through `@nxgt/openapi-httpyz` and `app.fetch`, with no server, every call typed by the spec, and keeping `app.request` for requests the spec forbids |
|
|
12
|
+
| [API docs](guide/api-docs.md) | serving an interactive page and the document from the app, choosing Scalar or Swagger UI, turning it off in production, using it with `secureHeaders`, or running it beside a GraphQL endpoint |
|
|
13
|
+
| [The checks](guide/checks.md) | calling `implemented` or `matchesSpec` in a test or at startup, checking an app with routes with middlewares, or choosing what `matchesSpec` leaves out |
|
|
14
|
+
| [How routes are matched](guide/matching.md) | understanding how the checks match operations to routes: the path's shape, prefixes, and special cases |
|
|
15
|
+
| [Troubleshooting](troubleshooting.md) | a check threw, the generator refused the document or left an operation out, or an import from an older version no longer compiles |
|
|
16
|
+
| [Roadmap](roadmap.md) | wondering what is coming, what is not planned, and what this package was called before |
|
|
17
|
+
|
|
18
|
+
## Recipes
|
|
19
|
+
|
|
20
|
+
A task that crosses packages, in [the repository's recipes](https://github.com/softistx/alxia/blob/develop/docs/recipes/README.md), each with a complete example:
|
|
21
|
+
|
|
22
|
+
- [A spec-first CRUD API](https://github.com/softistx/alxia/blob/develop/docs/recipes/spec-first-crud.md): `openapi.yaml` to routes, `matchesSpec`, a typed test client and `apiDocs`
|
|
23
|
+
- [Test an alxia app](https://github.com/softistx/alxia/blob/develop/docs/recipes/testing.md): `app.request`, a middleware alone, the typed client, sockets, Redis
|
|
24
|
+
- [Answer errors consistently](https://github.com/softistx/alxia/blob/develop/docs/recipes/errors.md): problem details, `HttpError`, a `try`/`catch` middleware
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# API docs
|
|
2
|
+
|
|
3
|
+
`apiDocs` serves the OpenAPI document and an interactive page for it. It is
|
|
4
|
+
a plugin: one line, no configuration, and nothing added to your
|
|
5
|
+
dependencies.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { alxia } from '@softistx/alxia';
|
|
9
|
+
import { apiDocs } from '@softistx/alxia-openapi';
|
|
10
|
+
import spec from '../openapi.yaml'; // Bun imports YAML, and bundles it
|
|
11
|
+
|
|
12
|
+
export const app = alxia().plugin(apiDocs({ spec }));
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
| Route | Answers |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `GET /docs` | the interactive page |
|
|
18
|
+
| `GET /docs/openapi.yaml` | the document |
|
|
19
|
+
| `GET /docs/openapi.json` | the same, as JSON |
|
|
20
|
+
|
|
21
|
+
It is for the REST side of an app, the document you wrote first
|
|
22
|
+
([Spec first](spec-first.md)). A GraphQL endpoint has its own explorer: see
|
|
23
|
+
[Beside a GraphQL endpoint](#beside-a-graphql-endpoint).
|
|
24
|
+
|
|
25
|
+
## The spec
|
|
26
|
+
|
|
27
|
+
`spec` is one of:
|
|
28
|
+
|
|
29
|
+
- the document as an object. Import it: Bun reads a `.yaml` or `.json`
|
|
30
|
+
import as an object, and `bun build` bundles it, so the app a Dockerfile
|
|
31
|
+
builds into `dist/` alone still has it. This is the form to start with;
|
|
32
|
+
- a path to a YAML or JSON file, read once, when `apiDocs` is called. A
|
|
33
|
+
relative path is looked up from the working directory of the process, so
|
|
34
|
+
the file must ship beside the app: a bundled app whose image holds
|
|
35
|
+
`dist/` alone throws at startup. The file is parsed with Bun's own YAML
|
|
36
|
+
support (`Bun.YAML`), so there is no parser to install, and a YAML file
|
|
37
|
+
is served as written, comments included.
|
|
38
|
+
|
|
39
|
+
A file that is missing, does not parse, or has no `openapi` version throws a
|
|
40
|
+
`TypeError` at startup, naming `apiDocs()`, rather than serving a blank page
|
|
41
|
+
([troubleshooting](../troubleshooting.md#typeerror-apidocs-cannot-read-the-spec-)).
|
|
42
|
+
|
|
43
|
+
## Options
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
apiDocs({
|
|
47
|
+
spec, // import spec from '../openapi.yaml'
|
|
48
|
+
path: '/reference', // default '/docs'; the files are at /reference/openapi.yaml and .json
|
|
49
|
+
ui: 'swagger', // 'scalar' (default) or 'swagger'
|
|
50
|
+
title: 'Todos API', // default: the document's info.title
|
|
51
|
+
servers: [{ url: 'http://localhost:3000', description: 'local' }],
|
|
52
|
+
enabled: Bun.env.NODE_ENV === 'development', // default true
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
- **`path`** starts with `/` and does not end with one. In an app with a
|
|
57
|
+
prefix, `alxia({ prefix: '/api' })`, the routes are under it, as any
|
|
58
|
+
plugin's: `GET /api/docs`.
|
|
59
|
+
- **`ui`** is [Scalar](https://scalar.com) or
|
|
60
|
+
[Swagger UI](https://swagger.io/tools/swagger-ui/).
|
|
61
|
+
- **`servers`** replaces the document's `servers`, in the page and in both
|
|
62
|
+
files: the page's "Try it out" then calls the server you name, such as
|
|
63
|
+
localhost in development.
|
|
64
|
+
- **`enabled: false`** mounts nothing and reads nothing, so the file may be
|
|
65
|
+
absent. Read the environment at runtime, with `Bun.env`, as above, never
|
|
66
|
+
`process.env.NODE_ENV`: `bun build` replaces that with the mode of the
|
|
67
|
+
build, so a bundle built without it would serve the page in production.
|
|
68
|
+
|
|
69
|
+
## The document is public unless you guard it
|
|
70
|
+
|
|
71
|
+
Mounted as above, the page and the document answer anyone who can reach the
|
|
72
|
+
app, as every route does. To keep them behind a login, give the guard to
|
|
73
|
+
`use('/docs', …)` before the plugin: it runs on the three routes, and on
|
|
74
|
+
nothing else.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { alxia } from '@softistx/alxia';
|
|
78
|
+
import { apiDocs } from '@softistx/alxia-openapi';
|
|
79
|
+
import spec from '../openapi.yaml';
|
|
80
|
+
import { requireAdmin } from './auth'; // your own middleware
|
|
81
|
+
|
|
82
|
+
export const app = alxia()
|
|
83
|
+
.use('/docs', requireAdmin)
|
|
84
|
+
.plugin(apiDocs({ spec }));
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Or mount it in a group, after the guard; its routes then move under the
|
|
88
|
+
group's prefix, `/internal/docs`:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const app = alxia().group('/internal', (g) =>
|
|
92
|
+
g.use(requireAdmin).plugin(apiDocs({ spec })),
|
|
93
|
+
);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Where the page's code comes from
|
|
97
|
+
|
|
98
|
+
The page is one small HTML file, and the interface loads from
|
|
99
|
+
`cdn.jsdelivr.net`: Scalar's `@scalar/api-reference` or `swagger-ui-dist`,
|
|
100
|
+
each at the exact version this release of the package was written for, with
|
|
101
|
+
a `sha384` integrity hash, so a changed file does not run. The browser needs
|
|
102
|
+
to reach the CDN; the server does not. Upgrading the interface is a release
|
|
103
|
+
of `@softistx/alxia-openapi`, not a surprise.
|
|
104
|
+
|
|
105
|
+
## With `secureHeaders`
|
|
106
|
+
|
|
107
|
+
`secureHeaders` gives a page that needs scripts a problem: its default
|
|
108
|
+
policy, `default-src 'none'`, blocks the CDN. `apiDocs` settles it on the
|
|
109
|
+
page: **the docs page sets its own `Content-Security-Policy`**, and
|
|
110
|
+
`secureHeaders` keeps a header a route set (as `@softistx/alxia-graphql`'s IDE does),
|
|
111
|
+
so the two work together with no option on either side, with or without
|
|
112
|
+
`nonce: true`:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { secureHeaders } from '@softistx/alxia-secure-headers';
|
|
116
|
+
|
|
117
|
+
const app = alxia()
|
|
118
|
+
.use(secureHeaders({ nonce: true }))
|
|
119
|
+
.plugin(apiDocs({ spec }));
|
|
120
|
+
// /docs: its own policy. Every other response: secureHeaders' policy, a nonce included.
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
The policy is written for this page and is fresh for each response: scripts
|
|
124
|
+
from the pinned version's folder on `cdn.jsdelivr.net` alone
|
|
125
|
+
(`/npm/@scalar/api-reference@<version>/` or `/npm/swagger-ui-dist@<version>/`)
|
|
126
|
+
and, for Swagger UI's one inline script, a nonce the page makes itself;
|
|
127
|
+
styles from that folder and inline ones (both UIs inject styles); images
|
|
128
|
+
over `https:` and `data:`; fonts from `data:` and, for Scalar, its own
|
|
129
|
+
`fonts.scalar.com`; `connect-src` to `'self'` — the spec — and the origin
|
|
130
|
+
of each absolute `servers` URL of the document (or of the `servers`
|
|
131
|
+
option), which "Try it out" calls; no frames, no base URI, no forms. A
|
|
132
|
+
server URL with a template (`https://{region}.example.com`) names no
|
|
133
|
+
origin: give the `servers` option the URLs the page may call.
|
|
134
|
+
|
|
135
|
+
Scalar is configured to reach none of its own services: its AI agent
|
|
136
|
+
("Ask AI"), its MCP generator, the developer tools that share or deploy the
|
|
137
|
+
document on scalar.com, and its telemetry are off. The policy of the rest of the app
|
|
138
|
+
is untouched, so the strict one keeps guarding your API.
|
|
139
|
+
|
|
140
|
+
## `matchesSpec` ignores the docs routes
|
|
141
|
+
|
|
142
|
+
The page and the files are not operations of the document, and
|
|
143
|
+
`matchesSpec` leaves them out by itself, in `extra` and under `strict`:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
matchesSpec(app, operations, { strict: true }); // the three docs routes are not listed
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`isApiDocsRoute(route)` says whether `apiDocs` declared a route, for a check
|
|
150
|
+
of your own, and composes with `exclude`:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
matchesSpec(app, operations, {
|
|
154
|
+
strict: true,
|
|
155
|
+
exclude: (route) => isApiDocsRoute(route) || route.path === '/health',
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Beside a GraphQL endpoint
|
|
160
|
+
|
|
161
|
+
`apiDocs` is for the REST and OpenAPI side. A GraphQL API's explorer is
|
|
162
|
+
[GraphiQL](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs) (`@softistx/graxia-graphiql`),
|
|
163
|
+
served by `@softistx/alxia-graphql` at the endpoint itself: open `/graphql` in a
|
|
164
|
+
browser. The two live in one app, behind the same middlewares:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import { alxia } from '@softistx/alxia';
|
|
168
|
+
import { graphql } from '@softistx/alxia-graphql';
|
|
169
|
+
import { apiDocs, matchesSpec } from '@softistx/alxia-openapi';
|
|
170
|
+
import { secureHeaders } from '@softistx/alxia-secure-headers';
|
|
171
|
+
import { createSchema } from '@softistx/graxia';
|
|
172
|
+
import spec from '../openapi.yaml';
|
|
173
|
+
import { operations } from './generated/alxia';
|
|
174
|
+
|
|
175
|
+
const schema = createSchema()({
|
|
176
|
+
typeDefs: /* GraphQL */ `type Query { hello: String! }`,
|
|
177
|
+
resolvers: { Query: { hello: () => 'world' } },
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
const dev = Bun.env.NODE_ENV === 'development'; // at runtime: bun build inlines process.env.NODE_ENV
|
|
181
|
+
|
|
182
|
+
export const app = alxia()
|
|
183
|
+
.use(secureHeaders())
|
|
184
|
+
.route(operations.listTodos, ({ reply }) => reply.ok([])) // REST, from openapi.yaml
|
|
185
|
+
.plugin((app) => graphql(app, { schema })) // POST and GET /graphql; GraphiQL in dev alone
|
|
186
|
+
.plugin(apiDocs({ spec, enabled: dev })); // GET /docs
|
|
187
|
+
|
|
188
|
+
// the REST routes against the document: the GraphQL endpoint is not one of its operations
|
|
189
|
+
matchesSpec(app, operations, {
|
|
190
|
+
strict: true,
|
|
191
|
+
exclude: (route) => route.path === '/graphql',
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
- `/docs` documents the REST operations only; the GraphQL schema is its own
|
|
196
|
+
document, explored at `/graphql`.
|
|
197
|
+
- Each page sets its own `Content-Security-Policy`; `secureHeaders` keeps
|
|
198
|
+
both, and guards the rest.
|
|
199
|
+
- `apiDocs` leaves its own routes to `matchesSpec`; under `strict`, the GraphQL
|
|
200
|
+
endpoint is excluded by its path, as above.
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
# The checks
|
|
2
|
+
|
|
3
|
+
This page covers `implemented` and `matchesSpec`: what they take, where to call them, and how to check an app
|
|
4
|
+
that has routes with middlewares or routes the document does not declare.
|
|
5
|
+
For how routes are matched, including prefixes and path shapes, see [How routes are matched](matching.md).
|
|
6
|
+
Where the operations come from is [Spec first](spec-first.md).
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { alxia } from '@softistx/alxia';
|
|
10
|
+
import { implemented, matchesSpec } from '@softistx/alxia-openapi';
|
|
11
|
+
import { operations as api } from './generated/alxia';
|
|
12
|
+
|
|
13
|
+
// pets, search: your own store and query
|
|
14
|
+
export const app = alxia()
|
|
15
|
+
.route(api.getPet, ({ params, reply }) => {
|
|
16
|
+
const pet = pets.get(params.petId);
|
|
17
|
+
return pet ? reply.ok(pet) : reply.notFound({ title: 'No such pet' });
|
|
18
|
+
})
|
|
19
|
+
.route(api.searchEmployees, ({ body, reply }) => reply.ok(search(body)));
|
|
20
|
+
|
|
21
|
+
matchesSpec(app, api); // throws if an operation of the spec has no route; reports the routes the spec lacks as `extra`
|
|
22
|
+
matchesSpec(app, api, { strict: true }); // and throws on each route that is not in the spec
|
|
23
|
+
implemented(app, api); // throws only if an operation of the spec has no route
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## The signatures
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
function implemented(
|
|
30
|
+
app: { readonly routes: readonly RouteDefinition[] },
|
|
31
|
+
operations: Operations,
|
|
32
|
+
options?: ImplementedOptions,
|
|
33
|
+
): void;
|
|
34
|
+
|
|
35
|
+
function matchesSpec(
|
|
36
|
+
app: { readonly routes: readonly RouteDefinition[] },
|
|
37
|
+
operations: Operations,
|
|
38
|
+
options?: MatchesSpecOptions,
|
|
39
|
+
): MatchesSpecReport;
|
|
40
|
+
|
|
41
|
+
type Operations =
|
|
42
|
+
| { readonly [name: string]: RouteOperation }
|
|
43
|
+
| readonly RouteOperation[];
|
|
44
|
+
|
|
45
|
+
interface ImplementedOptions {
|
|
46
|
+
readonly prefix?: RoutePath; // `/${string}`, from @softistx/alxia
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface MatchesSpecOptions extends ImplementedOptions {
|
|
50
|
+
readonly strict?: boolean; // fail on a route no operation declares
|
|
51
|
+
readonly exclude?: (route: RouteDefinition) => boolean; // under strict
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface MatchesSpecReport {
|
|
55
|
+
readonly extra: readonly { readonly method: string; readonly path: string }[];
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Any `alxia()` app fits `app`: both read `app.routes`, every HTTP route the
|
|
60
|
+
app holds, groups and plugins included, with their full paths. They send
|
|
61
|
+
no request and start no server.
|
|
62
|
+
|
|
63
|
+
`RouteOperation` is `@softistx/alxia`'s, the type `app.route(operation,
|
|
64
|
+
...middlewares, handler)` reads: `{ method, path, schema? }`. So `operations` is what the
|
|
65
|
+
routes were declared from:
|
|
66
|
+
|
|
67
|
+
- the `operations` object of a generated `alxia.ts`, keyed by operation id
|
|
68
|
+
([Spec first](spec-first.md#2-generate-the-operations)). A message names
|
|
69
|
+
each operation by its key;
|
|
70
|
+
- a list of operations, written by hand or picked from that object. A
|
|
71
|
+
message names each one by its `schema.detail.operationId`, which the
|
|
72
|
+
generator always writes, or by method and path alone when it has none.
|
|
73
|
+
Declare a hand-written list `as const`, or type it `RouteOperation[]`, so
|
|
74
|
+
each `method` stays a `Method`.
|
|
75
|
+
|
|
76
|
+
A path is written the router's way, `/pets/:petId`, as the generator writes
|
|
77
|
+
it, not OpenAPI's `/pets/{petId}`: an operation written with braces matches
|
|
78
|
+
no route.
|
|
79
|
+
|
|
80
|
+
Both return nothing when the check passes, and throw a `TypeError` when it
|
|
81
|
+
does not, listing everything that is wrong at once. An operation path no
|
|
82
|
+
route may be declared at — `/pets/:pet-id`, `/a/*/b` — is the exception: it
|
|
83
|
+
throws at once, with the core's reason for that path, since no route
|
|
84
|
+
could serve it ([troubleshooting](../troubleshooting.md#typeerror-implemented---is-not-a-parameter-name)).
|
|
85
|
+
|
|
86
|
+
## `implemented`
|
|
87
|
+
|
|
88
|
+
```text
|
|
89
|
+
TypeError: implemented(): 2 operations have no route: GET /pets/:petId (getPet), QUERY /employees (searchEmployees)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
It lists each operation the app does not serve, in the order of
|
|
93
|
+
`operations`. Routes the document does not declare are fine: a health
|
|
94
|
+
check, a page, an admin route.
|
|
95
|
+
|
|
96
|
+
## `matchesSpec`
|
|
97
|
+
|
|
98
|
+
Called `exactly` until 0.2.0 of `@alxia/openapi-routes`; `exactly` and
|
|
99
|
+
`ExactlyOptions` were removed in 0.5.
|
|
100
|
+
|
|
101
|
+
```text
|
|
102
|
+
TypeError: matchesSpec(): 1 operation has no route: GET /pets/:petId (getPet)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
It throws on each operation with no route, as `implemented` does. A route
|
|
106
|
+
of another method or path does not serve an operation, so a `PUT` route
|
|
107
|
+
where the spec says `GET` fails too. A route the document does not
|
|
108
|
+
declare does not fail: an app may proxy routes, serve a health check, the
|
|
109
|
+
docs or a hand-written route the spec never describes. They come back as
|
|
110
|
+
the report's `extra`, in the order the app declared them, so a test can
|
|
111
|
+
assert on them:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
const { extra } = matchesSpec(app, api);
|
|
115
|
+
expect(extra).toEqual([{ method: 'POST', path: '/admin/reset' }]);
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### `strict: true`
|
|
119
|
+
|
|
120
|
+
For a spec that must be exhaustive, `strict: true` fails on each route that
|
|
121
|
+
no operation declares too, after a `;`, in the order the app declared them:
|
|
122
|
+
|
|
123
|
+
```text
|
|
124
|
+
TypeError: matchesSpec(): 1 operation has no route: GET /pets/:petId (getPet); 1 route has no operation: POST /admin/reset
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Either half appears only when it lists something. Before the check was
|
|
128
|
+
lenient, this was the only behaviour: upgrading, pass `strict: true` to
|
|
129
|
+
keep the old check.
|
|
130
|
+
|
|
131
|
+
`exclude` leaves a route out of the second half, and out of `extra`. It is given the
|
|
132
|
+
route as `app.routes` holds it — method, full path, schema — and returns
|
|
133
|
+
`true` for a route the document does not have to declare:
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { isReactRouterRoute } from '@softistx/alxia-react-router';
|
|
137
|
+
|
|
138
|
+
matchesSpec(app, api, {
|
|
139
|
+
strict: true,
|
|
140
|
+
// the pages a React Router app serves beside the API, and a metrics route of its own
|
|
141
|
+
exclude: (route) => isReactRouterRoute(route) || route.path === '/metrics',
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`isReactRouterRoute`, from `@softistx/alxia-react-router`, is one such predicate:
|
|
146
|
+
`true` for the routes `reactRouter()` declared, its catch-all and the
|
|
147
|
+
client build's files. Any function of the route works. The routes of
|
|
148
|
+
`apiDocs()` and the probes of `@softistx/alxia`'s `health()` — `/health` and
|
|
149
|
+
`/ready`, wherever mounted — need none: `matchesSpec` leaves them out
|
|
150
|
+
already, under `strict`, and from `extra`.
|
|
151
|
+
|
|
152
|
+
`exclude` is not consulted for the first half: an operation with no route
|
|
153
|
+
is always listed.
|
|
154
|
+
|
|
155
|
+
## Routes with middlewares
|
|
156
|
+
|
|
157
|
+
`app.route(operation, ...middlewares, handler)`, in `@softistx/alxia`, gives a
|
|
158
|
+
route declared from an operation the middlewares of any route. The
|
|
159
|
+
operation's schema is two of them, just before the handler: a `validate` of
|
|
160
|
+
its request, then a `responds` of its responses, which checks the handler's
|
|
161
|
+
reply alone. An `auth` placed before them answers 401 before the body is
|
|
162
|
+
read. `validate(operation)`, given the same operation, validates where it
|
|
163
|
+
stands instead, once. Put it after the auth: an anonymous client then gets
|
|
164
|
+
no body parsed, and no validation issues back, which would reveal the
|
|
165
|
+
schema:
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { alxia, defineMiddleware, validate } from '@softistx/alxia';
|
|
169
|
+
import { matchesSpec } from '@softistx/alxia-openapi';
|
|
170
|
+
import { operations as api } from './generated/alxia';
|
|
171
|
+
|
|
172
|
+
const auth = defineMiddleware(({ request, reply }, next) =>
|
|
173
|
+
request.headers.has('authorization') ? next() : reply(401, { error: 'unauthorized' as const }),
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
export const app = alxia()
|
|
177
|
+
.route(api.renamePet, auth, ({ params, body, reply }) => reply.ok(rename(params.petId, body.name)))
|
|
178
|
+
.route(api.adoptPet, auth, validate(api.adoptPet), ({ params, reply }) => reply.created(adopt(params.petId)));
|
|
179
|
+
|
|
180
|
+
matchesSpec(app, api); // the routes are matched as any others: by method and path
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
The checks read `app.routes`, so middlewares change nothing for them. A
|
|
184
|
+
reply a middleware sends, such as `auth`'s 401, is sent as it is, even when
|
|
185
|
+
the document declares its status: the implicit `responds` checks the
|
|
186
|
+
handler's. To check the middlewares' replies too, place
|
|
187
|
+
`responds(operation)` before them; the route then adds no other:
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
import { responds } from '@softistx/alxia';
|
|
191
|
+
|
|
192
|
+
app.route(api.adoptPet, responds(api.adoptPet), auth, ({ params, reply }) => reply.created(adopt(params.petId)));
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`responds(operation)` reads the operation's `schema.response`, and throws
|
|
196
|
+
`responds(): the operation GET /health declares no response` for one that
|
|
197
|
+
declares none.
|
|
198
|
+
|
|
199
|
+
## Where to call it
|
|
200
|
+
|
|
201
|
+
**In a test**, the usual place: the suite fails, naming every missing route,
|
|
202
|
+
before a client meets a 404.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
// app.spec.ts
|
|
206
|
+
import { test } from 'bun:test';
|
|
207
|
+
import { implemented } from '@softistx/alxia-openapi';
|
|
208
|
+
import { app } from './app';
|
|
209
|
+
import { operations } from './generated/alxia';
|
|
210
|
+
|
|
211
|
+
test('every operation of the spec is served', () => {
|
|
212
|
+
implemented(app, operations);
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
**At startup**, with the package installed as a dependency rather than a
|
|
217
|
+
dev dependency, once every route is declared and before `listen`, to refuse
|
|
218
|
+
to start a server that does not serve its spec. It runs once, over the
|
|
219
|
+
routes, and costs nothing per request:
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
implemented(app, operations);
|
|
223
|
+
app.listen(3000);
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Call it after the last `route`, `use`, `plugin` and `group`: a route declared later is
|
|
227
|
+
not in `app.routes` yet.
|
|
228
|
+
|
|
229
|
+
## What it cannot see
|
|
230
|
+
|
|
231
|
+
- **An operation the generator left out.** `@nxgt/openapi-codegen` skips an
|
|
232
|
+
operation alxia cannot route or validate yet — a `TRACE`, a binary body,
|
|
233
|
+
JSON Lines, server-sent events with text data — with an `ignored` warning,
|
|
234
|
+
and it is not in `operations`. Read the generator's warnings: the check only
|
|
235
|
+
knows the operations it is given
|
|
236
|
+
([what the generator leaves out](spec-first.md#what-the-generator-leaves-out-0110)).
|
|
237
|
+
- **A route that answers 404 on purpose.** A route is served if it is
|
|
238
|
+
declared; what its handler does is the specs' to check.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# How routes are matched
|
|
2
|
+
|
|
3
|
+
The checks match an operation to a route by method and path, and handle special cases like prefixes and middleware-declared routes.
|
|
4
|
+
|
|
5
|
+
## How a route is matched
|
|
6
|
+
|
|
7
|
+
An operation is served by a route of the same method and path:
|
|
8
|
+
|
|
9
|
+
- **The path's shape.** A parameter's name does not count:
|
|
10
|
+
`app.get('/pets/:id', …)` serves the operation `GET /pets/:petId`, since
|
|
11
|
+
the router sends them the same requests. Both are compared by
|
|
12
|
+
`shapeOf` from `@softistx/alxia`, the function the router uses itself. As in the router, a parameter
|
|
13
|
+
is a whole `:name` segment, and an operation path with a `:` anywhere
|
|
14
|
+
else, such as `/at/10:45`, throws the core's `TypeError`, as declaring a
|
|
15
|
+
route there would. The route's handler still reads
|
|
16
|
+
`params.id`, not `params.petId`; declaring it with
|
|
17
|
+
`app.route(api.getPet, …)` keeps the spec's names and schemas.
|
|
18
|
+
- **`HEAD`.** The core answers `HEAD` with the `GET` route, so a `HEAD`
|
|
19
|
+
operation is served by a `GET` route at its path. `matchesSpec` still lists
|
|
20
|
+
that `GET` route, as `extra` or under `strict`, when no operation declares it.
|
|
21
|
+
- **Every other method stands alone.** A `POST /employees` route does not
|
|
22
|
+
serve a `QUERY /employees` operation.
|
|
23
|
+
- **An `all` route serves no operation.** `app.all('/api/*', proxy(url))`
|
|
24
|
+
answers every method, but declares none of the document's: it is listed
|
|
25
|
+
as `ALL /api/*`, in `extra` or under `strict`, and an operation under its
|
|
26
|
+
path still needs a route of its own method. Leave it out of `strict`
|
|
27
|
+
with `exclude: (route) => route.method === 'ALL'`.
|
|
28
|
+
- **Socket routes are not read.** `app.ws` routes live in `app.sockets`,
|
|
29
|
+
and an OpenAPI operation is HTTP: `matchesSpec` never lists them.
|
|
30
|
+
|
|
31
|
+
Only the method and the path are compared. A route declared with
|
|
32
|
+
`app.route(operation, ...middlewares, handler)` reads its schemas from the operation, so
|
|
33
|
+
they cannot differ from the spec's; one written by hand is the app's to
|
|
34
|
+
keep in step.
|
|
35
|
+
|
|
36
|
+
## Under a prefix
|
|
37
|
+
|
|
38
|
+
`app.routes` holds full paths, so an app made with `alxia({ prefix: '/api' })`
|
|
39
|
+
serves `api.getPet` at `GET /api/pets/:petId`. The operations are written
|
|
40
|
+
without it, as the document's paths are. Give the prefix, and each operation
|
|
41
|
+
is looked up under it, joined by the core's own `joinPath` (`/` under `/api`
|
|
42
|
+
is `/api`):
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const app = alxia({ prefix: '/api' }).route(api.getPet, getPet);
|
|
46
|
+
|
|
47
|
+
implemented(app, api, { prefix: '/api' });
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Write the prefix as the app's: a leading `/` and no trailing one. `'api'`
|
|
51
|
+
[does not compile](../troubleshooting.md#type-pets-is-not-assignable-to-type-string), and `'/api/'` throws
|
|
52
|
+
[`implemented(): the prefix "/api/" must start with "/" and not end with one`](../troubleshooting.md#typeerror-implemented-the-prefix--must-start-with--and-not-end-with-one).
|
|
53
|
+
|
|
54
|
+
The messages then name the full paths, `GET /api/pets/:petId (getPet)`,
|
|
55
|
+
since those are what the app is missing. For operations served under a
|
|
56
|
+
group, `alxia().group('/v1', …)`, give the group's prefix the same way. A
|
|
57
|
+
call takes one prefix: check each group's operations in a call of their
|
|
58
|
+
own, and use `matchesSpec` only when every route of the app is under that
|
|
59
|
+
prefix, or, under `strict`, excluded.
|