Skip to content

Generate an OpenAPI 3.1 document from the wire contract - #1239

Merged
neuromechanist merged 6 commits into
devfrom
feature/issue-937-openapi-document
Sep 3, 2026
Merged

neuromechanist merged 6 commits into
devfrom
feature/issue-937-openapi-document

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Issue #937 item 2 only (item 1, extracting shared/contract into an npm package, and item 4, the contract-live conformance test, are out of scope for this PR).

Generates an OpenAPI 3.1 document from the Zod schemas in shared/contract/ using @asteasolutions/zod-to-openapi (the zod 3.x-compatible 7.x major, matching this repo's zod ^3.23), and serves it read-only at GET /openapi.json.

Chose shape (b) from the issue: build-time generation into a checked-in static artifact (shared/openapi.json), imported by backend/src/routes/openapi.ts the same way backend/src/routes/schemas.ts imports shared/zarr-index.schema.json ("One file, two readers"). This matches the repo's existing precedent for serving a contract document, keeps generation cost off the Worker's critical path, and lets a test regenerate the document and diff it against the committed artifact so the two cannot silently drift apart.

The document is descriptive only. Every response schema handed to the registry in scripts/generate-openapi.ts is the exact object exported from shared/contract/.ts, registered as-is; shared/contract/.ts itself is not touched by this change (no .describe()/.openapi() annotations added there). No shape, requiredness, type, or refinement was changed anywhere in the contract.

One non-cosmetic generator-level fix was needed: @asteasolutions/zod-to-openapi 7.3.4 renders a nullable enum (e.g. zarr_status, attestation_deposit_type) as {type: ["string", "null"], enum: [...]} without widening the enum array to include null, so a schema that claims to allow null actually rejects it under JSON Schema's enum keyword. This was caught by the round-trip test below against a real nullable zarr_status row. Fixed with a small post-processing pass over the generated document's OUTPUT (not the input contract) that adds null to any enum array whose sibling type allows it.

Routes documented

  • GET /datasets -> datasetListEnvelopeSchema
  • GET /datasets/:id -> datasetDetailEnvelopeSchema
  • GET /datasets/search -> datasetSearchEnvelopeSchema
  • GET /datasets/facets -> datasetFacetsEnvelopeSchema

Plus a reusable VersionTag component from shared/contract/version.ts (the canonical vX.Y.Z tag shape).

Query parameters are read from the real handlers (backend/src/routes/datasets/catalog.ts): the nine legacy bespoke filters (modality, author, task, has_doi, has_hed, has_zarr, has_zarr_verified, data_complete, recent, license, include_unknown) plus all 20 declared facets from shared/facets.ts (built programmatically from that table, so a new facet is documented automatically), plus mine/status/limit/offset/owner/sort/search for the list route and q/limit/offset/min_score for search. GET /datasets/facets takes no query parameters, matching its handler. GET /datasets/:id takes the id path parameter.

Test plan

backend/test/openapi-document.test.ts (unit-pure tier: no network, no live backend):

  • Drift guard: buildOpenApiDocument() deep-equals the committed shared/openapi.json.
  • Structural validity: openapi starts with "3.1", info and non-empty paths present, every $ref resolves under components.schemas, every components.schemas entry compiles as JSON Schema 2020-12 (ajv).
  • Route coverage: every GET route on the real datasets router (introspected via Hono's own .routes, the same mechanism test/datasets-route-inventory.unit.test.ts pins) is either documented or explicitly triaged as out of scope, so a new undocumented route fails the test.
  • Round-trip: a real GET /datasets and GET /datasets/:id response, captured from the actual Hono routes against an in-memory bun:sqlite-backed D1, validates against the generated JSON Schema for DatasetListEnvelope / DatasetDetailEnvelope.

Proved each assertion category actually fails on a one-line mutation (reverted before committing): a stale generator literal without regenerating failed the drift guard; removing one entry from the documented-routes map failed the coverage test; the nullable-enum bug above was caught live by the round-trip test before being fixed.

Gate results:

  • bun run lint (repo default only checks src/): clean. Additionally ran bunx biome check --fix directly against the new/changed files (scripts/generate-openapi.ts, backend/src/routes/openapi.ts, backend/test/openapi-document.test.ts, backend/src/index.ts): clean.
  • bun run typecheck: clean (tsc --noEmit at root and -p backend both pass). scripts/ is outside both tsconfig include globs, matching this repo's existing convention for other scripts/*.ts files; ran a standalone tsc --noEmit against scripts/generate-openapi.ts with equivalent compiler options as an extra check: clean.
  • bun test backend/test/openapi-document.test.ts: 9 pass, 0 fail.
  • bun test backend/test/: 1656 pass, 0 fail (121 files) -- no regressions from this change.
  • Full CI unit-pure tier replicated locally (test/*.test.ts + backend/test/*.test.ts, minus the same exclusions test.yml uses): 3899 pass, 20 skip, 0 fail (258 files, 3919 tests) -- pre-existing skips, no failures.

Part of #937
Part of epic nemarOrg/website#284

Adds scripts/generate-openapi.ts, which builds an OpenAPI 3.1 document from
the shared/contract/ Zod schemas via @asteasolutions/zod-to-openapi, and the
resulting static shared/openapi.json artifact. No contract schema is edited;
generation is descriptive only (issue #937 item 2).
Mounts backend/src/routes/openapi.ts next to the existing /schemas route,
serving the static shared/openapi.json generated by
scripts/generate-openapi.ts. Static and D1-free, matching the /schemas
precedent (backend/src/routes/schemas.ts).
backend/test/openapi-document.test.ts: drift guard against
shared/openapi.json, OpenAPI 3.1 structural validity, public catalog route
coverage derived from the real Hono router, and a round-trip of a real
GET /datasets and GET /datasets/:id response against the generated
JSON Schema components.
@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1239

Version: 0.9.15-PR1239.0ec936d
Commit: 0ec936d


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review addressed. No Critical and no Important findings; the one Suggestion and two of the three Nice-to-haves are fixed, and the third is declined with a reason.

Suggestion, undeclared 401 responses. Fixed in 2f07cdf. Both handlers were read before writing the descriptions, and the two paths turn out to fail differently, which the descriptions now say. On GET /datasets, mine=true with no valid session 401s whether no bearer token was sent or one was sent and rejected. On GET /datasets/{id} the 401 fires only when the dataset is private and a bearer token was sent and rejected; a private dataset requested with no credentials at all still 404s, because disclosing that it exists is itself a leak. That distinction is stated in the document rather than left for a client to discover.

Nice-to-have, no script alias. Fixed in 10c8a47: bun run generate-openapi.

Nice-to-have, the media-type comment. Fixed in 0ec936d. The comment claimed application/openapi+json is what OpenAPI-aware clients content-sniff for, in deliberate parallel with schemas.ts's citation of RFC 9358 for application/schema+json. That parallel implied a formal registration that does not exist. The media type stays, since it is useful and is a strict subtype of application/json, but the comment now says plainly that it is a de facto tooling convention. schemas.ts was not touched; its RFC citation is accurate.

Nice-to-have, scripts/** is outside bun run typecheck. Declined deliberately. tsconfig.json's include is ["src/**/*", "shared/**/*"], so every root-level script is uncovered, not just this one. That is pre-existing and repo-wide, and widening the include inside a descriptive epic phase would change what CI typechecks across the whole repo. Logged for the owner as a separate item rather than carried as silent debt.

The drift guard is the thing worth restating, because it is what makes a committed generated artifact safe: backend/test/openapi-document.test.ts regenerates the document from the live Zod schemas and asserts it deep-equals the committed shared/openapi.json, so editing a contract schema without re-running the generator fails CI rather than shipping a stale document. Route coverage is derived from the real Hono router rather than a hand-typed list, so adding an undocumented public catalog route also fails. Both were exercised by this change: the 401 additions required a regeneration, and the test caught the intermediate state before it was committed.

Gates after the fixes: lint clean, typecheck clean on root and backend, bun test backend/test/openapi-document.test.ts 9 pass, and the full bun test backend/test/ tier 1656 pass with 0 failures.

This branch was previously deployed

1 inactive deployment
npm — 0ec936d2 Deployed Sep 3, 2026 by neuromechanist via publish #2270
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant