From 3a37f4efee32b85bc176016cec1fefc449f86f4f Mon Sep 17 00:00:00 2001 From: Bryan Thompson <18094023+SnowboardTechie@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:14:36 -0800 Subject: [PATCH 01/20] docs(website): add ADR 0032 for API version negotiation (#1400) ### Summary - Fixes #1159 - Time to review: 30 minutes ### Changes proposed Adds [ADR 0032](https://github.com/HHS/simpler-grants-protocol/blob/bryan/1159-adr-0032-version-negotiation/website/src/content/docs/governance/adr/0032-api-version-negotiation.md), which decides how a client asks a CommonGrants API for a protocol version and what the server tells it back: - A client selects a version with an optional `CG-Version` request header. Every response confirms the version served in `CG-Version-Served`, and a client that sends no version gets the server's pinned default. - A server publishes the versions it serves at `GET /common-grants/versions`, as a baseline plus entries for routes that differ. - Version problems get dedicated codes: `version.malformed` and `version.conflict` (400), and `version.unsupported` and `version.retired` (406). - Retirement uses the standard `Deprecation`, `Sunset`, and `Link` headers. A change of default uses `Link` with `rel="successor-version"`, and the date is published in discovery. The ADR is organized as Overview, Evaluation, and Specification, with client and implementer questions in each area. It also covers how a client discovers versions and how a server retires one. It also answers #1372, which is already closed. ### Context for reviewers Implementation is tracked in the [[Core] v0.6.0 release](https://github.com/HHS/simpler-grants-protocol/milestone/5) milestone: headers #1386, discovery #1387, version errors #1388, and the mock API #1393. The specification's versioning section still describes a patch as adding "new optional functionality", which contradicts this ADR. #1389 owns that correction, along with documenting the default-change link. This PR also adds a "Partly superseded" note to [ADR 0028](https://github.com/HHS/simpler-grants-protocol/blob/bryan/1159-adr-0032-version-negotiation/website/src/content/docs/governance/adr/0028-mock-api-hosting.md), since this decision replaces its version path prefix while the rest of 0028 stands. Verified locally: Prettier and cspell pass on the changed files, and the website builds. ### Additional information Rendered page: the website preview link on this PR, at `/governance/adr/0032-api-version-negotiation/`. --- .../governance/adr/0028-mock-api-hosting.md | 4 + .../adr/0032-api-version-negotiation.md | 783 ++++++++++++++++++ 2 files changed, 787 insertions(+) create mode 100644 website/src/content/docs/governance/adr/0032-api-version-negotiation.md diff --git a/website/src/content/docs/governance/adr/0028-mock-api-hosting.md b/website/src/content/docs/governance/adr/0028-mock-api-hosting.md index cd9e492e4..85ef69882 100644 --- a/website/src/content/docs/governance/adr/0028-mock-api-hosting.md +++ b/website/src/content/docs/governance/adr/0028-mock-api-hosting.md @@ -3,6 +3,10 @@ title: Mock API hosting description: Records the decision to serve the fixture-backed mock CommonGrants API from the docs website itself, so the browser, curl, and the SDK all hit the same endpoint and see the same data. --- +:::caution[Partly superseded] +[ADR 0032: API version negotiation](/governance/adr/0032-api-version-negotiation/) supersedes this ADR's version path prefix (`/api/v{version}/...`). The mock moves to the `CG-Version` request header. The rest of this decision, serving the mock from the docs website, still stands. +::: + We want visitors to test the CommonGrants API against a mock for every published spec version (v0.1.0 to v0.4.0). We're turning Swagger UI's "Try it out" back on in the browser, but our core goal is **determinism**. A user should be able to try a request in the browser, copy the `curl` command and run it in their terminal, point the SDK at the same URL, and get the **same data** every time. The mock also gives the quickstart a sandbox: a new SDK user can fetch realistic grant data with no local setup. So the mock has three consumers: diff --git a/website/src/content/docs/governance/adr/0032-api-version-negotiation.md b/website/src/content/docs/governance/adr/0032-api-version-negotiation.md new file mode 100644 index 000000000..538d2b2cc --- /dev/null +++ b/website/src/content/docs/governance/adr/0032-api-version-negotiation.md @@ -0,0 +1,783 @@ +--- +title: API version negotiation +description: ADR documenting the decision to select a CommonGrants protocol version with a request header, advertise supported versions at a discovery route, and announce retirement with standard HTTP headers. +tableOfContents: + maxHeadingLevel: 3 +--- + +A CommonGrants API can serve more than one protocol version, and clients built against different versions need to ask for the one they were built for. The protocol defines no way to do that today. A client can't ask for a version, can't find out which versions a server supports, and can't confirm which version a response was served in. The mock API selects a version by path prefix ([ADR 0028](https://commongrants.org/governance/adr/0028-mock-api-hosting/)), but production APIs have no shared convention. + +We decided that a client selects a version with an optional `CG-Version` request header, a server lists the versions it serves at `GET /common-grants/versions`, and every response confirms the version it was served in. Retirement uses the standard `Deprecation` and `Sunset` headers. + +This decision covers three areas: discovering supported versions, requesting a specific version, and retiring a version, which includes changing a server's default. How the SDKs support versioning is a separate decision. + +## Overview + +### Decision + +:::note[At a glance] + +- A client selects a version with an optional `CG-Version` request header. Every response confirms the version served in `CG-Version-Served`, and a client that sends no version gets the server's pinned default. +- A server publishes its supported versions at `GET /common-grants/versions`, as a baseline plus entries for routes that differ. It's required only for servers that serve more than one version. +- Version problems get dedicated codes: `version.malformed` and `version.conflict` (400), and `version.unsupported` and `version.retired` (406). +- Retiring a version uses the standard `Deprecation`, `Sunset`, and `Link` headers. A change of default uses `Link` with `rel="successor-version"`, with the date published in discovery. + +::: + +We recommend that servers move all their routes to a new version at the same time. The protocol doesn't require it: a server can serve different versions on different routes and advertise those exceptions in discovery. + +#### Discovering supported versions + +- A server publishes `GET /common-grants/versions`: a baseline (the default version and the versions every route serves) plus entries for routes that differ, in the standard success envelope. +- The route is optional, and required for servers that serve more than one version. It SHOULD be readable without authentication. +- It takes no request parameters, ignores `CG-Version`, and never returns a version error. +- Optional lifecycle fields appear while a change is pending: the upcoming default and its date, and deprecated versions with their deprecation and sunset dates. Dates use RFC 3339. +- Fields are only ever added, and clients ignore fields they don't recognize. +- Ordinary responses don't carry a supported-versions header. Discovery and unsupported-version errors carry the list. + +#### Requesting a specific version + +- A client selects a version only with the `CG-Version` request header: no path segment, query parameter, or media type. Each request carries one value. +- The header applies only to protocol routes under `/common-grants/`, relative to the API's base URL, so a host API may mount them at a path such as `/api/v2/common-grants/`. Custom routes and the discovery route ignore it. +- A version is a full published version, such as `0.5.0`. Servers match on major and minor, so a request for `0.5.0` is served by a server hosting `0.5.1`. A server never substitutes a different major or minor version. +- A request without the header is served in the server's pinned default. A server adopting negotiation sets its default to the version it already serves, and adding versions never moves it. +- Every response produced after a version is selected carries `CG-Version-Served` with the full version served. The served version travels in headers only, so response bodies don't change. +- Version problems return `version.malformed` (400), `version.unsupported` (406), `version.retired` (406), or `version.conflict` (400), never 404 or 410. +- Cacheable responses carry `Vary: CG-Version`, and cross-origin servers allow and expose the version headers. + +#### Retiring a version + +- **Retiring a version:** responses served in it carry `Deprecation`, `Sunset`, and `Link` headers, with their standard IETF meaning, and discovery lists it as deprecated. After the sunset date, requests for it get `version.retired` for a period the server chooses, and `version.unsupported` after that. +- **Changing the default:** responses served by default carry a `Link` with `rel="successor-version"`, and discovery shows the upcoming default and its date. Clients that send a version see no change. +- A retiring default moves forward to the next newer version no later than the sunset. A server can't retire its default without a newer version to move to. +- A single route retires a version the same way as the whole server. Experimental routes are exempt. + +### Consequences + +- **Positive consequences** + - Resource URLs never change across versions, so links stored in grant systems stay valid, and a host API keeps its own path scheme. + - Existing clients keep working without changes: a server adopting negotiation keeps serving them the version they already use. + - A server can upgrade one route at a time and say so truthfully, and a client can predict a route's versions before calling it. + - Every response says which version it is, and an unconfirmed response is recognizable as unconfirmed. + - Retirement uses headers that existing HTTP tooling already understands, with their standard meaning. + - The 0.6.0 contract is purely additive. The version headers, errors, and discovery route are declared from 0.6.0, and the published 0.1.0 through 0.5.0 contracts don't change. A negotiating server sends `CG-Version-Served` whatever version it serves; a client of an older version gets one extra header and, because it sends no `CG-Version`, never a version error. +- **Negative consequences** + - A URL alone doesn't reproduce a version. Bug reports, docs examples, and curl commands have to include the header. + - Servers behind shared caches or CDNs need `Vary: CG-Version`, and some CDNs need the header added to their cache key. + - Cross-origin servers need CORS configuration for the version headers. + - Discovery dates use RFC 3339, `Deprecation` uses the `@` form, and `Sunset` uses HTTP-date. Client parsers and the docs have to handle all three. + - A client that sends no version accepts that its default can move. Before 1.0 the new default may not be compatible with the old one. + - The specification's versioning section describes a patch as adding "new optional functionality," which contradicts the patch rule here. It needs correcting alongside this decision. + +### Questions + +**Clients** + +- Discovering supported versions + - How do I find out which versions a server supports? + - Does every route support the same versions? +- Requesting a specific version + - How do I ask for a version? + - What happens if I don't ask? + - How do I know which version I got? + - What errors can I get, and how do I recover? +- Retiring a version + - How will I hear that a version is retiring? + - How will I hear that the default is changing? + - What happens after a version is retired? + +**Implementers** + +- Discovering supported versions + - When must I publish discovery? + - What does listing a version promise? + - What goes in discovery while a change is pending? +- Requesting a specific version + - How do I resolve the requested version? + - Which errors do I return, and in what order do I check? + - Which headers must my responses carry? +- Retiring a version + - How do I change my default? + - How do I retire a version, server-wide or for one route? + +### Use cases + +- **An aggregator** pulls opportunities from many servers. Before it sends a request, it needs to know which versions each server and each route serves, so it can pick one it understands. +- **A vendor upgrading one route.** A grants platform adds the 0.5.0 form list while every other route stays on 0.4.0. It needs to say so truthfully without moving every route at once. +- **A client that never sends a version.** An existing integration written before negotiation existed has to keep getting the contract it already uses, whatever versions the server adds later. +- **A browser app on another origin** calls the API directly. It needs to send the version and read which version it got. +- **A long-running integration on an old version** needs warning before that version stops responding, and needs to know what to move to. +- **A host API that mounts CommonGrants routes** under its own versioned paths, such as `/api/v2/common-grants/...`, needs the two versions to stay independent. + +### Criteria + +- **Many versions is the easy standard:** serving several versions, or upgrading one route at a time, should cost a server as little as possible. +- **Existing clients keep working:** a client that has never sent a version keeps getting the contract it already uses. +- **Predictable before the request:** a client can tell whether a request will work before sending it. +- **One contract per response:** a response never mixes versions, and the client can tell which version it got. +- **Minimum mandatory surface:** new obligations fall only on servers whose behavior creates the need. +- **Conform by default:** reuse the existing envelopes, route status tags, route prefix, and IETF headers. +- **Stable resource identity:** a resource has one URL across versions, so stored links and cross-references don't depend on a version. +- **Change locality:** a release that changes some routes leaves the URLs of every other route untouched. +- **Works inside a host API:** CommonGrants routes can be mounted inside a host API that has its own paths and versioning. +- **Tooling fit:** expressible in TypeSpec and OpenAPI, usable from Swagger UI and curl, and checkable by `cg check`. +- **Cache- and browser-safe:** shared caches never return one version's response for another, and browser clients can read the version metadata. +- **Shareable URLs:** a URL pasted into a browser, bug report, or docs page reproduces the same version. +- **Implementation cost:** simple for adopters to route and validate in the frameworks the protocol supports. + +### Options considered + +| Question | Options | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| Where the version travels | **Request header**; path segment; query parameter; media type; header with a query-parameter fallback | +| Header names | **`CG-Version` and `CG-Version-Served`**; `CommonGrants-Version`; `Accept-Version`; `X-CG-Version`; one name for both | +| Version format | **Full 0.5.0, matched on major and minor**; full 0.5.0, matched exactly; patch always 0; major.minor 0.5; accept both | +| What supporting a version promises | API-wide list; **baseline plus per-route entries**; full per-route list | +| Discovery route status | Optional, SHOULD for multi-version servers; **optional, MUST for multi-version servers**; required | +| Version metadata on ordinary responses | **Served version only**; plus a required supported-versions header; plus an optional one | +| Served version in the response body | **Headers only**; headers plus a metadata block in the envelope | +| No version sent | **Pinned default per server**; latest; oldest; version required | +| Version error status | One status for every error; **400 or 406 by case**; 400/406 plus 410 for retired versions | +| Retiring a default | Reject requests without a version; move only to a compatible version; **move forward** | +| Announcing a default change | **`successor-version` link**; a CommonGrants link relation; Deprecation and Sunset redefined; only by retiring the old default | +| Removing a version from one route | No notice required; **the same process as the whole server** | + +Selected options are in bold. The [Evaluation](#evaluation) section compares them. + +## Evaluation + +### Side-by-side + +- โœ… Criterion met +- โŒ Criterion not met +- ๐ŸŸก Partially met or unsure + +Where the version travels: + +| Criteria | Header | Path | Query parameter | Media type | Header + query | +| ---------------------------------- | :----: | :--: | :-------------: | :--------: | :------------: | +| Stable resource identity | โœ… | โŒ | ๐ŸŸก | โœ… | ๐ŸŸก | +| Change locality | โœ… | โŒ | โœ… | โœ… | โœ… | +| Many versions is the easy standard | โœ… | โŒ | โœ… | โœ… | โœ… | +| Works inside a host API | โœ… | โŒ | โœ… | ๐ŸŸก | โœ… | +| Tooling fit | โœ… | โœ… | โœ… | ๐ŸŸก | ๐ŸŸก | +| Cache- and browser-safe | ๐ŸŸก | โœ… | ๐ŸŸก | โŒ | ๐ŸŸก | +| Shareable URLs | โŒ | โœ… | โœ… | โŒ | โœ… | +| Existing clients keep working | โœ… | ๐ŸŸก | โœ… | โœ… | โœ… | +| Implementation cost | โœ… | โœ… | โœ… | ๐ŸŸก | โŒ | + +What supporting a version promises: + +| Criteria | API-wide | Baseline plus entries | Full per-route | +| ---------------------------------- | :------: | :-------------------: | :------------: | +| Many versions is the easy standard | โŒ | โœ… | ๐ŸŸก | +| Predictable before the request | ๐ŸŸก | โœ… | โœ… | +| Minimum mandatory surface | โœ… | โœ… | โŒ | + +### Discovering supported versions + +#### What supporting a version promises + +##### Option 1: API-wide list โ€” Rejected + +:::note[Bottom line] +An API-wide list is best if: + +- we want the simplest possible discovery response +- but can compromise on servers upgrading one route at a time + ::: + +- **Pros** + - One list and one default answer every question. +- **Cons** + - A server that upgrades one route can't say so. It has to upgrade every route together, or serve the new version without advertising it. + - A route that exists only in a newer version can't be listed at all. + +##### Option 2: Baseline plus per-route entries โ€” Selected + +:::note[Bottom line] +A baseline plus per-route entries is best if: + +- we want servers to upgrade one route at a time and say so truthfully +- but can compromise on clients doing one lookup per route + ::: + +- **Pros** + - A server whose routes all match the baseline publishes the same thing it would under an API-wide list, so it pays nothing extra. + - The baseline stays a compliance claim, because every route a baseline version requires serves that version. +- **Cons** + - Clients check for a route's entry before using the baseline. + - A hand-maintained entry can go stale when the baseline moves. Generating discovery from the routes a server registers removes that risk. + +Describing the top-level list as a baseline matters even for servers with no entries. If it instead promised that every route serves every listed version, adding per-route entries later would change what an existing field means. + +##### Option 3: Full per-route list โ€” Rejected + +:::note[Bottom line] +A full per-route list is best if: + +- we want an exact inventory of every route and version +- but can compromise on every server listing every route and every client computing which versions its routes share + ::: + +- **Pros** + - The most precise option, and it doubles as an inventory of implemented routes. +- **Cons** + - Nothing answers which version the API speaks. + - Every server lists every route, even when they all match. + +#### Discovery route status + +##### Optional, MUST for multi-version servers โ€” Selected + +Clients get a guarantee where it matters, because per-route entries appear only in discovery. Servers that serve one version take on nothing and stay compliant. Route status tags can't express the condition, so it lives in the specification text while the route is tagged optional. + +##### Optional, SHOULD for multi-version servers โ€” Rejected + +A client can't count on discovery even from a server that serves several versions. + +##### Required โ€” Rejected + +The specification classifies adding a required route as a major change, and single-version servers gain nothing from it. Clients need a fallback for servers without discovery for years either way. + +#### Version metadata on ordinary responses + +##### Served version only โ€” Selected + +The useful prompt to upgrade is that the served version is going away, and `Deprecation` and `Sunset` already carry it. Discovery and unsupported-version errors carry the supported versions. + +##### Required supported-versions header โ€” Rejected + +Microsoft's ASP.NET API Versioning library does this with `api-supported-versions` and `api-deprecated-versions`, sent when a service turns on `ReportApiVersions`. It lets a long-running client notice new versions without re-reading discovery. But clients that never send a version, the ones that most need the prompt, won't read a new header either. It's a second source that must agree with discovery, and servers on different builds during a rolling deploy can return different lists. The library itself later added `Deprecation` and `Sunset` support because those headers can't say when a version goes away. Adding the header later is additive if clients ask for it. + +##### Optional supported-versions header โ€” Rejected + +A header clients can't count on doesn't give them a dependable prompt. + +### Requesting a specific version + +#### Where the version travels + +##### Option 1: Request header โ€” Selected + +:::note[Bottom line] +A request header is best if: + +- we want stable URLs for every resource, per-route versions, and one documented route with a version history +- but can compromise on shareable version-specific URLs and on setting a `Vary` header + ::: + +GitHub (`X-GitHub-Api-Version`), Stripe (`Stripe-Version`), and OpenStack (`OpenStack-API-Version`) all select the version with a request header. + +- **Pros** + - Resource URLs never change, so links stored in grant systems, bookmarks, and cross-references stay valid across versions. + - A host API keeps its own path scheme. CommonGrants routes mount under `/common-grants/` whatever the host does with versions. + - Per-route versions and per-route defaults work without a URL per combination. + - A server that serves one version needs very little code: it checks the header, rejects other major and minor versions, and reports what it serves. + - Declared once in the core library and present on every operation, so docs, `cg check`, and the SDKs all see it. +- **Cons** + - A URL alone doesn't reproduce a version: a resource link copied from a 0.5.0 request reopens in the default. Version-specific shareable links are an uncommon need for grant data, and the docs site's own `?version=` selector covers the sandbox case. + - Caches need `Vary: CG-Version`, and some CDNs need the header added to their cache key. + - Browser clients need CORS to allow and expose the headers. + - Not visible in default access logs without configuration. + +##### Option 2: Path segment โ€” Rejected + +:::note[Bottom line] +A path segment is best if: + +- we want the version visible in every URL, log line, and cache key with no setup +- but can compromise on a copy of every URL per version, stacked version segments inside host APIs, and moving every route at once on each release + ::: + +Kubernetes serves resources under a group and version, such as `/apis/apps/v1/deployments`, and our mock API uses this pattern today. + +- **Pros** + - Shareable, cacheable, and visible everywhere without configuration. + - The simplest thing to route in any framework. +- **Cons** + - Every resource gets a URL per version, so stored links go stale and cross-references between resources have to agree on a version. + - Inside a host API with its own path versioning, the URL carries two versions, such as `/api/v2/common-grants/v0.5/opportunities`. + - Per-route versions and per-route defaults can't be expressed, because a path is all one version. + - Every route moves on every release, and docs repeat every route per version. + +##### Option 3: Query parameter โ€” Rejected + +:::note[Bottom line] +A query parameter is best if: + +- we want the version visible in shareable URLs while paths stay stable +- but can compromise on a parameter declared on every operation, CDNs that ignore query strings by default, and a version error that looks like any other bad request + ::: + +Azure Resource Manager requires `api-version` on every request. + +- **Pros** + - Stable paths and shareable URLs at the same time. + - Easy to use from a browser address bar and in docs examples. +- **Cons** + - A version that isn't part of the resource's identity still ends up in its URL, so two links to one record differ. + - Strict servers reject unknown query parameters with a plain 400, which a client can't tell apart from a version error on servers that predate negotiation. + - Crowds query strings that already carry pagination, sorting, and filters, and collides with host APIs that use the same name. + - Every version error has to be a 400, because 406 is tied to request headers. + +##### Option 4: Media type โ€” Rejected + +:::note[Bottom line] +Media type negotiation is best if: + +- we want to follow HTTP content negotiation strictly +- but can compromise on tooling support, shareable URLs, and cache efficiency + ::: + +GitHub's legacy `application/vnd.github.v3+json` worked this way before GitHub replaced it with a dedicated header. + +- **Pros** + - Uses HTTP's own content negotiation, with no new header. +- **Cons** + - Touches every content type the protocol declares, including the `application/merge-patch+json` routes from [ADR 0026](https://commongrants.org/governance/adr/0026-org-profile-syncing/). + - Swagger UI and most client generators handle media type parameters poorly. + - `Vary: Accept` fragments caches far more than a single custom header does. + +##### Option 5: Header with a query-parameter fallback โ€” Rejected + +:::note[Bottom line] +Accepting both is best if: + +- we want shareable links in addition to stable paths +- but can compromise on two carriers to validate, document, and support in every SDK and template + ::: + +- **Pros** + - Shareable links without giving up stable paths. +- **Cons** + - Two carriers double the validation rules (which wins when both are present, and what a conflict means), the docs, the test matrix, and the SDK support for each. + - Caches would need to key on both. + - Shareable links are the only criterion it adds, and the docs site's own `?version=` selector serves that need better than a protocol-level carrier. + +#### Header names + +Each header follows the closest published standard or precedent: + +| Header | Direction | Purpose | Standard or precedent | Deviation and rationale | +| ----------------------------------------------------------------------- | --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `CG-Version` | Request | The version the client wants, such as `0.5.0` | Vendor-prefixed request header, as in `Stripe-Version`, `X-GitHub-Api-Version`, and `OpenStack-API-Version`. No `X-` prefix, per [RFC 6648](https://www.rfc-editor.org/rfc/rfc6648) | Short, pairs with `CG-Version-Served`, and avoids colliding with `Accept-Version`, which other APIs use for their own versions | +| `CG-Version-Served` | Response | The full version actually served, including by default | GitHub's `X-GitHub-Api-Version-Selected`; Shopify's `X-Shopify-API-Version`, which reflects the version used to fulfill the request; OpenStack echoes `OpenStack-API-Version` with the executed version | "Served" rather than GitHub's "Selected", because it also covers the default, where the client selected nothing | +| `Vary: CG-Version` | Response | Keys shared caches on `CG-Version` | [RFC 9110 ยง12.5.5](https://www.rfc-editor.org/rfc/rfc9110#section-12.5.5): an origin server SHOULD send `Vary` on a cacheable response that depends on a request header. OpenStack always sends `Vary: OpenStack-API-Version` | GitHub and Stripe omit their version header from `Vary`. CommonGrants requires it on cacheable responses, because the protocol can't know an implementer's caching setup and the header costs nothing | +| `Deprecation` | Response | The served version is deprecated | [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745), with a Structured Field Date value such as `@1796083200` | None. GitHub uses the same name with an HTTP-date value, the format from before the RFC was published. CommonGrants follows the RFC | +| `Sunset` | Response | When the served version stops responding | [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594), with an HTTP-date value. GitHub uses the same header and format | None. RFC 8594 says Sunset isn't appropriate for a version that's no longer preferred but still operational, so it isn't used for a default change | +| `Link` with `rel="deprecation"` and `rel="sunset"` | Response | Migration documentation | [RFC 8288](https://www.rfc-editor.org/rfc/rfc8288). Both relation types are IANA-registered, by RFC 9745 and RFC 8594 | None | +| `Link` with `rel="successor-version"` | Response | Announces a change of default on responses served by default | [RFC 5829](https://www.rfc-editor.org/rfc/rfc5829), IANA-registered: points to a resource containing the successor version | A registered relation instead of a CommonGrants relation URI, which RFC 8288 allows but no tooling recognizes. The header says a successor exists; the date lives in discovery | +| `Link` with `rel="version-history"` | Response | Points to the discovery route | RFC 5829, IANA-registered: points to a resource containing the version history | None. Sent alongside `Deprecation` and `successor-version`, so a client can find what to move to without reading docs | +| CORS `Access-Control-Allow-Headers` and `Access-Control-Expose-Headers` | Response | Lets browsers send `CG-Version` and read the version metadata | The [Fetch Standard](https://fetch.spec.whatwg.org/#cors-safelisted-request-header) allows only a few request headers without a preflight, so `CG-Version` needs allow-listing | None | + +##### `CG-Version` and `CG-Version-Served` โ€” Selected + +Short, paired, and `cg` is already the CLI's name. The specification text spells out what CG means. A distinct served-version name says what it means and can't be mistaken for an echo of the request. + +##### `CommonGrants-Version` โ€” Rejected + +Clearer to a reader who has never seen the protocol, but long on every request, and the pair `CommonGrants-Version-Served` is longer still. + +##### `Accept-Version` โ€” Rejected + +Reads as a standard header but isn't one, and would collide with other APIs that use the same name for their own versions. + +##### `X-CG-Version` โ€” Rejected + +The `X-` convention is deprecated by RFC 6648. GitHub still uses one, but we have no legacy header to stay compatible with. + +##### One name for the request and the served version โ€” Rejected + +OpenStack's approach. It gives clients one name to learn, but requested and served values share a name in logs and captures. + +#### Version format + +##### Full 0.5.0, matched on major and minor โ€” Selected + +Clients and servers use the same full version string as the protocol's version list, the published OpenAPI documents, and the CLI, and the server reports exactly what it hosts. Because a patch never changes the contract, matching on major and minor means a patch release never breaks a client or forces a server to list extra versions. Caches keep separate entries for requests that differ only in the patch number, which costs some cache efficiency but never returns the wrong contract. + +##### Full 0.5.0, matched exactly โ€” Rejected + +The first time the protocol publishes a patch, a server hosting 0.5.1 rejects clients sending 0.5.0 for an identical contract, or has to list every patch it could serve. + +##### Patch always 0 โ€” Rejected + +Keeps exact matching simple, but leaves the third number permanently meaningless and stops a server from reporting the patch it actually hosts. + +##### Major.minor 0.5 โ€” Rejected + +Adds a second format beside the one the protocol's version list, OpenAPI documents, and CLI already use. + +##### Accept both โ€” Rejected + +Two formats for one contract double the test matrix and the parsing rules. + +#### Served version in the response body + +##### Headers only โ€” Selected + +`CG-Version-Served` already confirms the version, and the envelopes stay exactly as they are in every version, which keeps the 0.6.0 schemas a pure addition. + +##### Headers plus a metadata block in the envelope โ€” Deferred + +A client that never inspects headers would still see the version it got. But it duplicates the header, changes every envelope schema, and the SDKs read headers anyway. Worth revisiting if we find clients that can't read response headers, which exposing them through CORS is meant to prevent. + +#### No version sent + +##### Pinned default per server โ€” Selected + +The only option that keeps existing clients on the contract they use, whatever versions the server adds later. + +##### Latest โ€” Rejected + +A client that sends no version gets new and possibly breaking changes the day the server adds a version. + +##### Oldest โ€” Rejected + +A server that adds an older version for compatibility moves its existing clients backward. + +##### Version required โ€” Rejected + +Breaks every client that exists today. + +#### Version error status + +##### 400 or 406 by case โ€” Selected + +406 is the closest fit for an unavailable version, not an exact match. RFC 9110 defines 406 against the proactive negotiation header fields in the request, and the fields it defines for that are the `Accept` family, which `CG-Version` isn't. OpenStack returns 406 for an unsupported `OpenStack-API-Version` the same way. 400 covers malformed or conflicting requests. On writes, 406 describes the response even though the version also governs the request body, and `code` carries the distinction either way. + +##### One status for every version error โ€” Rejected + +Generic monitoring can't separate a broken request from an unavailable version. + +##### 400/406 plus 410 for retired versions โ€” Rejected + +GitHub returns 410 for retired versions, but with a header carrier, 410 says the URL is gone, which is false when only one version is retired. It can also be cached by default, and it adds a third status for clients. + +### Retiring a version + +#### Retiring a default + +##### Move forward โ€” Selected + +Clients that send no version are never forced to start sending one. When serving many versions is the norm, retiring a default is rare and announced well in advance. The cost: before 1.0, a client that ignored the notice can get changed fields in a successful response. GitHub moves its default forward the same way. + +##### Reject requests without a version โ€” Rejected + +A loud, easy-to-diagnose failure, but every client that sends no version must change, even when the next version is compatible. + +##### Move only to a compatible version, otherwise reject โ€” Rejected + +Before 1.0 a minor version may break compatibility, so this behaves like rejecting while adding a way to declare compatibility. + +#### Announcing a default change + +##### `successor-version` link โ€” Selected + +A server can move clients that send no version forward without dropping a version other clients still request, which keeps serving many versions cheap. `Deprecation` and `Sunset` keep their standard meaning, so a client, proxy, or monitoring tool that sees them can trust they describe the version being served. Clients that request the old version explicitly see nothing, because nothing changes for them. The relation is IANA-registered, so generic tooling can recognize it. The cost is that the header alone says only that a successor exists, not that the default is moving or when. The date lives in discovery. + +##### A CommonGrants link relation โ€” Rejected + +Would say "the default is changing" precisely. But a relation that isn't registered has to be a URI the protocol controls, and no generic tooling recognizes it. + +##### Deprecation and Sunset redefined on responses served by default โ€” Rejected + +Reuses headers that existing tooling already watches. But their standard meaning is that the resource itself is being deprecated or will stop responding, and the Sunset RFC says it isn't meant for a version that's no longer preferred but still operational. Tooling that doesn't know the redefinition reports a deprecated endpoint. + +##### Only by retiring the old default โ€” Rejected + +Keeps the headers' standard meaning with no new relation, but a server that wants a newer default has to drop the old version to get it, which works against serving many versions. + +#### Removing a version from one route + +##### Same process as the whole server โ€” Selected + +Clients using that route get the same warning they would for a server-wide retirement, and there is one lifecycle for servers and tooling to implement. It adds no cost to serving a version, only notice before dropping one. Experimental routes are exempt, matching their existing status ([ADR 0019](https://commongrants.org/governance/adr/0019-api-route-status/)). + +##### No notice required โ€” Rejected + +Less work for the server, but clients of that route break without warning, and clients that send no version can have that route's default switched silently. + +### Existing patterns + +| Question | GitHub | Stripe | Kubernetes | This decision | +| --------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------ | ---------------------------------------------------------------------------------- | +| Selecting a version | `X-GitHub-Api-Version` request header, with a release date | `Stripe-Version` request header, with a dated release | A path segment per API group, such as `/apis/batch/v1` | `CG-Version` request header | +| No version sent | A fixed default | The account's default, kept until the account upgrades | Doesn't arise: every path names its version | A pinned default per server | +| Served version on responses | `X-GitHub-Api-Version-Selected` header | Not documented | `apiVersion` field in every object | `CG-Version-Served` header | +| Supported versions | `GET /versions` | The changelog | `/api` and `/apis` list each group's versions | `GET /common-grants/versions` | +| Deprecation signal | `Deprecation` and `Sunset` headers | Not documented | `Warning` header | `Deprecation`, `Sunset`, and `Link`, plus `successor-version` for a default change | +| After retirement | 410 Gone; the default moves to the next oldest supported version | Not documented | The version stops being served | `version.retired`, and the default moves forward | +| Scope of a version | The whole API | The whole account | Each API group | A baseline plus per-route entries | + +Sources: [GitHub API versions](https://docs.github.com/en/rest/about-the-rest-api/api-versions), [GitHub versions endpoint](https://docs.github.com/en/rest/meta/meta#get-all-api-versions), [Stripe API versioning](https://docs.stripe.com/api-versions), [Kubernetes API versioning](https://kubernetes.io/docs/reference/using-api/), [Kubernetes deprecation policy](https://kubernetes.io/docs/reference/using-api/deprecation-policy/). + +### Protocol conformance + +| Aspect | Convention | Conforms / Diverges | +| ---------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Route prefix | Protocol routes under `/common-grants/` | Conforms: `/common-grants/versions`. No version segment is added to any path | +| Route status | Tags required, optional, experimental ([ADR 0019](https://commongrants.org/governance/adr/0019-api-route-status/)) | Diverges (scoped exception): discovery is tagged optional, and the requirement for multi-version servers lives in the specification text, because a tag can't state a condition | +| Identifiers | `{resource}Id` path parameters; versions as `0.5.0` strings | Conforms: route keys reuse the protocol's path templates, and versions use the existing format | +| Success shape | Success envelope with the payload under `data` | Conforms | +| Error shape | Error envelope `{status, message, errors}` | Conforms: version details are entries in `errors` | +| Field names | camelCase | Conforms. Map keys (version strings and route keys) are values, not field names | +| Headers | `Location` on accepted responses | New pattern: `CG-Version` and `CG-Version-Served` are the first protocol-defined custom headers. Uses the IETF `Deprecation`, `Sunset`, and `Link` headers instead of custom ones | +| Status codes | Operations declare 401, 403, and 404 | New: 400 and 406 for version errors. 406 is new to the protocol | +| Query parameters | camelCase, such as `pageSize` | Not applicable: no query parameter is added | +| Versioning | `@added` on new fields and routes | Conforms: the headers, errors, and discovery route are declared from 0.6.0. A negotiating server applies them whatever version it serves | +| Custom routes | Outside `/common-grants/` ([ADR 0014](https://commongrants.org/governance/adr/0014-custom-routes/)) | Conforms: the header has no meaning on custom routes | +| Pagination | Page-based ([ADR 0011](https://commongrants.org/governance/adr/0011-pagination/)) | Not applicable: discovery isn't paginated | +| Mock API | Versioned by path ([ADR 0028](https://commongrants.org/governance/adr/0028-mock-api-hosting/)) | Diverges: this decision supersedes ADR 0028's path prefix, and the mock moves to the header. The rest of ADR 0028 stands | + +## Specification + +### Scenarios + +These scenarios show the decision end to end. The sections that follow answer the client and implementer questions for each area. + +| Scenario | Request | Result | +| ---------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | +| Request a served version | `CG-Version: 0.5.0` | 200 in 0.5.0. `CG-Version-Served` reports the version, which can differ in the patch number only | +| No version sent | No header | 200 in the server's pinned default. `CG-Version-Served` names it | +| Version the server doesn't serve | `CG-Version: 0.3.0` | 406 `version.unsupported`, scope `deployment`, with the supported versions and the discovery URL | +| Version this route doesn't serve | `CG-Version: 0.4.0` on a route that serves only 0.5.0 | 406 `version.unsupported`, scope `operation`. The route's entry in discovery predicts this | +| Server that serves only one version | `CG-Version: 0.5.0` to a server that serves only 0.6.0 | 406 `version.unsupported`, scope `deployment`. The server doesn't substitute 0.6.0 | +| Malformed or repeated value | `CG-Version: banana`, or two values | 400 `version.malformed` or `version.conflict` | +| Version in the URL instead of the header | `?cg-version=0.5.0` with no header | 200 in the default. The URL isn't a selector, and `CG-Version-Served` shows what the client got | +| Body validated in the requested version | A 0.4.0 search with a filter that exists only in 0.5.0 | 400 validation error naming the filter, with `CG-Version-Served: 0.4.0` | +| Server that predates negotiation | `CG-Version: 0.5.0` to a server that ignores the header | 200 with no `CG-Version-Served`. The response is unconfirmed and must not be read as 0.5.0 | +| Host API with its own path versioning | `GET /api/v2/common-grants/opportunities` with `CG-Version: 0.5.0` | 200 in 0.5.0. The host's v2 and the protocol version are independent | +| Custom route | `CG-Version: 0.5.0` on a route outside `/common-grants/` | The header is ignored. No `CG-Version-Served` and no version errors | +| Shared cache in front of the API | Two clients request 0.4.0 and 0.5.0 for the same URL | Each gets its own version, because `Vary: CG-Version` keeps the cached responses apart | +| Default is changing | No header, while the default moves from 0.4.0 to 0.5.0 | 200 in 0.4.0 with the `successor-version` link, and no `Deprecation` or `Sunset` | +| Version is retiring | `CG-Version: 0.3.0` before its sunset date | 200 in 0.3.0 with `Deprecation`, `Sunset`, and `Link` headers | +| Version has been retired | `CG-Version: 0.3.0` after its sunset date | 406 `version.retired` with the sunset date, the supported versions, and the discovery URL. Later, `version.unsupported` | + +### Discovering supported versions + +#### Clients + +##### How do I find out which versions a server supports? + +Call `GET /common-grants/versions`, relative to the API's base URL. You don't need to send `CG-Version`, and the route never returns a version error. Here's a server whose baseline is 0.4.0, which also serves form detail in 0.5.0 and serves its form list only in 0.5.0: + +```json +{ + "status": 200, + "message": "Success", + "data": { + "versions": ["0.4.0"], + "defaultVersion": "0.4.0", + "operations": { + "GET /common-grants/forms": { + "versions": ["0.5.0"], + "defaultVersion": "0.5.0" + }, + "GET /common-grants/forms/{formId}": { + "versions": ["0.4.0", "0.5.0"], + "defaultVersion": "0.4.0" + } + } + } +} +``` + +Version values are strings in the `0.5.0` format, not a closed list, so accept versions published after your client was built. Ignore fields you don't recognize. + +If discovery returns 404, treat the server as serving one version it doesn't advertise. If responses also lack `CG-Version-Served`, that version is unknown and every response is unconfirmed. + +##### Does every route support the same versions? + +Not always. `versions` and `defaultVersion` are the baseline. A route listed under `operations` uses its own entry instead. A route is identified by its HTTP method and its path as published in the protocol. Path parameter names are ignored when matching, so `{id}` and `{formId}` in the same position identify the same route. + +#### Implementers + +##### When must I publish discovery? + +The route is optional. A server that serves more than one version MUST implement it. It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. It ignores `CG-Version`, and its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. A server whose routes all serve the baseline omits `operations`. + +##### What does listing a version promise? + +- A route can serve a version only if that version of the protocol defines the route. +- Every route a baseline version requires serves that version, so the baseline is a compliance claim: the server is compliant with every version in it. +- Supporting a version doesn't mean implementing that version's optional or experimental routes. +- A default is always one of the versions it applies to. +- One request is served in one version. The whole response follows that version's schemas, including nested objects. How a server represents data that an older version can't express is outside this decision. +- Only protocol routes under `/common-grants/` are covered. A plugin's package version is never a CommonGrants version ([ADR 0022](https://commongrants.org/governance/adr/0022-plugin-framework/)). + +##### What goes in discovery while a change is pending? + +Optional lifecycle fields, included only while a change is pending: at the top level for the baseline, or in a route's entry for that route only. Dates use RFC 3339. Here's the `data` payload of a server moving its default to 0.5.0 and retiring 0.3.0: + +```json +{ + "versions": ["0.3.0", "0.4.0", "0.5.0"], + "defaultVersion": "0.4.0", + "upcomingDefault": { + "version": "0.5.0", + "date": "2027-03-01T00:00:00Z" + }, + "deprecated": { + "0.3.0": { + "deprecation": "2026-12-01T00:00:00Z", + "sunset": "2027-06-01T00:00:00Z" + } + } +} +``` + +Fields are only ever added. + +### Requesting a specific version + +#### Clients + +##### How do I ask for a version? + +Send the full version in the `CG-Version` request header: + +```http +GET /common-grants/opportunities/123 HTTP/1.1 +CG-Version: 0.5.0 + +HTTP/1.1 200 OK +CG-Version-Served: 0.5.1 +Vary: CG-Version +``` + +Send one value per request. The value is three dot-separated numbers with no leading zeros. A `v` prefix, a short form such as `0.5`, ranges, and aliases are malformed. The header only means something on routes under `/common-grants/`. A version in the path or query string is never read as a selector. + +##### What happens if I don't ask? + +You're served in the server's default: the baseline default, or the route's own default when the route has an entry. The default doesn't change when the server adds versions. It changes only after an announced default change (see [Retiring a version](#retiring-a-version-2)). If you need a fixed contract, send a version. + +##### How do I know which version I got? + +Read `CG-Version-Served`. It reports the full version served, so it can differ from your request in the patch number only. + +- A successful response without it is unconfirmed: the server may predate negotiation, or something in between dropped your header. Don't read it as the version you asked for. +- A served version whose major or minor number differs from the one you asked for wasn't served as requested. Don't treat it as your version. + +##### What errors can I get, and how do I recover? + +| Case | `code` | Status | +| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------ | +| Malformed version, such as `banana` or `0.5` | `version.malformed` | 400 | +| Version this server doesn't serve | `version.unsupported`, scope `deployment` | 406 | +| Version this route doesn't serve | `version.unsupported`, scope `operation` | 406 | +| Version retired from this server or this route | `version.retired`, scope `deployment` or `operation` | 406 | +| More than one version value, as two header lines or one comma-separated line, even the same value twice | `version.conflict` | 400 | + +Details are entries in the existing error envelope. `supported` and `defaultVersion` always describe the route you called, so retry with a listed version: + +```json +{ + "status": 406, + "message": "The requested CommonGrants version is not available for this route", + "errors": [ + { + "field": "CG-Version", + "code": "version.unsupported", + "message": "Version 0.4.0 is not served by GET /common-grants/forms. Supported versions: 0.5.0", + "requested": "0.4.0", + "supported": ["0.5.0"], + "scope": "operation", + "defaultVersion": "0.5.0", + "discovery": "https://grants.example.org/common-grants/versions" + } + ] +} +``` + +`version.retired` also carries `sunset`, in RFC 3339. `version.conflict` omits `requested`, and its message names the values received. `code` values are stable; branch on them. + +#### Implementers + +##### How do I resolve the requested version? + +- Read `CG-Version` only on protocol routes under `/common-grants/`, never on custom routes or discovery. The name is case-insensitive. A proxy may fold two header lines into one comma-separated line ([RFC 9110 ยง5.3](https://www.rfc-editor.org/rfc/rfc9110#section-5.3)), so treat two lines or a comma in the value as more than one value, and check for that before the format. Trim surrounding whitespace, then match the format exactly. +- Match on major and minor. Host one patch of each major and minor you serve, and report that full version everywhere you list or report it. A request for any patch of a served major and minor is served in the version you host. +- Never serve a different major or minor version than the one requested, even if you serve only one version. +- Never read the version from the URL path, the query string, `Accept`, or a vendor media type, and never fall back to one. A host API that versions its own routes by path keeps doing so; its path version and `CG-Version` are independent. +- A protocol patch never changes schemas, validation, required routes, or status codes. A fix that changes any of these is published as a new minor or major version. + +##### Which errors do I return, and in what order do I check? + +Match the route, then resolve the version, then validate the request body against that version's schemas, all before any side effect. A route you don't implement gets an ordinary 404. Where authentication runs is up to you. A rejected write changes nothing, and is never retried under another version. + +A version problem never returns 404 or 410: both can be cached by default, and clients read them as a missing route or record. How long you answer `version.retired` rather than `version.unsupported` after a sunset is up to you, since both carry the supported versions. + +##### Which headers must my responses carry? + +- Every response produced after a version is selected MUST carry `CG-Version-Served`, whatever version you serve, including responses served by default and errors such as a missing record or a body validation error. The header is declared in the 0.6.0 documents, but a negotiating server sends it on 0.5.0 and earlier responses too. Responses to 401 and 403 MAY omit it, because authentication can run before selection. Version errors MUST NOT carry it. +- Every cacheable response that depends on `CG-Version` MUST carry `Vary: CG-Version`, including responses served by default. +- Cross-origin servers MUST allow `CG-Version` in `Access-Control-Allow-Headers`, and MUST expose `CG-Version-Served`, `Deprecation`, `Sunset`, and `Link` in `Access-Control-Expose-Headers`. +- Ordinary responses MUST NOT carry a supported-versions header. +- Header names use hyphens and no `X-` prefix. + +### Retiring a version + +#### Clients + +##### How will I hear that a version is retiring? + +Responses served in that version carry `Deprecation`, then `Sunset` once a date is set, with `Link` headers to migration documentation and to discovery. These headers always describe the version you were served, and discovery lists the version under `deprecated` with its dates: + +```http +GET /common-grants/opportunities/123 HTTP/1.1 +CG-Version: 0.3.0 + +HTTP/1.1 200 OK +CG-Version-Served: 0.3.0 +Vary: CG-Version +Deprecation: @1796083200 +Sunset: Tue, 01 Jun 2027 00:00:00 GMT +Link: ; rel="deprecation" +Link: ; rel="sunset" +Link: ; rel="version-history" +``` + +`Deprecation` uses the `@` form from RFC 9745, `Sunset` uses HTTP-date, and discovery uses RFC 3339. + +##### How will I hear that the default is changing? + +If you send no version, responses from routes whose default is changing carry a `successor-version` link, and discovery shows `upcomingDefault` with the date. They carry no `Deprecation` or `Sunset` unless the version itself is retiring. If you send a version, nothing changes for you. + +```http +GET /common-grants/opportunities/123 HTTP/1.1 + +HTTP/1.1 200 OK +CG-Version-Served: 0.4.0 +Vary: CG-Version +Link: ; rel="successor-version" +Link: ; rel="version-history" +``` + +##### What happens after a version is retired? + +Requests for any patch of that major and minor get 406 `version.retired`, with the sunset date and the supported versions, for a period the server chooses. After that, the server may answer `version.unsupported` instead, so handle both the same way: retry with a version from `supported`. If it was your default, the default has already moved to the next newer version. + +#### Implementers + +##### How do I change my default? + +You can change a default whether or not you keep serving the old one. Announce it first: + +- On responses served by default from the affected routes, send `Link` with `rel="successor-version"` pointing to documentation for the new default, and `Link` with `rel="version-history"` pointing to discovery. +- Show `upcomingDefault` with the date in discovery: at the top level for the baseline default, which also covers route entries whose default follows the baseline, or in a route's entry for that route's own default. +- Don't send `Deprecation` or `Sunset` for a default change. + +At the announced date, the default moves to the next newer version it applies to. + +##### How do I retire a version, server-wide or for one route? + +The same way in both cases: + +- Send `Deprecation`, and `Sunset` once a date is set, with `Link` headers to migration documentation (`rel="deprecation"` and `rel="sunset"`) and to discovery (`rel="version-history"`), on every response served in that version on the affected routes. +- List the version under `deprecated` in discovery: at the top level when it's leaving the whole server, or in the route's entry when it's leaving one route. +- After the sunset, answer requests for it with `version.retired`. +- If the version is a default, move that default forward no later than the sunset, announcing it as above. Responses served by default then carry both the retirement headers and the `successor-version` link. You can't retire a default unless you serve a newer version for it to move to. +- A required route can't drop a baseline version that requires it, so retiring that version from the route means retiring it from the baseline. +- Experimental routes may drop a version without notice. From d2489be8bddc56f66aff6cabe700d4bd11bb0241 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Mon, 9 Nov 2026 07:56:08 -0800 Subject: [PATCH 02/20] feat(core): add the versions discovery route Adds GET /common-grants/versions to the 0.6.0 base API, tagged optional, with the VersionDiscovery, OperationVersions, UpcomingDefault and VersionRetirement models and a protocolVersion type. The route lets a server publish its default version, the versions every route serves, per-route exceptions, an upcoming default and deprecated versions, per the API version negotiation ADR draft (#1159, #1372). Versions.v0_6 and Types.protocolVersion are stubs owned by #1386 and are dropped when that PR lands. The 0.1.0 through 0.5.0 OpenAPI documents are unchanged. Refs #1387 --- lib/core/lib/api.tsp | 20 +++ lib/core/lib/core/models/index.tsp | 1 + .../lib/core/models/version-discovery.tsp | 132 ++++++++++++++++++ lib/core/lib/core/routes/index.tsp | 1 + .../lib/core/routes/version-discovery.tsp | 49 +++++++ .../schemas/yaml/OperationVersions.yaml | 30 ++++ .../public/schemas/yaml/UpcomingDefault.yaml | 17 +++ .../public/schemas/yaml/VersionDiscovery.yaml | 75 ++++++++++ .../schemas/yaml/VersionRetirement.yaml | 17 +++ 9 files changed, 342 insertions(+) create mode 100644 lib/core/lib/core/models/version-discovery.tsp create mode 100644 lib/core/lib/core/routes/version-discovery.tsp create mode 100644 website/public/schemas/yaml/OperationVersions.yaml create mode 100644 website/public/schemas/yaml/UpcomingDefault.yaml create mode 100644 website/public/schemas/yaml/VersionDiscovery.yaml create mode 100644 website/public/schemas/yaml/VersionRetirement.yaml diff --git a/lib/core/lib/api.tsp b/lib/core/lib/api.tsp index 55d868182..d8626375d 100644 --- a/lib/core/lib/api.tsp +++ b/lib/core/lib/api.tsp @@ -30,6 +30,12 @@ using Versioning; description: "Endpoints that MUST be implemented by all CommonGrants APIs", } ) +@tagMetadata( + "Versions", + #{ + description: "Endpoints related to discovering the protocol versions an API serves", + } +) @tagMetadata("Forms", #{ description: "Endpoints related to forms" }) @tagMetadata("Awards", #{ description: "Endpoints related to grant awards" }) @tagMetadata( @@ -246,3 +252,17 @@ namespace Forms { @added(Versions.v0_2) op read is Router.read; } + +// ######################################################### +// Versions +// ######################################################### + +@tag("Versions") +@route("/versions") +namespace ProtocolVersions { + alias Router = Routes.ProtocolVersions; + + @added(Versions.v0_6) + @tag("optional") + op read is Router.read; +} diff --git a/lib/core/lib/core/models/index.tsp b/lib/core/lib/core/models/index.tsp index 028834a10..60e383cbe 100644 --- a/lib/core/lib/core/models/index.tsp +++ b/lib/core/lib/core/models/index.tsp @@ -15,6 +15,7 @@ import "./form.tsp"; import "./form-response.tsp"; import "./mapping.tsp"; import "./applicant-type.tsp"; +import "./version-discovery.tsp"; using TypeSpec.JsonSchema; diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp new file mode 100644 index 000000000..381f95b1e --- /dev/null +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -0,0 +1,132 @@ +import "../types.tsp"; + +namespace CommonGrants.Models; + +// ######################################################### +// UpcomingDefault +// ######################################################### + +/** A scheduled change to the version a server serves by default */ +@Versioning.added(CommonGrants.Versions.v0_6) +model UpcomingDefault { + /** The version that will become the default */ + version: Types.protocolVersion; + + /** When the new default takes effect */ + date: utcDateTime; +} + +// ######################################################### +// VersionRetirement +// ######################################################### + +/** The retirement schedule for a deprecated version */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionRetirement { + /** When the version was or will be deprecated */ + deprecation: utcDateTime; + + /** When the server will stop serving the version, if scheduled */ + sunset?: utcDateTime; +} + +// ######################################################### +// OperationVersions +// ######################################################### + +/** The versions a single route serves, when they differ from the API-wide values */ +@Versioning.added(CommonGrants.Versions.v0_6) +model OperationVersions { + /** The versions this route serves */ + versions: Types.protocolVersion[]; + + /** The version this route serves when a request doesn't name one */ + defaultVersion: Types.protocolVersion; + + /** A scheduled change to this route's default version, if any */ + upcomingDefault?: UpcomingDefault; + + /** Deprecated versions of this route, keyed by version, with their retirement schedule */ + deprecated?: Record; +} + +// ######################################################### +// VersionDiscovery +// ######################################################### + +/** The protocol versions an API serves + * + * The top-level fields describe every route. Routes that differ from them + * have an entry in `operations`. New fields are only ever added to this + * model; clients ignore fields they don't recognize. + */ +@example( + Examples.VersionDiscovery.routeEntries, + #{ title: "Baseline with route entries" } +) +@example( + Examples.VersionDiscovery.lifecycle, + #{ title: "Upcoming default and deprecated version" } +) +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionDiscovery { + /** The versions every route serves */ + versions: Types.protocolVersion[]; + + /** The version every route serves when a request doesn't name one */ + defaultVersion: Types.protocolVersion; + + /** A scheduled change to the API-wide default version, if any */ + upcomingDefault?: UpcomingDefault; + + /** Deprecated versions, keyed by version, with their retirement schedule */ + deprecated?: Record; + + /** Routes whose versions differ from the API-wide values + * + * Each key is the HTTP method and the route's published path, separated + * by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + * names are ignored when matching a key to a route. Omitted when every + * route serves the API-wide values. + */ + operations?: Record; +} + +// ######################################################### +// Examples +// ######################################################### + +/** Examples of version discovery responses */ +namespace Examples.VersionDiscovery { + /** A 0.4.0 baseline with routes that serve other versions */ + const routeEntries = #{ + versions: #["0.4.0"], + defaultVersion: "0.4.0", + operations: #{ + `GET /common-grants/forms`: #{ + versions: #["0.5.0"], + defaultVersion: "0.5.0", + }, + `GET /common-grants/forms/{formId}`: #{ + versions: #["0.4.0", "0.5.0"], + defaultVersion: "0.4.0", + }, + }, + }; + + /** A scheduled default change and a deprecated version */ + const lifecycle = #{ + versions: #["0.3.0", "0.4.0", "0.5.0"], + defaultVersion: "0.4.0", + upcomingDefault: #{ + version: "0.5.0", + date: utcDateTime.fromISO("2027-03-01T00:00:00Z"), + }, + deprecated: #{ + `0.3.0`: #{ + deprecation: utcDateTime.fromISO("2026-12-01T00:00:00Z"), + sunset: utcDateTime.fromISO("2027-06-01T00:00:00Z"), + }, + }, + }; +} diff --git a/lib/core/lib/core/routes/index.tsp b/lib/core/lib/core/routes/index.tsp index 8f4e4f8f7..bdcba2661 100644 --- a/lib/core/lib/core/routes/index.tsp +++ b/lib/core/lib/core/routes/index.tsp @@ -9,6 +9,7 @@ import "./applications.tsp"; import "./form-responses.tsp"; import "./forms.tsp"; import "./competitions.tsp"; +import "./version-discovery.tsp"; /** A series of routing interfaces for CommonGrants API endpoints * diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp new file mode 100644 index 000000000..dc01c40d3 --- /dev/null +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -0,0 +1,49 @@ +import "../models/index.tsp"; +import "../responses/index.tsp"; + +// Define the top-level namespace for CommonGrants routes +namespace CommonGrants.Routes; + +// Expose the contents of the Http and Rest namespaces +// these include the decorators @route, @get, etc. +using TypeSpec.Http; +using TypeSpec.Versioning; + +/** A re-usable interface for the versions discovery router + * + * Unlike the other routers, `read` is deliberately not templated: adopters + * don't extend the discovery response. Routes that differ from the API-wide + * versions are described in the response's `operations` field instead. + * + * @example Declaring the versions discovery route: + * ```typespec + * using TypeSpec.Http; + * + * @tag("Versions") + * @route("/versions") + * namespace ProtocolVersions { + * alias Router = Routes.ProtocolVersions; + * + * op read is Router.read; + * } + * ``` + */ +@added(CommonGrants.Versions.v0_6) +interface ProtocolVersions { + // ############################### + // List supported versions + // ############################### + + /** `GET /versions` List the protocol versions this API serves */ + @summary("List supported versions") + @doc(""" + List the protocol versions this API serves, its default version, and any routes whose versions differ. + + This route is optional, but a server that serves more than one protocol version MUST implement it. + It ignores the `CG-Version` request header, because clients call it before they know which version to request. + It SHOULD be readable without authentication. + Fields are only ever added to the response; clients ignore fields they don't recognize. + """) + @get + read(): Responses.OkT; +} diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml new file mode 100644 index 000000000..c4c6ecae8 --- /dev/null +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -0,0 +1,30 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: OperationVersions.yaml +type: object +properties: + versions: + type: array + items: + $ref: protocolVersion.yaml + description: The versions this route serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version this route serves when a request doesn't name one + upcomingDefault: + $ref: UpcomingDefault.yaml + description: A scheduled change to this route's default version, if any + deprecated: + $ref: "#/$defs/RecordVersionRetirement" + description: Deprecated versions of this route, keyed by version, with their retirement schedule +required: + - versions + - defaultVersion +unevaluatedProperties: + not: {} +description: The versions a single route serves, when they differ from the API-wide values +$defs: + RecordVersionRetirement: + type: object + properties: {} + unevaluatedProperties: + $ref: VersionRetirement.yaml diff --git a/website/public/schemas/yaml/UpcomingDefault.yaml b/website/public/schemas/yaml/UpcomingDefault.yaml new file mode 100644 index 000000000..355fcbb32 --- /dev/null +++ b/website/public/schemas/yaml/UpcomingDefault.yaml @@ -0,0 +1,17 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: UpcomingDefault.yaml +type: object +properties: + version: + $ref: protocolVersion.yaml + description: The version that will become the default + date: + type: string + format: date-time + description: When the new default takes effect +required: + - version + - date +unevaluatedProperties: + not: {} +description: A scheduled change to the version a server serves by default diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml new file mode 100644 index 000000000..1c2ad16d1 --- /dev/null +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -0,0 +1,75 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionDiscovery.yaml +type: object +properties: + versions: + type: array + items: + $ref: protocolVersion.yaml + description: The versions every route serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version every route serves when a request doesn't name one + upcomingDefault: + $ref: UpcomingDefault.yaml + description: A scheduled change to the API-wide default version, if any + deprecated: + $ref: "#/$defs/RecordVersionRetirement" + description: Deprecated versions, keyed by version, with their retirement schedule + operations: + $ref: "#/$defs/RecordOperationVersions" + description: |- + Routes whose versions differ from the API-wide values + + Each key is the HTTP method and the route's published path, separated + by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + names are ignored when matching a key to a route. Omitted when every + route serves the API-wide values. +required: + - versions + - defaultVersion +unevaluatedProperties: + not: {} +examples: + - versions: + - 0.3.0 + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 + upcomingDefault: + version: 0.5.0 + date: 2027-03-01T00:00:00Z + deprecated: + 0.3.0: + deprecation: 2026-12-01T00:00:00Z + sunset: 2027-06-01T00:00:00Z + - versions: + - 0.4.0 + defaultVersion: 0.4.0 + operations: + GET /common-grants/forms: + versions: + - 0.5.0 + defaultVersion: 0.5.0 + GET /common-grants/forms/{formId}: + versions: + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 +description: |- + The protocol versions an API serves + + The top-level fields describe every route. Routes that differ from them + have an entry in `operations`. New fields are only ever added to this + model; clients ignore fields they don't recognize. +$defs: + RecordVersionRetirement: + type: object + properties: {} + unevaluatedProperties: + $ref: VersionRetirement.yaml + RecordOperationVersions: + type: object + properties: {} + unevaluatedProperties: + $ref: OperationVersions.yaml diff --git a/website/public/schemas/yaml/VersionRetirement.yaml b/website/public/schemas/yaml/VersionRetirement.yaml new file mode 100644 index 000000000..bd0df99de --- /dev/null +++ b/website/public/schemas/yaml/VersionRetirement.yaml @@ -0,0 +1,17 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionRetirement.yaml +type: object +properties: + deprecation: + type: string + format: date-time + description: When the version was or will be deprecated + sunset: + type: string + format: date-time + description: When the server will stop serving the version, if scheduled +required: + - deprecation +unevaluatedProperties: + not: {} +description: The retirement schedule for a deprecated version From e81958aea3590c0fd1a0d785972105dec960b7bc Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Mon, 9 Nov 2026 08:15:10 -0800 Subject: [PATCH 03/20] feat(core): keep the discovery models open to new fields Discovery sits outside version selection, so its models tolerate fields they don't know instead of being versioned per document, as the route description promises. The baseline fields now say they describe routes without an operations entry, versions requires at least one entry, and the deprecated map documents its keys. Refs #1387 --- .../lib/core/models/version-discovery.tsp | 32 +++++++++++++++---- .../schemas/yaml/OperationVersions.yaml | 9 ++++-- .../public/schemas/yaml/UpcomingDefault.yaml | 3 +- .../public/schemas/yaml/VersionDiscovery.yaml | 20 +++++++----- .../schemas/yaml/VersionRetirement.yaml | 3 +- 5 files changed, 45 insertions(+), 22 deletions(-) diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp index 381f95b1e..4d87dae09 100644 --- a/lib/core/lib/core/models/version-discovery.tsp +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -14,6 +14,9 @@ model UpcomingDefault { /** When the new default takes effect */ date: utcDateTime; + + // Discovery sits outside version selection, so new fields must be tolerated rather than versioned + ...Record; } // ######################################################### @@ -28,6 +31,8 @@ model VersionRetirement { /** When the server will stop serving the version, if scheduled */ sunset?: utcDateTime; + + ...Record; } // ######################################################### @@ -38,6 +43,7 @@ model VersionRetirement { @Versioning.added(CommonGrants.Versions.v0_6) model OperationVersions { /** The versions this route serves */ + @minItems(1) versions: Types.protocolVersion[]; /** The version this route serves when a request doesn't name one */ @@ -46,8 +52,13 @@ model OperationVersions { /** A scheduled change to this route's default version, if any */ upcomingDefault?: UpcomingDefault; - /** Deprecated versions of this route, keyed by version, with their retirement schedule */ + /** Deprecated versions of this route, keyed by version, with their retirement schedule + * + * Each key is a full protocol version listed in `versions`, matched on major and minor. + */ deprecated?: Record; + + ...Record; } // ######################################################### @@ -56,9 +67,10 @@ model OperationVersions { /** The protocol versions an API serves * - * The top-level fields describe every route. Routes that differ from them - * have an entry in `operations`. New fields are only ever added to this - * model; clients ignore fields they don't recognize. + * The top-level fields describe every route that has no entry in + * `operations`. Routes that differ from them have an entry in `operations`. + * New fields are only ever added to this model; clients ignore fields they + * don't recognize. */ @example( Examples.VersionDiscovery.routeEntries, @@ -70,16 +82,20 @@ model OperationVersions { ) @Versioning.added(CommonGrants.Versions.v0_6) model VersionDiscovery { - /** The versions every route serves */ + /** The versions every route without an `operations` entry serves */ + @minItems(1) versions: Types.protocolVersion[]; - /** The version every route serves when a request doesn't name one */ + /** The version every route without an `operations` entry serves when a request doesn't name one */ defaultVersion: Types.protocolVersion; /** A scheduled change to the API-wide default version, if any */ upcomingDefault?: UpcomingDefault; - /** Deprecated versions, keyed by version, with their retirement schedule */ + /** Deprecated versions, keyed by version, with their retirement schedule + * + * Each key is a full protocol version listed in `versions`, matched on major and minor. + */ deprecated?: Record; /** Routes whose versions differ from the API-wide values @@ -90,6 +106,8 @@ model VersionDiscovery { * route serves the API-wide values. */ operations?: Record; + + ...Record; } // ######################################################### diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml index c4c6ecae8..97785f237 100644 --- a/website/public/schemas/yaml/OperationVersions.yaml +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -6,6 +6,7 @@ properties: type: array items: $ref: protocolVersion.yaml + minItems: 1 description: The versions this route serves defaultVersion: $ref: protocolVersion.yaml @@ -15,12 +16,14 @@ properties: description: A scheduled change to this route's default version, if any deprecated: $ref: "#/$defs/RecordVersionRetirement" - description: Deprecated versions of this route, keyed by version, with their retirement schedule + description: |- + Deprecated versions of this route, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. required: - versions - defaultVersion -unevaluatedProperties: - not: {} +unevaluatedProperties: {} description: The versions a single route serves, when they differ from the API-wide values $defs: RecordVersionRetirement: diff --git a/website/public/schemas/yaml/UpcomingDefault.yaml b/website/public/schemas/yaml/UpcomingDefault.yaml index 355fcbb32..266e7a54a 100644 --- a/website/public/schemas/yaml/UpcomingDefault.yaml +++ b/website/public/schemas/yaml/UpcomingDefault.yaml @@ -12,6 +12,5 @@ properties: required: - version - date -unevaluatedProperties: - not: {} +unevaluatedProperties: {} description: A scheduled change to the version a server serves by default diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml index 1c2ad16d1..55f32c579 100644 --- a/website/public/schemas/yaml/VersionDiscovery.yaml +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -6,16 +6,20 @@ properties: type: array items: $ref: protocolVersion.yaml - description: The versions every route serves + minItems: 1 + description: The versions every route without an `operations` entry serves defaultVersion: $ref: protocolVersion.yaml - description: The version every route serves when a request doesn't name one + description: The version every route without an `operations` entry serves when a request doesn't name one upcomingDefault: $ref: UpcomingDefault.yaml description: A scheduled change to the API-wide default version, if any deprecated: $ref: "#/$defs/RecordVersionRetirement" - description: Deprecated versions, keyed by version, with their retirement schedule + description: |- + Deprecated versions, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. operations: $ref: "#/$defs/RecordOperationVersions" description: |- @@ -28,8 +32,7 @@ properties: required: - versions - defaultVersion -unevaluatedProperties: - not: {} +unevaluatedProperties: {} examples: - versions: - 0.3.0 @@ -59,9 +62,10 @@ examples: description: |- The protocol versions an API serves - The top-level fields describe every route. Routes that differ from them - have an entry in `operations`. New fields are only ever added to this - model; clients ignore fields they don't recognize. + The top-level fields describe every route that has no entry in + `operations`. Routes that differ from them have an entry in `operations`. + New fields are only ever added to this model; clients ignore fields they + don't recognize. $defs: RecordVersionRetirement: type: object diff --git a/website/public/schemas/yaml/VersionRetirement.yaml b/website/public/schemas/yaml/VersionRetirement.yaml index bd0df99de..7aad7db8e 100644 --- a/website/public/schemas/yaml/VersionRetirement.yaml +++ b/website/public/schemas/yaml/VersionRetirement.yaml @@ -12,6 +12,5 @@ properties: description: When the server will stop serving the version, if scheduled required: - deprecation -unevaluatedProperties: - not: {} +unevaluatedProperties: {} description: The retirement schedule for a deprecated version From cc51eb4bdd19e13f3d316cecbf0884e0a3f1b2f2 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Wed, 18 Nov 2026 08:39:19 -0800 Subject: [PATCH 04/20] feat(core): give discovery its own 200 response without version headers OkT now spreads the version response headers, so discovery would have advertised CG-Version-Served and Vary. ADR 0032 says discovery carries neither, because clients call it before they know which version to request. The route returns a dedicated VersionDiscoveryResponse instead. Refs #1387 --- lib/core/lib/core/responses/success.tsp | 16 ++ .../lib/core/routes/version-discovery.tsp | 3 +- website/public/openapi/openapi.0.6.0.yaml | 158 ++++++++++++++++++ .../yaml/VersionDiscoveryResponse.yaml | 14 ++ 4 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 website/public/schemas/yaml/VersionDiscoveryResponse.yaml diff --git a/lib/core/lib/core/responses/success.tsp b/lib/core/lib/core/responses/success.tsp index e6c13588c..9c8722a8f 100644 --- a/lib/core/lib/core/responses/success.tsp +++ b/lib/core/lib/core/responses/success.tsp @@ -64,6 +64,22 @@ model OkT extends Success { data: T; } +// ############################################################################ +// 200 version discovery response +// ############################################################################ + +/** A 200 response listing the protocol versions an API serves + * + * Discovery sits outside version selection, so unlike `OkT` this response + * carries no version headers: neither `CG-Version-Served` nor `Vary`. + */ +@doc("A 200 response listing the protocol versions an API serves") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionDiscoveryResponse extends Success { + /** The protocol versions the API serves */ + data: Models.VersionDiscovery; +} + // ############################################################################ // 200 paginated response // ############################################################################ diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp index dc01c40d3..328596e50 100644 --- a/lib/core/lib/core/routes/version-discovery.tsp +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -41,9 +41,10 @@ interface ProtocolVersions { This route is optional, but a server that serves more than one protocol version MUST implement it. It ignores the `CG-Version` request header, because clients call it before they know which version to request. + Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. It SHOULD be readable without authentication. Fields are only ever added to the response; clients ignore fields they don't recognize. """) @get - read(): Responses.OkT; + read(): Responses.VersionDiscoveryResponse; } diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index 3cbbeb359..08bf59db6 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -22,6 +22,8 @@ tags: description: Endpoints related to grant awards - name: Forms description: Endpoints related to forms + - name: Versions + description: Endpoints related to discovering the protocol versions an API serves - name: required description: Endpoints that MUST be implemented by all CommonGrants APIs - name: optional @@ -2577,6 +2579,29 @@ paths: security: - OAuth2Auth: - org.changes:read + /common-grants/versions: + get: + operationId: ProtocolVersions_read + summary: List supported versions + description: |- + List the protocol versions this API serves, its default version, and any routes whose versions differ. + + This route is optional, but a server that serves more than one protocol version MUST implement it. + It ignores the `CG-Version` request header, because clients call it before they know which version to request. + Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. + It SHOULD be readable without authentication. + Fields are only ever added to the response; clients ignore fields they don't recognize. + parameters: [] + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.VersionDiscoveryResponse' + tags: + - Versions + - optional components: parameters: CommonGrants.Headers.VersionRequest: @@ -5271,6 +5296,36 @@ components: active: open inactive: closed default: custom + CommonGrants.Models.OperationVersions: + type: object + required: + - versions + - defaultVersion + properties: + versions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions this route serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version this route serves when a request doesn't name one + upcomingDefault: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' + description: A scheduled change to this route's default version, if any + deprecated: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.VersionRetirement' + description: |- + Deprecated versions of this route, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. + additionalProperties: {} + description: The versions a single route serves, when they differ from the API-wide values CommonGrants.Models.OppDefaultFilters: type: object properties: @@ -7094,6 +7149,97 @@ components: A revision moves once from `pending` into a terminal state; a terminal revision is never restated. How a receiver resolves a `pending` change (a human review, a policy engine, a batch job) is out of scope for this contract. + CommonGrants.Models.UpcomingDefault: + type: object + required: + - version + - date + properties: + version: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version that will become the default + date: + type: string + format: date-time + description: When the new default takes effect + additionalProperties: {} + description: A scheduled change to the version a server serves by default + CommonGrants.Models.VersionDiscovery: + type: object + required: + - versions + - defaultVersion + properties: + versions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions every route without an `operations` entry serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version every route without an `operations` entry serves when a request doesn't name one + upcomingDefault: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' + description: A scheduled change to the API-wide default version, if any + deprecated: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.VersionRetirement' + description: |- + Deprecated versions, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. + operations: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.OperationVersions' + description: |- + Routes whose versions differ from the API-wide values + + Each key is the HTTP method and the route's published path, separated + by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + names are ignored when matching a key to a route. Omitted when every + route serves the API-wide values. + additionalProperties: {} + description: |- + The protocol versions an API serves + + The top-level fields describe every route that has no entry in + `operations`. Routes that differ from them have an entry in `operations`. + New fields are only ever added to this model; clients ignore fields they + don't recognize. + example: + versions: + - 0.3.0 + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 + upcomingDefault: + version: 0.5.0 + date: '2027-03-01T00:00:00Z' + deprecated: + 0.3.0: + deprecation: '2026-12-01T00:00:00Z' + sunset: '2027-06-01T00:00:00Z' + CommonGrants.Models.VersionRetirement: + type: object + required: + - deprecation + properties: + deprecation: + type: string + format: date-time + description: When the version was or will be deprecated + sunset: + type: string + format: date-time + description: When the server will stop serving the version, if scheduled + additionalProperties: {} + description: The retirement schedule for a deprecated version CommonGrants.Pagination.PaginatedBodyParams: type: object properties: @@ -7846,6 +7992,18 @@ components: message: type: string example: Success + CommonGrants.Responses.VersionDiscoveryResponse: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.VersionDiscovery' + description: The protocol versions the API serves + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response listing the protocol versions an API serves CommonGrants.Sorting.SortBodyParams: type: object required: diff --git a/website/public/schemas/yaml/VersionDiscoveryResponse.yaml b/website/public/schemas/yaml/VersionDiscoveryResponse.yaml new file mode 100644 index 000000000..f2f1792f4 --- /dev/null +++ b/website/public/schemas/yaml/VersionDiscoveryResponse.yaml @@ -0,0 +1,14 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionDiscoveryResponse.yaml +type: object +properties: + data: + $ref: VersionDiscovery.yaml + description: The protocol versions the API serves +required: + - data +allOf: + - $ref: Success.yaml +unevaluatedProperties: + not: {} +description: A 200 response listing the protocol versions an API serves From 62d018d7ce71666b9410219cd27d04855f982200 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Wed, 18 Nov 2026 09:27:42 -0800 Subject: [PATCH 05/20] docs(core): state the discovery rules ADR 0032 settles The defaultVersion docs now say a default is one of the listed versions, which the schema can't express. The route description adds the ADR's authentication ceiling and narrows "fields are only ever added" to data, since the response envelope stays closed. The interface comment says adopters don't type-parameterize the response, now that the models accept unknown fields. Refs #1387 --- lib/core/lib/core/models/version-discovery.tsp | 4 ++-- lib/core/lib/core/routes/version-discovery.tsp | 6 +++--- website/public/openapi/openapi.0.6.0.yaml | 8 ++++---- website/public/schemas/yaml/OperationVersions.yaml | 2 +- website/public/schemas/yaml/VersionDiscovery.yaml | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp index 4d87dae09..37a896c47 100644 --- a/lib/core/lib/core/models/version-discovery.tsp +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -46,7 +46,7 @@ model OperationVersions { @minItems(1) versions: Types.protocolVersion[]; - /** The version this route serves when a request doesn't name one */ + /** The version this route serves when a request doesn't name one, one of `versions` */ defaultVersion: Types.protocolVersion; /** A scheduled change to this route's default version, if any */ @@ -86,7 +86,7 @@ model VersionDiscovery { @minItems(1) versions: Types.protocolVersion[]; - /** The version every route without an `operations` entry serves when a request doesn't name one */ + /** The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` */ defaultVersion: Types.protocolVersion; /** A scheduled change to the API-wide default version, if any */ diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp index 328596e50..e5bba00f3 100644 --- a/lib/core/lib/core/routes/version-discovery.tsp +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -12,7 +12,7 @@ using TypeSpec.Versioning; /** A re-usable interface for the versions discovery router * * Unlike the other routers, `read` is deliberately not templated: adopters - * don't extend the discovery response. Routes that differ from the API-wide + * don't type-parameterize the discovery response. Routes that differ from the API-wide * versions are described in the response's `operations` field instead. * * @example Declaring the versions discovery route: @@ -42,8 +42,8 @@ interface ProtocolVersions { This route is optional, but a server that serves more than one protocol version MUST implement it. It ignores the `CG-Version` request header, because clients call it before they know which version to request. Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. - It SHOULD be readable without authentication. - Fields are only ever added to the response; clients ignore fields they don't recognize. + It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. + Fields are only ever added to `data`; clients ignore fields they don't recognize. """) @get read(): Responses.VersionDiscoveryResponse; diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index 08bf59db6..3c6ea3999 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -2589,8 +2589,8 @@ paths: This route is optional, but a server that serves more than one protocol version MUST implement it. It ignores the `CG-Version` request header, because clients call it before they know which version to request. Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. - It SHOULD be readable without authentication. - Fields are only ever added to the response; clients ignore fields they don't recognize. + It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. + Fields are only ever added to `data`; clients ignore fields they don't recognize. parameters: [] responses: '200': @@ -5311,7 +5311,7 @@ components: defaultVersion: allOf: - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' - description: The version this route serves when a request doesn't name one + description: The version this route serves when a request doesn't name one, one of `versions` upcomingDefault: allOf: - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' @@ -7180,7 +7180,7 @@ components: defaultVersion: allOf: - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' - description: The version every route without an `operations` entry serves when a request doesn't name one + description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` upcomingDefault: allOf: - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml index 97785f237..7937f7f98 100644 --- a/website/public/schemas/yaml/OperationVersions.yaml +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -10,7 +10,7 @@ properties: description: The versions this route serves defaultVersion: $ref: protocolVersion.yaml - description: The version this route serves when a request doesn't name one + description: The version this route serves when a request doesn't name one, one of `versions` upcomingDefault: $ref: UpcomingDefault.yaml description: A scheduled change to this route's default version, if any diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml index 55f32c579..6858332a7 100644 --- a/website/public/schemas/yaml/VersionDiscovery.yaml +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -10,7 +10,7 @@ properties: description: The versions every route without an `operations` entry serves defaultVersion: $ref: protocolVersion.yaml - description: The version every route without an `operations` entry serves when a request doesn't name one + description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` upcomingDefault: $ref: UpcomingDefault.yaml description: A scheduled change to the API-wide default version, if any From 84b9be904f17a26bf74db7cdd7bc0cf35ef468a7 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Thu, 19 Nov 2026 12:44:56 -0800 Subject: [PATCH 06/20] feat(website): find TypeSpec, Python and TypeScript declarations by name Adds the lookup protocol pages will use to show a schema's code without file paths or line numbers. TypeSpec is read with the compiler's own parser; TypeScript with the TypeScript parser; Python with a small scanner that tracks brackets and strings. A name that isn't declared, or is declared more than once, throws. --- .../__tests__/lib/schema/schema-files.spec.ts | 26 + .../lib/schema/source-declarations.spec.ts | 530 +++++++++++++++++ website/src/lib/schema/paths.ts | 33 +- website/src/lib/schema/schema-files.ts | 28 + .../src/lib/schema/schema-metadata-loader.ts | 114 ---- website/src/lib/schema/source-declarations.ts | 538 ++++++++++++++++++ website/src/scripts/generate-schema-docs.ts | 164 ------ .../src/scripts/generate-schema-metadata.ts | 184 ------ .../src/scripts/generate-type-formatting.ts | 164 ------ 9 files changed, 1140 insertions(+), 641 deletions(-) create mode 100644 website/__tests__/lib/schema/schema-files.spec.ts create mode 100644 website/__tests__/lib/schema/source-declarations.spec.ts create mode 100644 website/src/lib/schema/schema-files.ts delete mode 100644 website/src/lib/schema/schema-metadata-loader.ts create mode 100644 website/src/lib/schema/source-declarations.ts delete mode 100644 website/src/scripts/generate-schema-docs.ts delete mode 100644 website/src/scripts/generate-schema-metadata.ts delete mode 100644 website/src/scripts/generate-type-formatting.ts diff --git a/website/__tests__/lib/schema/schema-files.spec.ts b/website/__tests__/lib/schema/schema-files.spec.ts new file mode 100644 index 000000000..179ca41f1 --- /dev/null +++ b/website/__tests__/lib/schema/schema-files.spec.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from "vitest"; +import { schemaFilePath } from "@/lib/schema/schema-files"; + +// Reads the generated schemas โ€” run `pnpm --filter website run build` first. +describe("schemaFilePath", () => { + it("gives the generated JSON Schema file for a schema", () => { + expect(schemaFilePath("AwardBase")).toBe( + "website/public/schemas/yaml/AwardBase.yaml", + ); + }); + + it("gives a version's copy when asked for one", () => { + expect(schemaFilePath("CompetitionBase", "v0.5.0")).toBe( + "website/public/schemas/yaml/versions/v0.5.0/CompetitionBase.yaml", + ); + }); + + it("fails for a schema that has no JSON Schema file", () => { + expect(() => schemaFilePath("NoSuchSchema")).toThrow( + /No JSON Schema for "NoSuchSchema"/, + ); + expect(() => schemaFilePath("AwardBase", "v0.1.0")).toThrow( + /No JSON Schema for "AwardBase" in v0.1.0/, + ); + }); +}); diff --git a/website/__tests__/lib/schema/source-declarations.spec.ts b/website/__tests__/lib/schema/source-declarations.spec.ts new file mode 100644 index 000000000..8e645a6c6 --- /dev/null +++ b/website/__tests__/lib/schema/source-declarations.spec.ts @@ -0,0 +1,530 @@ +import { describe, it, expect } from "vitest"; +import { + listTypeSpecDeclarations, + listPythonDeclarations, + listTypeScriptDeclarations, + findDeclaration, + findSchemaDeclaration, + findSnippet, + sourceUrl, + type Declaration, +} from "@/lib/schema/source-declarations"; + +/** Picks one declaration out of a listing by name. */ +function pick(declarations: Declaration[], name: string): Declaration { + const matches = declarations.filter((d) => d.name === name); + expect(matches, `exactly one declaration named ${name}`).toHaveLength(1); + return matches[0]; +} + +// ############################################################################ +// TypeSpec +// ############################################################################ + +describe("listTypeSpecDeclarations", () => { + it("includes the doc comment and decorators above a model", () => { + const source = [ + "namespace CommonGrants.Fields;", + "", + "// A section banner that belongs to no declaration", + "/** A monetary amount */", + '@example(Examples.Money.usd, #{ title: "US dollars" })', + "@example(", + " Examples.Money.euro,", + ' #{ title: "Euros" }', + ")", + "@Versioning.added(CommonGrants.Versions.v0_1)", + "model Money {", + " /** The amount */", + " amount: decimalString;", + "}", + "", + ].join("\n"); + + const money = pick(listTypeSpecDeclarations(source), "Money"); + expect(money.startLine).toBe(4); + expect(money.endLine).toBe(14); + expect(money.code.split("\n")[0]).toBe("/** A monetary amount */"); + expect(money.code.endsWith("}")).toBe(true); + }); + + it("finds the whole of a model with nested braces", () => { + const source = [ + "model OrgRelationshipT {", + " kind?: {", + " ...Fields.ExtensibleEnumT;", + " };", + "", + " allIds?: Array<{", + " id: string;", + " }>;", + "}", + "", + "model After {}", + ].join("\n"); + + const declaration = pick( + listTypeSpecDeclarations(source), + "OrgRelationshipT", + ); + expect(declaration.startLine).toBe(1); + expect(declaration.endLine).toBe(9); + }); + + it("finds one-line declarations, scalars and aliases", () => { + const source = [ + "/** An email address */", + '@format("email")', + "scalar email extends string;", + "", + "/** An email address. */", + "alias Email = Types.email; // Exposes Email from CommonGrants.Fields", + "", + "/** The status */", + "model AwdStatus is Fields.ExtensibleEnumT;", + ].join("\n"); + + const declarations = listTypeSpecDeclarations(source); + expect(pick(declarations, "email")).toMatchObject({ + startLine: 1, + endLine: 3, + }); + // The trailing comment on the declaration's last line is kept. + expect(pick(declarations, "Email").code).toBe( + [ + "/** An email address. */", + "alias Email = Types.email; // Exposes Email from CommonGrants.Fields", + ].join("\n"), + ); + expect(pick(declarations, "AwdStatus")).toMatchObject({ + startLine: 8, + endLine: 9, + }); + }); + + it("finds declarations inside a namespace block, keeping their indentation", () => { + const source = [ + "namespace CommonGrants.Patch {", + " model OrgProfileWritable {}", + "}", + "", + "namespace CommonGrants.Models {", + " /** A merge patch. */", + " @Versioning.added(CommonGrants.Versions.v0_4)", + " model OrgPatchData is TypeSpec.Http.MergePatchUpdate<", + " CommonGrants.Patch.OrgProfileWritable,", + ' "OrgPatch{name}"', + " >;", + "", + " /** Examples of the OrgPatchData model */", + " namespace Examples.OrgPatchData {", + ' const patch = #{ name: "x" };', + " }", + "}", + ].join("\n"); + + const declarations = listTypeSpecDeclarations(source); + const patch = pick(declarations, "OrgPatchData"); + expect(patch.startLine).toBe(6); + expect(patch.endLine).toBe(11); + expect(patch.code.split("\n")[0]).toBe(" /** A merge patch. */"); + // Namespaces and consts are not declarations a page can name. + expect(declarations.map((d) => d.name)).not.toContain("patch"); + expect(declarations.map((d) => d.name)).toEqual([ + "OrgProfileWritable", + "OrgPatchData", + ]); + // Each declaration records the namespace it's declared in. + expect(pick(declarations, "OrgProfileWritable").namespace).toBe( + "CommonGrants.Patch", + ); + expect(patch.namespace).toBe("CommonGrants.Models"); + }); + + it("records the namespace a file-level namespace statement sets", () => { + const source = [ + "namespace CommonGrants.Fields;", + "", + "model Money {}", + ].join("\n"); + expect(pick(listTypeSpecDeclarations(source), "Money").namespace).toBe( + "CommonGrants.Fields", + ); + }); + + it("keeps names that are prefixes of other names apart", () => { + const source = [ + "model OppStatus is ExtensibleEnumT;", + "", + "enum OppStatusOptions {", + " open,", + "}", + ].join("\n"); + + const declarations = listTypeSpecDeclarations(source); + expect(pick(declarations, "OppStatus").endLine).toBe(1); + expect(pick(declarations, "OppStatusOptions")).toMatchObject({ + startLine: 3, + endLine: 5, + }); + }); + + it("throws on a source that doesn't parse", () => { + expect(() => listTypeSpecDeclarations("model Broken {")).toThrow(); + }); +}); + +// ############################################################################ +// Python +// ############################################################################ + +describe("listPythonDeclarations", () => { + it("covers a class through its last body line, not the next section's comments", () => { + const source = [ + '"""Module docstring."""', + "", + "# ###############", + "# Event Types", + "# ###############", + "", + "", + "class EventType(StrEnum):", + ' """Type of event."""', + "", + ' SINGLE_DATE = "singleDate"', + ' OTHER = "other"', + "", + "", + "# ###############", + "# Event Base", + "# ###############", + "", + "", + "class EventBase(SealedModel):", + " name: str", + ].join("\n"); + + const declarations = listPythonDeclarations(source); + expect(pick(declarations, "EventType")).toMatchObject({ + startLine: 8, + endLine: 12, + }); + expect(pick(declarations, "EventBase")).toMatchObject({ + startLine: 20, + endLine: 21, + }); + }); + + it("keeps a class body whose strings and brackets reach column 0", () => { + const source = [ + "class Filtered(Paginated[ItemsT], Generic[ItemsT, FilterT]):", + ' """A filtered list.', + "", + "Continued at column 0 inside the docstring.", + ' """', + "", + " filter_info: FilterInfo[FilterT] = Field(", + " ...,", + ' alias="filterInfo",', + ")", + " # A trailing comment inside the body", + "", + "", + "class Next:", + " pass", + ].join("\n"); + + expect(pick(listPythonDeclarations(source), "Filtered")).toMatchObject({ + startLine: 1, + endLine: 11, + }); + }); + + it("includes decorators and multi-line class headers", () => { + const source = [ + "@dataclass(", + " frozen=True,", + ")", + "@other", + "class Point(", + " Base,", + "):", + " x: int", + "", + "def helper() -> None:", + " return None", + ].join("\n"); + + const declarations = listPythonDeclarations(source); + expect(pick(declarations, "Point")).toMatchObject({ + startLine: 1, + endLine: 8, + }); + expect(pick(declarations, "helper")).toMatchObject({ + startLine: 10, + endLine: 11, + }); + }); + + it("finds one-line and multi-line assignments", () => { + const source = [ + "Event = Union[SingleDateEvent, DateRangeEvent, OtherEvent]", + 'T = TypeVar("T")', + "UTCDateTime = Annotated[", + " datetime,", + " AfterValidator(_utc),", + "]", + 'Duns: TypeAlias = Annotated[str, StringConstraints(pattern=r"^[0-9]{9}$")]', + "if TYPE_CHECKING:", + " from x import Y", + ].join("\n"); + + const declarations = listPythonDeclarations(source); + expect(pick(declarations, "Event")).toMatchObject({ + startLine: 1, + endLine: 1, + }); + expect(pick(declarations, "UTCDateTime")).toMatchObject({ + startLine: 3, + endLine: 6, + }); + expect(pick(declarations, "Duns").startLine).toBe(7); + expect(declarations.map((d) => d.name)).toEqual([ + "Event", + "T", + "UTCDateTime", + "Duns", + ]); + }); + + it("keeps names that are prefixes of other names apart", () => { + const source = [ + "class OppStatus(Base):", + " value: str", + "", + "", + "class OppStatusOptions(StrEnum):", + ' OPEN = "open"', + ].join("\n"); + + const declarations = listPythonDeclarations(source); + expect(pick(declarations, "OppStatus").endLine).toBe(2); + expect(pick(declarations, "OppStatusOptions").startLine).toBe(5); + }); +}); + +// ############################################################################ +// TypeScript +// ############################################################################ + +describe("listTypeScriptDeclarations", () => { + it("covers a whole statement, starting at the declaration rather than its comment", () => { + const source = [ + 'import { z } from "zod";', + "", + "/** Query parameters for paginated routes */", + "export const PaginatedQueryParamsSchema = z.object({", + " /** The page */", + " page: z.number().int().min(1).default(1),", + "});", + "", + "// Base event schema (common fields)", + "const EventBaseSchema = z.object({", + " name: z.string(),", + "});", + ].join("\n"); + + const declarations = listTypeScriptDeclarations(source); + expect(pick(declarations, "PaginatedQueryParamsSchema")).toMatchObject({ + startLine: 4, + endLine: 7, + }); + // Unexported declarations count too. + expect(pick(declarations, "EventBaseSchema")).toMatchObject({ + startLine: 10, + endLine: 12, + }); + }); + + it("finds one-line declarations and keeps prefix names apart", () => { + const source = [ + 'export const SortOrderEnum = z.enum(["asc", "desc"]);', + 'export const SortOrderEnumExtra = z.enum(["x"]);', + ].join("\n"); + + const declarations = listTypeScriptDeclarations(source); + expect(pick(declarations, "SortOrderEnum")).toMatchObject({ + startLine: 1, + endLine: 1, + code: 'export const SortOrderEnum = z.enum(["asc", "desc"]);', + }); + }); + + it("finds generic functions, types, interfaces and chained calls", () => { + const source = [ + "export const PaginatedSchema = (itemsSchema: T) =>", + " SuccessSchema.extend({", + " items: z.array(itemsSchema),", + " });", + "", + "export type Money = z.infer;", + "", + "export interface Plugin {", + " name: string;", + "}", + "", + "export const MoneySchema = z", + " .object({", + " amount: DecimalStringSchema,", + " })", + " .strict();", + ].join("\n"); + + const declarations = listTypeScriptDeclarations(source); + expect(pick(declarations, "PaginatedSchema")).toMatchObject({ + startLine: 1, + endLine: 4, + }); + expect(pick(declarations, "Money").startLine).toBe(6); + expect(pick(declarations, "Plugin")).toMatchObject({ + startLine: 8, + endLine: 10, + }); + expect(pick(declarations, "MoneySchema")).toMatchObject({ + startLine: 12, + endLine: 16, + }); + }); +}); + +// ############################################################################ +// Finding a declaration across the sources +// ############################################################################ + +describe("findDeclaration", () => { + it("finds a TypeSpec declaration in the protocol sources and names its file", () => { + const found = findDeclaration("typeSpec", "OrgPatchData"); + expect(found.path).toBe("lib/core/lib/core/models/organization-sync.tsp"); + expect(found.code).toMatch(/model OrgPatchData is/); + expect(found.code.split("\n")[0]).toMatch(/^\s*\/\*\*/); + }); + + it("finds Python and TypeScript declarations in the SDK sources", () => { + expect(findDeclaration("python", "OppStatusOptions").path).toMatch( + /^lib\/python-sdk\/common_grants_sdk\/schemas\/pydantic\/.+\.py$/, + ); + expect(findDeclaration("typescript", "MoneySchema").path).toMatch( + /^lib\/ts-sdk\/src\/schemas\/zod\/.+\.ts$/, + ); + }); + + it("fails when no declaration has the name", () => { + expect(() => findDeclaration("typeSpec", "NoSuchSchema")).toThrow( + /No TypeSpec declaration named "NoSuchSchema"/, + ); + expect(() => findDeclaration("python", "NoSuchSchema")).toThrow( + /No Python declaration named "NoSuchSchema"/, + ); + expect(() => findDeclaration("typescript", "NoSuchSchema")).toThrow( + /No TypeScript declaration named "NoSuchSchema"/, + ); + }); + + it("skips the merge-patch mirrors, which reuse the names of the models they mirror", () => { + // CommonGrants.Patch redeclares OrgIds and others as compile-time sources + // for OrgPatchData; the page for OrgIds means the model in Models. + expect(findDeclaration("typeSpec", "OrgIds").path).toBe( + "lib/core/lib/core/models/organization.tsp", + ); + // A qualified name still reaches a mirror. + expect(findDeclaration("typeSpec", "Patch.OrgIds").path).toBe( + "lib/core/lib/core/models/organization-sync.tsp", + ); + expect(findDeclaration("typeSpec", "CommonGrants.Models.OrgIds").path).toBe( + "lib/core/lib/core/models/organization.tsp", + ); + }); + + it("fails when more than one file declares the name", () => { + // `V` is a TypeVar declared separately in several SDK modules. + expect(() => findDeclaration("python", "V")).toThrow( + /More than one Python declaration named "V"/, + ); + }); +}); + +describe("findSchemaDeclaration", () => { + it("finds TypeSpec and Python declarations by the schema's own name", () => { + expect(findSchemaDeclaration("typeSpec", "AwdIdFain").code).toMatch( + /model AwdIdFain is/, + ); + expect(findSchemaDeclaration("python", "OppStatusOptions").code).toMatch( + /^class OppStatusOptions\(/, + ); + }); + + it("finds a TypeScript schema named Schema", () => { + expect(findSchemaDeclaration("typescript", "Money").name).toBe( + "MoneySchema", + ); + }); + + it("fails when the SDK declares the schema under another name", () => { + // The TypeScript SDK names enums Enum. + expect(() => findSchemaDeclaration("typescript", "SortOrder")).toThrow( + /No TypeScript declaration named "SortOrderSchema"/, + ); + // The Python SDK names its operator enums in the singular. + expect(() => + findSchemaDeclaration("python", "EquivalenceOperators"), + ).toThrow(/No Python declaration named "EquivalenceOperators"/); + }); +}); + +describe("findSnippet", () => { + it("looks up the schema's conventional name when the page just asks for the tab", () => { + expect(findSnippet("typescript", true, "Money").name).toBe("MoneySchema"); + }); + + it("looks up the name the page gives instead", () => { + expect(findSnippet("typescript", "SortOrderEnum", "SortOrder").name).toBe( + "SortOrderEnum", + ); + expect(findSnippet("typeSpec", "ExtensibleEnumT").name).toBe( + "ExtensibleEnumT", + ); + }); + + it("shows several declarations from one file together, each whole, linking across them", () => { + const snippet = findSnippet("typeSpec", ["IdentifierT", "Identifier"]); + const template = findDeclaration("typeSpec", "IdentifierT"); + const model = findDeclaration("typeSpec", "Identifier"); + expect(snippet.code).toBe(`${template.code}\n\n${model.code}`); + expect(snippet.path).toBe(model.path); + expect(snippet.startLine).toBe(template.startLine); + expect(snippet.endLine).toBe(model.endLine); + }); + + it("fails when declarations shown together are in different files", () => { + expect(() => findSnippet("typeSpec", ["Money", "AwardBase"])).toThrow( + /must be in one file/, + ); + }); + + it("fails when the page asks for the tab without naming a schema or a declaration", () => { + expect(() => findSnippet("python", true)).toThrow( + /Python tab needs a declaration name/, + ); + }); +}); + +describe("sourceUrl", () => { + it("links to the declaration's lines on GitHub", () => { + expect(sourceUrl({ path: "lib/a.tsp", startLine: 3, endLine: 9 })).toBe( + "https://github.com/HHS/simpler-grants-protocol/tree/main//lib/a.tsp#L3-L9", + ); + expect(sourceUrl({ path: "lib/a.tsp", startLine: 3, endLine: 3 })).toBe( + "https://github.com/HHS/simpler-grants-protocol/tree/main//lib/a.tsp#L3", + ); + }); +}); diff --git a/website/src/lib/schema/paths.ts b/website/src/lib/schema/paths.ts index 686606d0c..8e662866d 100644 --- a/website/src/lib/schema/paths.ts +++ b/website/src/lib/schema/paths.ts @@ -8,9 +8,7 @@ import * as path from "path"; * Directory tree (relative to WEBSITE_ROOT unless noted): * * cache/ - * schema-docs-mapping.json - * schema-metadata.json - * type-formatting-cache.json + * plugin-metadata.json * public/ * openapi/ * schemas/ @@ -23,6 +21,8 @@ import * as path from "path"; * * REPO_ROOT is the parent of WEBSITE_ROOT. Extension schemas are referenced * from repo root as website/.extension-schemas (EXTENSION_SCHEMAS_PATH_PREFIX). + * Docs pages find code snippets by name under TYPESPEC_SOURCE_DIR, + * PYTHON_SDK_SCHEMAS_DIR and TS_SDK_SCHEMAS_DIR. */ export class Paths { /** Absolute path to the website directory (process.cwd() at build time) */ @@ -53,24 +53,27 @@ export class Paths { .join("/"); // Generated cache files - static readonly SCHEMA_DOCS_MAPPING = path.join( - Paths.CACHE_DIR, - "schema-docs-mapping.json", - ); - static readonly SCHEMA_METADATA = path.join( - Paths.CACHE_DIR, - "schema-metadata.json", - ); - static readonly TYPE_FORMATTING_CACHE = path.join( - Paths.CACHE_DIR, - "type-formatting-cache.json", - ); static readonly PLUGIN_METADATA = path.join( Paths.CACHE_DIR, "plugin-metadata.json", ); // Source directories + /** Protocol TypeSpec source, searched for declarations by name */ + static readonly TYPESPEC_SOURCE_DIR = path.join( + Paths.REPO_ROOT, + "lib/core/lib", + ); + /** Python SDK schemas, searched for declarations by name */ + static readonly PYTHON_SDK_SCHEMAS_DIR = path.join( + Paths.REPO_ROOT, + "lib/python-sdk/common_grants_sdk/schemas/pydantic", + ); + /** TypeScript SDK schemas, searched for declarations by name */ + static readonly TS_SDK_SCHEMAS_DIR = path.join( + Paths.REPO_ROOT, + "lib/ts-sdk/src/schemas/zod", + ); static readonly CONTENT_DOCS_DIR = path.join( Paths.WEBSITE_ROOT, "src/content/docs", diff --git a/website/src/lib/schema/schema-files.ts b/website/src/lib/schema/schema-files.ts new file mode 100644 index 000000000..19384ae1a --- /dev/null +++ b/website/src/lib/schema/schema-files.ts @@ -0,0 +1,28 @@ +import { existsSync } from "fs"; +import * as path from "path"; +import { Paths } from "./paths"; + +/** + * Gives the path, relative to the repository root, of the JSON Schema file the + * website's TypeSpec build writes for a schema, or of its copy for one + * protocol version (`v0.5.0`). + * + * @throws if the file doesn't exist, so a page naming an unknown schema fails the build + */ +export function schemaFilePath(schemaName: string, version?: string): string { + const dir = version + ? path.join(Paths.SCHEMAS_DIR, "versions", version) + : Paths.SCHEMAS_DIR; + const file = path.join(dir, `${schemaName}.yaml`); + const relative = path + .relative(Paths.REPO_ROOT, file) + .split(path.sep) + .join("/"); + + if (!existsSync(file)) { + throw new Error( + `No JSON Schema for "${schemaName}"${version ? ` in ${version}` : ""}: ${relative} doesn't exist`, + ); + } + return relative; +} diff --git a/website/src/lib/schema/schema-metadata-loader.ts b/website/src/lib/schema/schema-metadata-loader.ts deleted file mode 100644 index 9761d8680..000000000 --- a/website/src/lib/schema/schema-metadata-loader.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { readFileSync } from "fs"; -import { Paths } from "./paths"; - -/** - * Pre-computed schema metadata - */ -export interface SchemaMetadata { - schemaName: string; - filePath: string; - type: - "object" | "enum" | "array" | "string" | "number" | "boolean" | "unknown"; - isEnum: boolean; - isObject: boolean; - properties?: string[]; - enumValues?: string[]; - lastModified: number; - contentHash: string; -} - -/** - * Schema metadata collection - */ -export interface SchemaMetadataCollection { - schemas: Record; - generatedAt: number; - totalSchemas: number; -} - -/** - * Schema metadata loader service - */ -export class SchemaMetadataLoader { - private static cache: SchemaMetadataCollection | null = null; - - /** - * Loads schema metadata with caching - */ - static loadMetadata(): SchemaMetadataCollection { - if (this.cache) { - return this.cache; - } - - try { - const metadataPath = Paths.SCHEMA_METADATA; - const metadataContent = readFileSync(metadataPath, "utf-8"); - const metadata = JSON.parse(metadataContent) as SchemaMetadataCollection; - - this.cache = metadata; - console.log(`Loaded schema metadata (${metadata.totalSchemas} schemas)`); - return metadata; - } catch (error) { - console.warn(`Could not load schema metadata: ${error}`); - - // Return empty collection as fallback - const fallback: SchemaMetadataCollection = { - schemas: {}, - generatedAt: Date.now(), - totalSchemas: 0, - }; - - this.cache = fallback; - return fallback; - } - } - - /** - * Gets metadata for a specific schema - */ - static getSchemaMetadata(schemaName: string): SchemaMetadata | undefined { - const metadata = this.loadMetadata(); - return metadata.schemas[schemaName]; - } - - /** - * Checks if a schema is an enum schema - */ - static isEnumSchema(schemaName: string): boolean { - const metadata = this.getSchemaMetadata(schemaName); - return metadata?.isEnum || false; - } - - /** - * Checks if a schema is an object schema - */ - static isObjectSchema(schemaName: string): boolean { - const metadata = this.getSchemaMetadata(schemaName); - return metadata?.isObject || false; - } - - /** - * Gets all schema names - */ - static getAllSchemaNames(): string[] { - const metadata = this.loadMetadata(); - return Object.keys(metadata.schemas); - } - - /** - * Gets schemas by type - */ - static getSchemasByType(type: SchemaMetadata["type"]): SchemaMetadata[] { - const metadata = this.loadMetadata(); - return Object.values(metadata.schemas).filter( - (schema) => schema.type === type, - ); - } - - /** - * Clears the cache (useful for testing) - */ - static clearCache(): void { - this.cache = null; - } -} diff --git a/website/src/lib/schema/source-declarations.ts b/website/src/lib/schema/source-declarations.ts new file mode 100644 index 000000000..fcd8399ad --- /dev/null +++ b/website/src/lib/schema/source-declarations.ts @@ -0,0 +1,538 @@ +import { readdirSync, readFileSync } from "fs"; +import * as path from "path"; +import { parse, SyntaxKind } from "@typespec/compiler/ast"; +import type { TypeSpecScriptNode } from "@typespec/compiler/ast"; +import ts from "typescript"; +import { Paths } from "./paths"; + +/** + * Finds a named declaration in the protocol's TypeSpec source or in the SDKs' + * Python and TypeScript source, so a docs page can show the code for a schema + * by naming it rather than by typing a file path and a range of lines. + */ + +/** A declaration found in a source file. */ +export interface Declaration { + /** The declared name */ + name: string; + /** First line of the declaration, 1-based */ + startLine: number; + /** Last line of the declaration, 1-based and inclusive */ + endLine: number; + /** The declaration's source lines, as they appear in the file */ + code: string; + /** The TypeSpec namespace the declaration sits in, if any */ + namespace?: string; +} + +/** A declaration and the file it was found in. */ +export interface FoundDeclaration extends Declaration { + /** Path to the file, relative to the repository root */ + path: string; +} + +/** The source languages a docs page can show a declaration in. */ +export type SourceLanguage = "typeSpec" | "python" | "typescript"; + +/** Where each language's source lives, and how to list its declarations. */ +const SOURCES: Record< + SourceLanguage, + { + label: string; + dir: string; + extension: string; + list: (source: string) => Declaration[]; + } +> = { + typeSpec: { + label: "TypeSpec", + dir: Paths.TYPESPEC_SOURCE_DIR, + extension: ".tsp", + list: listTypeSpecDeclarations, + }, + python: { + label: "Python", + dir: Paths.PYTHON_SDK_SCHEMAS_DIR, + extension: ".py", + list: listPythonDeclarations, + }, + typescript: { + label: "TypeScript", + dir: Paths.TS_SDK_SCHEMAS_DIR, + extension: ".ts", + list: listTypeScriptDeclarations, + }, +}; + +// ############################################################################ +// Finding a declaration by name +// ############################################################################ + +const indexes = new Map>(); + +/** + * TypeSpec namespaces whose declarations a bare name never refers to. + * `CommonGrants.Patch` holds compile-time mirrors of the organization models + * that `OrgPatchData` is built from; they keep the names of the models they + * mirror, so `OrgIds` on its own means the model in `CommonGrants.Models`. A + * qualified name such as `Patch.OrgIds` still reaches a mirror. + */ +const TYPESPEC_MIRROR_NAMESPACES = new Set(["CommonGrants.Patch"]); + +/** + * Finds the one declaration with this name in a language's source. + * + * A TypeSpec name may be qualified with the end of its namespace + * (`Patch.OrgIds`, `CommonGrants.Models.OrgIds`). + * + * @throws if no file declares the name, or more than one declaration has it + */ +export function findDeclaration( + language: SourceLanguage, + name: string, +): FoundDeclaration { + const { label, dir } = SOURCES[language]; + const matches = matchDeclarations(language, name); + + if (matches.length === 0) { + throw new Error( + `No ${label} declaration named "${name}" under ${path.relative(Paths.REPO_ROOT, dir)}`, + ); + } + if (matches.length > 1) { + const places = matches.map((m) => `${m.path}:${m.startLine}`).join(", "); + throw new Error( + `More than one ${label} declaration named "${name}": ${places}. Name the one to show explicitly.`, + ); + } + return matches[0]; +} + +/** The declarations a name refers to, before checking there's exactly one. */ +function matchDeclarations( + language: SourceLanguage, + name: string, +): FoundDeclaration[] { + const parts = name.split("."); + const bareName = parts.pop()!; + const candidates = getIndex(language).get(bareName) ?? []; + + if (parts.length > 0) { + const qualifier = parts.join("."); + return candidates.filter( + (d) => + d.namespace === qualifier || + (d.namespace ?? "").endsWith(`.${qualifier}`), + ); + } + return candidates.filter( + (d) => !TYPESPEC_MIRROR_NAMESPACES.has(d.namespace ?? ""), + ); +} + +/** + * The name a language's source declares a schema under, by convention: + * TypeSpec and Python use the schema's own name, and the TypeScript SDK names + * its Zod schemas `Schema`. A page names the declaration explicitly + * when an SDK doesn't follow this (its enums, for example, end in `Enum`). + */ +export function conventionalName( + language: SourceLanguage, + schemaName: string, +): string { + return language === "typescript" ? `${schemaName}Schema` : schemaName; +} + +/** + * Finds the declaration for a schema under its conventional name. + * + * @throws if nothing or more than one thing has that name + */ +export function findSchemaDeclaration( + language: SourceLanguage, + schemaName: string, +): FoundDeclaration { + return findDeclaration(language, conventionalName(language, schemaName)); +} + +/** + * Finds the code a source tab shows. The page either just asks for the tab + * (`true`), which looks up the schema's conventional name; gives the + * declaration's name, for an SDK that names it differently; or lists several + * names, to show a template with the model built from it. Several + * declarations must be in one file; each is shown whole, in the order listed, + * separated by a blank line. + * + * @throws if a declaration can't be found + */ +export function findSnippet( + language: SourceLanguage, + requested: true | string | string[], + schemaName?: string, +): FoundDeclaration { + if (Array.isArray(requested)) { + const found = requested.map((name) => findDeclaration(language, name)); + const files = new Set(found.map((d) => d.path)); + if (found.length === 0 || files.size !== 1) { + throw new Error( + `Declarations shown together must be in one file: ${requested.join(", ")} are in ${[...files].join(", ") || "no file"}`, + ); + } + return { + name: requested.join(", "), + path: found[0].path, + startLine: Math.min(...found.map((d) => d.startLine)), + endLine: Math.max(...found.map((d) => d.endLine)), + code: found.map((d) => d.code).join("\n\n"), + }; + } + if (typeof requested === "string") { + return findDeclaration(language, requested); + } + if (!schemaName) { + throw new Error( + `The ${SOURCES[language].label} tab needs a declaration name, or a schema name to look it up by`, + ); + } + return findSchemaDeclaration(language, schemaName); +} + +/** + * Links to a declaration's lines in the repository on GitHub. Keeps the + * double slash the docs have always published. + */ +export function sourceUrl( + declaration: Pick, +): string { + const { path: filePath, startLine, endLine } = declaration; + const lines = + endLine > startLine ? `#L${startLine}-L${endLine}` : `#L${startLine}`; + return `https://github.com/HHS/simpler-grants-protocol/tree/main//${filePath}${lines}`; +} + +/** Lists every declaration in a language's source, by name, once per build. */ +function getIndex(language: SourceLanguage): Map { + const cached = indexes.get(language); + if (cached) return cached; + + const { dir, extension, list } = SOURCES[language]; + const index = new Map(); + + for (const file of listFiles(dir, extension)) { + const relativePath = path + .relative(Paths.REPO_ROOT, file) + .split(path.sep) + .join("/"); + let declarations: Declaration[]; + try { + declarations = list(readFileSync(file, "utf-8")); + } catch (error) { + throw new Error(`Could not read declarations from ${relativePath}`, { + cause: error, + }); + } + for (const declaration of declarations) { + const entries = index.get(declaration.name) ?? []; + entries.push({ ...declaration, path: relativePath }); + index.set(declaration.name, entries); + } + } + + indexes.set(language, index); + return index; +} + +/** Lists files with an extension under a directory, in a stable order. */ +function listFiles(dir: string, extension: string): string[] { + const files: string[] = []; + const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => + a.name.localeCompare(b.name), + ); + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + files.push(...listFiles(fullPath, extension)); + } else if (entry.isFile() && entry.name.endsWith(extension)) { + files.push(fullPath); + } + } + return files; +} + +// ############################################################################ +// Shared helpers +// ############################################################################ + +/** Converts a character offset to a 1-based line number. */ +function lineAt(lineStarts: number[], offset: number): number { + let low = 0; + let high = lineStarts.length - 1; + while (low < high) { + const mid = Math.ceil((low + high) / 2); + if (lineStarts[mid] <= offset) low = mid; + else high = mid - 1; + } + return low + 1; +} + +function getLineStarts(source: string): number[] { + const starts = [0]; + for (let i = 0; i < source.length; i++) { + if (source[i] === "\n") starts.push(i + 1); + } + return starts; +} + +/** Builds a declaration from whole lines of the source. */ +function fromLines( + lines: string[], + name: string, + startLine: number, + endLine: number, +): Declaration { + return { + name, + startLine, + endLine, + code: lines.slice(startLine - 1, endLine).join("\n"), + }; +} + +// ############################################################################ +// TypeSpec +// ############################################################################ + +/** A statement in a TypeSpec source or namespace block */ +type Statement = TypeSpecScriptNode["statements"][number]; + +const TYPESPEC_DECLARATION_KINDS = new Set([ + SyntaxKind.ModelStatement, + SyntaxKind.EnumStatement, + SyntaxKind.UnionStatement, + SyntaxKind.ScalarStatement, + SyntaxKind.AliasStatement, + SyntaxKind.InterfaceStatement, + SyntaxKind.OperationStatement, +]); + +/** + * Lists the named type declarations in a TypeSpec source, each with the doc + * comment and decorators above it, including those inside namespace blocks. + * Uses the TypeSpec compiler's own parser, so nested braces, one-line + * declarations and multi-line decorators need no special handling. + * + * @throws if the source doesn't parse + */ +export function listTypeSpecDeclarations(source: string): Declaration[] { + const ast = parse(source, { docs: true }); + if (ast.parseDiagnostics.length > 0) { + const messages = ast.parseDiagnostics.map((d) => d.message).join("; "); + throw new Error(`TypeSpec source doesn't parse: ${messages}`); + } + + const lineStarts = getLineStarts(source); + const lines = source.split("\n"); + const declarations: Declaration[] = []; + + const visit = (statements: readonly Statement[], namespace: string[]) => { + // A file-level `namespace X;` applies to the statements after it. + let current = namespace; + for (const statement of statements) { + if (statement.kind === SyntaxKind.NamespaceStatement) { + // `namespace A.B { }` parses as A holding B; walk down to the + // innermost one, collecting the name as we go. + const names = [...namespace]; + let node: Statement | undefined = statement; + let body: unknown; + while (node?.kind === SyntaxKind.NamespaceStatement) { + names.push(node.id.sv); + body = node.statements; + node = Array.isArray(body) ? undefined : (body as Statement); + } + if (Array.isArray(body)) { + visit(body as Statement[], names); + } else { + current = names; + } + continue; + } + if (!TYPESPEC_DECLARATION_KINDS.has(statement.kind)) continue; + + // The node starts at its doc comment; its decorators sit between. + const name = (statement as { id: { sv: string } }).id.sv; + declarations.push({ + ...fromLines( + lines, + name, + lineAt(lineStarts, statement.pos), + lineAt(lineStarts, statement.end - 1), + ), + namespace: current.join(".") || undefined, + }); + } + }; + visit(ast.statements, []); + + return declarations; +} + +// ############################################################################ +// TypeScript +// ############################################################################ + +/** + * Lists the top-level declarations in a TypeScript source. Each one starts at + * its declaration keyword, not at the comment above it, and runs to the end + * of its statement. + */ +export function listTypeScriptDeclarations(source: string): Declaration[] { + const file = ts.createSourceFile( + "source.ts", + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, + ); + const lines = source.split("\n"); + const declarations: Declaration[] = []; + + const add = (name: string, statement: ts.Statement) => { + const startLine = + file.getLineAndCharacterOfPosition(statement.getStart(file)).line + 1; + const endLine = file.getLineAndCharacterOfPosition(statement.end).line + 1; + declarations.push(fromLines(lines, name, startLine, endLine)); + }; + + for (const statement of file.statements) { + if (ts.isVariableStatement(statement)) { + for (const declaration of statement.declarationList.declarations) { + if (ts.isIdentifier(declaration.name)) { + add(declaration.name.text, statement); + } + } + } else if ( + (ts.isFunctionDeclaration(statement) || + ts.isClassDeclaration(statement) || + ts.isInterfaceDeclaration(statement) || + ts.isTypeAliasDeclaration(statement) || + ts.isEnumDeclaration(statement)) && + statement.name + ) { + add(statement.name.text, statement); + } + } + + return declarations; +} + +// ############################################################################ +// Python +// ############################################################################ + +const PYTHON_DEFINITION = /^(?:async\s+)?(?:class|def)\s+([A-Za-z_]\w*)/; +const PYTHON_ASSIGNMENT = /^([A-Za-z_]\w*)\s*(?::[^=]+)?=(?!=)/; + +/** One line of Python, after tracking the strings and brackets around it. */ +interface PythonLine { + text: string; + /** Whether the line opens inside a bracket or a multi-line string */ + continues: boolean; +} + +/** + * Marks which lines of a Python source continue an earlier line, because they + * open inside brackets or a triple-quoted string. Those lines can't start a + * statement, whatever their indentation. + */ +function scanPythonLines(source: string): PythonLine[] { + const result: PythonLine[] = []; + let depth = 0; + let quote: string | null = null; // the open string's delimiter + + for (const text of source.split("\n")) { + result.push({ text, continues: depth > 0 || quote !== null }); + + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (quote) { + if (char === "\\") { + i++; + } else if (text.startsWith(quote, i)) { + i += quote.length - 1; + quote = null; + } + continue; + } + if (char === "#") break; + if (char === '"' || char === "'") { + const triple = char.repeat(3); + quote = text.startsWith(triple, i) ? triple : char; + i += quote.length - 1; + } else if ("([{".includes(char)) { + depth++; + } else if (")]}".includes(char)) { + depth = Math.max(0, depth - 1); + } + } + // A single-quoted string can't run past the end of its line. + if (quote && quote.length === 1) quote = null; + } + + return result; +} + +/** + * Lists the module-level classes, functions and assignments in a Python + * source. Each one starts at its first decorator, or at its own line, and + * runs to the last non-blank line of its body. + */ +export function listPythonDeclarations(source: string): Declaration[] { + const lines = scanPythonLines(source); + const rawLines = lines.map((l) => l.text); + const declarations: Declaration[] = []; + + /** A line that begins a new module-level statement */ + const startsStatement = (line: PythonLine) => + !line.continues && /^[^\s#]/.test(line.text); + + let i = 0; + while (i < lines.length) { + if (!startsStatement(lines[i])) { + i++; + continue; + } + + // Decorators belong to the definition below them. + const start = i; + while (i < lines.length && /^@/.test(lines[i].text)) { + i++; + while (i < lines.length && lines[i].continues) i++; + } + const header = lines[i]?.text ?? ""; + + // The statement runs until the next line that starts a statement or is + // a comment at column 0. + let end = i; + for (let j = i + 1; j < lines.length; j++) { + const line = lines[j]; + if (startsStatement(line)) break; + if (!line.continues && /^#/.test(line.text)) break; + if (line.text.trim() !== "") end = j; + } + + const name = + header.match(PYTHON_DEFINITION)?.[1] ?? + (start === i ? header.match(PYTHON_ASSIGNMENT)?.[1] : undefined); + if (name) { + declarations.push(fromLines(rawLines, name, start + 1, end + 1)); + } + i = end + 1; + } + + return declarations; +} + +/** Clears the cached source indexes (for tests). */ +export function clearDeclarationCache(): void { + indexes.clear(); +} diff --git a/website/src/scripts/generate-schema-docs.ts b/website/src/scripts/generate-schema-docs.ts deleted file mode 100644 index 0d3e2a0ed..000000000 --- a/website/src/scripts/generate-schema-docs.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { readFileSync, writeFileSync } from "fs"; -import * as path from "path"; -import yaml from "js-yaml"; -import { BuildScriptUtils } from "./utils"; -import { Paths } from "../lib/schema/paths"; - -/** - * Frontmatter schema definition structure - */ -interface FrontmatterSchemaDef { - jsonSchema?: { - file?: { - path?: string; - }; - code?: string; - }; -} - -/** - * Frontmatter structure - */ -interface Frontmatter { - [key: string]: FrontmatterSchemaDef | unknown; -} - -/** - * Build-time script to generate schema documentation mapping - */ -class SchemaDocGenerator { - /** - * Main entry point - */ - static async generate(): Promise { - console.log("Generating schema documentation mapping..."); - - const startTime = Date.now(); - const mapping = new Map(); - - try { - const docsDir = Paths.PROTOCOL_DOCS_DIR; - const mdxFiles = BuildScriptUtils.findFilesByExtension(docsDir, ".mdx"); - - console.log(`Found ${mdxFiles.length} MDX files to process`); - - for (const file of mdxFiles) { - const references = this.extractSchemaReferences(file); - for (const { schemaName, docPath } of references) { - mapping.set(schemaName, docPath); - } - } - - // Convert to object for JSON serialization - const mappingObject = Object.fromEntries(mapping); - - // Write to output file - const outputPath = Paths.SCHEMA_DOCS_MAPPING; - writeFileSync(outputPath, JSON.stringify(mappingObject, null, 2)); - - const duration = Date.now() - startTime; - console.log(`Generated schema documentation mapping in ${duration}ms`); - console.log(`Mapped ${mapping.size} schemas to documentation paths`); - console.log(`Output written to: ${Paths.SCHEMA_DOCS_MAPPING}`); - } catch (error) { - BuildScriptUtils.handleError( - error, - "schema documentation mapping generation", - ); - } - } - - /** - * Extracts schema references from an MDX file's frontmatter - */ - private static extractSchemaReferences( - filePath: string, - ): Array<{ schemaName: string; docPath: string }> { - const references: Array<{ schemaName: string; docPath: string }> = []; - - try { - const content = readFileSync(filePath, "utf-8"); - const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/); - - if (!frontmatterMatch) return references; - - const frontmatterYaml = frontmatterMatch[1]; - const frontmatter = yaml.load(frontmatterYaml) as Frontmatter; - - // Convert file path to documentation URL - const relativePath = filePath.replace(Paths.CONTENT_DOCS_DIR + "/", ""); - const docPath = "/" + relativePath.replace(/\.mdx$/, ""); - - // Extract schema paths from each schema definition - for (const [, schemaDef] of Object.entries(frontmatter)) { - if ( - typeof schemaDef === "object" && - schemaDef !== null && - "jsonSchema" in schemaDef - ) { - const jsonSchema = (schemaDef as FrontmatterSchemaDef).jsonSchema; - if ( - jsonSchema?.file?.path && - typeof jsonSchema.file.path === "string" - ) { - const schemaPath = jsonSchema.file.path; - // Frontmatter paths are relative to repo root; convert - // SCHEMAS_DIR to repo-relative so the comparison works. - const relativeSchemaDir = - path.relative(Paths.REPO_ROOT, Paths.SCHEMAS_DIR) + "/"; - if (schemaPath.includes(relativeSchemaDir)) { - // Extract schema name from path - const schemaFileName = schemaPath - .split("/") - .pop() - ?.replace(".yaml", ""); - if (schemaFileName) { - references.push({ schemaName: schemaFileName, docPath }); - } - } - } else if (jsonSchema?.code) { - // Handle inline schemas (like basic types in types/ directory) - const schemaName = Object.keys(frontmatter).find( - (k) => frontmatter[k] === schemaDef, - ); - if (schemaName) { - references.push({ schemaName, docPath }); - - // Also add the actual JSON Schema type to the map - try { - const schemaCode = yaml.load(jsonSchema.code) as { - type?: string; - }; - if ( - schemaCode && - typeof schemaCode === "object" && - schemaCode.type - ) { - references.push({ schemaName: schemaCode.type, docPath }); - } - } catch (error) { - console.warn( - `Could not parse schema code for ${schemaName}: ${error}`, - ); - } - } - } - } - } - } catch (error) { - console.warn(`Could not read file ${filePath}: ${error}`); - } - - return references; - } -} - -// Run the generator if this script is executed directly -if (import.meta.url === `file://${process.argv[1]}`) { - SchemaDocGenerator.generate().catch((error) => { - console.error("Failed to generate schema documentation mapping:", error); - process.exit(1); - }); -} - -export { SchemaDocGenerator }; diff --git a/website/src/scripts/generate-schema-metadata.ts b/website/src/scripts/generate-schema-metadata.ts deleted file mode 100644 index c42ccc747..000000000 --- a/website/src/scripts/generate-schema-metadata.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { readFileSync, writeFileSync, statSync } from "fs"; -import yaml from "js-yaml"; -import { BuildScriptUtils } from "./utils"; -import { HashUtils } from "../lib/schema/hash-utils"; -import { Paths } from "../lib/schema/paths"; - -/** - * Pre-computed schema metadata - */ -interface SchemaMetadata { - schemaName: string; - filePath: string; - type: - "object" | "enum" | "array" | "string" | "number" | "boolean" | "unknown"; - isEnum: boolean; - isObject: boolean; - properties?: string[]; - enumValues?: string[]; - lastModified: number; - contentHash: string; -} - -/** - * Schema metadata collection - */ -interface SchemaMetadataCollection { - schemas: Record; - generatedAt: number; - totalSchemas: number; -} - -/** - * Build-time script to generate schema metadata - */ -class SchemaMetadataGenerator { - /** - * Main entry point - */ - static async generate(): Promise { - console.log("Generating schema metadata..."); - - const startTime = Date.now(); - const schemas: Record = {}; - - try { - const schemasDir = Paths.SCHEMAS_DIR; - const yamlFiles = BuildScriptUtils.findFilesByExtension( - schemasDir, - ".yaml", - ); - - console.log(`Found ${yamlFiles.length} YAML schema files to process`); - - for (const filePath of yamlFiles) { - const metadata = this.processSchemaFile(filePath); - if (metadata) { - schemas[metadata.schemaName] = metadata; - } - } - - const collection: SchemaMetadataCollection = { - schemas, - generatedAt: Date.now(), - totalSchemas: Object.keys(schemas).length, - }; - - // Write to output file - const outputPath = Paths.SCHEMA_METADATA; - writeFileSync(outputPath, JSON.stringify(collection, null, 2)); - - const duration = Date.now() - startTime; - console.log(`Generated schema metadata in ${duration}ms`); - console.log(`Processed ${collection.totalSchemas} schemas`); - console.log(`Output written to: ${Paths.SCHEMA_METADATA}`); - } catch (error) { - BuildScriptUtils.handleError(error, "schema metadata generation"); - } - } - - /** - * Processes a single schema file and extracts metadata - */ - private static processSchemaFile(filePath: string): SchemaMetadata | null { - try { - const content = readFileSync(filePath, "utf-8"); - const schema = yaml.load(content) as Record; - - if (!schema) { - console.warn(`Empty schema file: ${filePath}`); - return null; - } - - const schemaName = BuildScriptUtils.extractSchemaName(filePath); - const stats = statSync(filePath); - const lastModified = stats.mtime.getTime(); - - const metadata: SchemaMetadata = { - schemaName, - filePath: filePath.replace(Paths.WEBSITE_ROOT + "/", ""), - type: this.determineSchemaType(schema), - isEnum: this.isEnumSchema(schema), - isObject: this.isObjectSchema(schema), - properties: this.extractProperties(schema), - enumValues: this.extractEnumValues(schema), - lastModified, - contentHash: HashUtils.hashString(content), - }; - - return metadata; - } catch (error) { - console.warn(`Could not process schema file ${filePath}: ${error}`); - return null; - } - } - - /** - * Determines the primary type of a schema - */ - private static determineSchemaType( - schema: Record, - ): SchemaMetadata["type"] { - if (schema.type) { - return schema.type as SchemaMetadata["type"]; - } - - if (schema.enum) { - return "enum"; - } - - if (schema.properties) { - return "object"; - } - - return "unknown"; - } - - /** - * Checks if schema is an enum schema - */ - private static isEnumSchema(schema: Record): boolean { - return schema.type === "string" && Array.isArray(schema.enum); - } - - /** - * Checks if schema is an object schema - */ - private static isObjectSchema(schema: Record): boolean { - return schema.type === "object" && Boolean(schema.properties); - } - - /** - * Extracts property names from object schemas - */ - private static extractProperties( - schema: Record, - ): string[] | undefined { - if (schema.properties && typeof schema.properties === "object") { - return Object.keys(schema.properties); - } - return undefined; - } - - /** - * Extracts enum values from enum schemas - */ - private static extractEnumValues( - schema: Record, - ): string[] | undefined { - if (Array.isArray(schema.enum)) { - return schema.enum.map((value: unknown) => String(value)); - } - return undefined; - } -} - -// Run the generator if this script is executed directly -if (import.meta.url === `file://${process.argv[1]}`) { - SchemaMetadataGenerator.generate().catch((error) => { - console.error("Failed to generate schema metadata:", error); - process.exit(1); - }); -} - -export { SchemaMetadataGenerator }; diff --git a/website/src/scripts/generate-type-formatting.ts b/website/src/scripts/generate-type-formatting.ts deleted file mode 100644 index 3ed336d0d..000000000 --- a/website/src/scripts/generate-type-formatting.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { readFileSync, writeFileSync } from "fs"; -import yaml from "js-yaml"; -import { TypeFormatter } from "../lib/schema/type-formatter"; -import { SchemaDocMapper } from "../lib/schema/schema-doc-mapper"; -import { BuildScriptUtils } from "./utils"; -import { HashUtils } from "../lib/schema/hash-utils"; -import { Paths } from "../lib/schema/paths"; - -/** - * Pre-computed type formatting entry - */ -interface TypeFormattingEntry { - schemaName: string; - propertyName: string; - formattedType: string; - contentHash: string; -} - -/** - * Type formatting collection - */ -interface TypeFormattingCollection { - entries: Record; - generatedAt: number; - totalEntries: number; -} - -/** - * Build-time script to generate type formatting cache - */ -class TypeFormattingGenerator { - /** - * Main entry point - */ - static async generate(): Promise { - console.log("Generating type formatting cache..."); - - const startTime = Date.now(); - const entries: Record = {}; - - try { - // Initialize schema documentation mapping - const docMap = SchemaDocMapper.getSchemaDocMap(); - const getSchemaDocPath = (schemaName: string) => docMap.get(schemaName); - - const schemasDir = Paths.SCHEMAS_DIR; - const yamlFiles = BuildScriptUtils.findFilesByExtension( - schemasDir, - ".yaml", - ); - - console.log(`Found ${yamlFiles.length} YAML schema files to process`); - - for (const filePath of yamlFiles) { - const schemaEntries = this.processSchemaFile( - filePath, - getSchemaDocPath, - ); - Object.assign(entries, schemaEntries); - } - - const collection: TypeFormattingCollection = { - entries, - generatedAt: Date.now(), - totalEntries: Object.keys(entries).length, - }; - - // Write to output file - const outputPath = Paths.TYPE_FORMATTING_CACHE; - writeFileSync(outputPath, JSON.stringify(collection, null, 2)); - - const duration = Date.now() - startTime; - console.log(`Generated type formatting cache in ${duration}ms`); - console.log( - `Processed ${collection.totalEntries} type formatting entries`, - ); - console.log(`Output written to: ${Paths.TYPE_FORMATTING_CACHE}`); - } catch (error) { - BuildScriptUtils.handleError(error, "type formatting cache generation"); - } - } - - /** - * Processes a single schema file and generates type formatting entries - */ - private static processSchemaFile( - filePath: string, - getSchemaDocPath: (schemaName: string) => string | undefined, - ): Record { - const entries: Record = {}; - - try { - const content = readFileSync(filePath, "utf-8"); - const schema = yaml.load(content) as Record; - - if (!schema) { - console.warn(`Empty schema file: ${filePath}`); - return entries; - } - - const schemaName = BuildScriptUtils.extractSchemaName(filePath); - - // Process object schemas with properties - if (schema.type === "object" && schema.properties) { - for (const [propertyName, propertySchema] of Object.entries( - schema.properties, - )) { - const formattedType = TypeFormatter.formatPropertyType( - propertySchema as Record, - schema, - getSchemaDocPath, - ); - - const entryKey = `${schemaName}.${propertyName}`; - entries[entryKey] = { - schemaName, - propertyName, - formattedType, - contentHash: HashUtils.hashString(content), - }; - } - } - - // Process allOf schemas - if (schema.allOf && Array.isArray(schema.allOf)) { - for (const allOfItem of schema.allOf) { - if (allOfItem.properties) { - for (const [propertyName, propertySchema] of Object.entries( - allOfItem.properties, - )) { - const formattedType = TypeFormatter.formatPropertyType( - propertySchema as Record, - schema, - getSchemaDocPath, - ); - - const entryKey = `${schemaName}.${propertyName}`; - entries[entryKey] = { - schemaName, - propertyName, - formattedType, - contentHash: HashUtils.hashString(content), - }; - } - } - } - } - } catch (error) { - console.warn(`Could not process schema file ${filePath}: ${error}`); - } - - return entries; - } -} - -// Run the generator if this script is executed directly -if (import.meta.url === `file://${process.argv[1]}`) { - TypeFormattingGenerator.generate().catch((error) => { - console.error("Failed to generate type formatting cache:", error); - process.exit(1); - }); -} - -export { TypeFormattingGenerator }; From 65baa5404df9cfe8a012b0def5a85c9172d6792b Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Thu, 19 Nov 2026 12:44:56 -0800 Subject: [PATCH 07/20] docs(website): protocol pages name their schemas instead of line ranges Each protocol page now names the schema in and , and the code tabs show the whole declaration found by name. About 100 tabs that were cut off, shifted or showing other code now show the right declaration, and a schema or snippet that can't be found fails the build. The schema-to-page map that links table types to their pages is built from the pages during the site build, so generate-schema-docs.ts goes, along with generate-schema-metadata.ts, generate-type-formatting.ts and SchemaMetadataLoader, whose output nothing read. Closes #872 --- .../conformance/competition-versions.spec.ts | 87 ++-- .../lib/schema/schema-doc-mapper.spec.ts | 122 +++++ website/package.json | 5 +- website/src/components/SchemaFormatTabs.astro | 160 +++---- website/src/components/SchemaTable.astro | 15 +- .../content/docs/protocol/fields/address.mdx | 40 +- .../docs/protocol/fields/custom-field.mdx | 56 +-- .../content/docs/protocol/fields/email.mdx | 32 +- .../content/docs/protocol/fields/event.mdx | 181 +------- .../docs/protocol/fields/extensible-enum.mdx | 26 +- .../src/content/docs/protocol/fields/file.mdx | 20 +- .../docs/protocol/fields/identifier.mdx | 59 +-- .../content/docs/protocol/fields/metadata.mdx | 32 +- .../content/docs/protocol/fields/money.mdx | 32 +- .../src/content/docs/protocol/fields/name.mdx | 20 +- .../src/content/docs/protocol/fields/pcs.mdx | 126 +----- .../content/docs/protocol/fields/phone.mdx | 40 +- .../content/docs/protocol/filters/base.mdx | 185 +------- .../content/docs/protocol/filters/boolean.mdx | 30 +- .../content/docs/protocol/filters/date.mdx | 60 +-- .../content/docs/protocol/filters/money.mdx | 60 +-- .../content/docs/protocol/filters/numeric.mdx | 90 +--- .../content/docs/protocol/filters/string.mdx | 60 +-- .../docs/protocol/models/applicant-type.mdx | 38 +- .../docs/protocol/models/application.mdx | 76 +--- .../content/docs/protocol/models/award.mdx | 182 +------- .../docs/protocol/models/competition.mdx | 75 +--- .../docs/protocol/models/form-response.mdx | 44 +- .../src/content/docs/protocol/models/form.mdx | 41 +- .../content/docs/protocol/models/mapping.mdx | 70 +-- .../docs/protocol/models/opportunity.mdx | 256 +---------- .../docs/protocol/models/organization.mdx | 415 ++---------------- .../content/docs/protocol/models/person.mdx | 14 +- .../content/docs/protocol/models/proposal.mdx | 70 +-- .../content/docs/protocol/models/revision.mdx | 78 +--- .../src/content/docs/protocol/pagination.mdx | 90 +--- .../content/docs/protocol/responses/error.mdx | 54 +-- .../docs/protocol/responses/filtered.mdx | 26 +- .../docs/protocol/responses/paginated.mdx | 26 +- .../docs/protocol/responses/sorted.mdx | 26 +- .../docs/protocol/responses/success.mdx | 70 +-- website/src/content/docs/protocol/sorting.mdx | 121 +---- .../src/content/docs/protocol/types/date.mdx | 80 +--- .../content/docs/protocol/types/numeric.mdx | 19 +- .../content/docs/protocol/types/string.mdx | 114 +---- website/src/lib/schema/schema-doc-mapper.ts | 142 ++++-- 46 files changed, 671 insertions(+), 2994 deletions(-) create mode 100644 website/__tests__/lib/schema/schema-doc-mapper.spec.ts diff --git a/website/__tests__/lib/mock/conformance/competition-versions.spec.ts b/website/__tests__/lib/mock/conformance/competition-versions.spec.ts index 75e62d0f8..199428c26 100644 --- a/website/__tests__/lib/mock/conformance/competition-versions.spec.ts +++ b/website/__tests__/lib/mock/conformance/competition-versions.spec.ts @@ -19,6 +19,7 @@ import { describe, it, expect } from "vitest"; import yaml from "js-yaml"; import type { Version } from "@/lib/mock/data/fixtures"; import { resolveSchemaRefs } from "@/lib/schema/ref-resolver"; +import { schemaFilePath } from "@/lib/schema/schema-files"; import { getValidator } from "./schema-validator"; const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -319,20 +320,47 @@ describe("the unversioned CompetitionBase authoring schema", () => { // authoring schema, whose references resolve where it is served. describe("the Form and Competition docs pages", () => { const REPO_ROOT = path.resolve(HERE, "../../../../.."); - const page = readFileSync( - path.join(REPO_ROOT, "website/src/content/docs/protocol/models/form.mdx"), - "utf-8", - ); + const readPage = (model: string) => + readFileSync( + path.join( + REPO_ROOT, + `website/src/content/docs/protocol/models/${model}.mdx`, + ), + "utf-8", + ); + const page = readPage("form"); const { form } = yaml.load(page.split("---")[1]) as { - form: { - example: { code: string }; - table: { file: { path: string } }; - jsonSchema: { file: { path: string } }; - }; + form: { example: { code: string } }; }; const load = (repoPath: string) => yaml.load(readFileSync(path.join(REPO_ROOT, repoPath), "utf-8")) as Schema; + /** + * The files a page's table and JSON Schema tab read for a schema. A + * `` with a `version` reads that version's copy; the + * `` JSON Schema tab reads the unversioned file. + */ + const filesFor = (pageText: string, schema: string) => { + const tag = (component: string) => + pageText.match( + new RegExp(`<${component}\\b[^>]*\\bschema="${schema}"[^>]*>`), + )?.[0]; + const table = tag("SchemaTable"); + const tabs = tag("SchemaFormatTabs"); + expect(table, `a SchemaTable for ${schema}`).toBeDefined(); + expect(tabs, `a SchemaFormatTabs for ${schema}`).toBeDefined(); + expect( + tabs, + "the tabs take their JSON Schema from the schema file", + ).not.toMatch(/\bjsonSchema=/); + const version = table!.match(/\bversion="([^"]+)"/)?.[1]; + return { + table: version ? schemaFilePath(schema, version) : schemaFilePath(schema), + jsonSchema: schemaFilePath(schema), + }; + }; + const formFiles = filesFor(page, "FormBase"); + it("shows exactly the v0.5 FormBase example", () => { expect(JSON.parse(form.example.code)).toEqual( exampleOf(requireSchema("jsonSchema", "0.5.0", "FormBase")), @@ -340,58 +368,37 @@ describe("the Form and Competition docs pages", () => { }); it("renders the table from the v0.5 schema, which requires title alone", () => { - expect(page).toContain( - "", - ); - expect(form.table.file.path).toBe( + expect(formFiles.table).toBe( "website/public/schemas/yaml/versions/v0.5.0/FormBase.yaml", ); - const table = load(form.table.file.path); + const table = load(formFiles.table); expect(table.required).toContain("title"); expect(table.required).not.toContain("name"); }); it("renders the Competition table from the v0.5 schema, which requires opportunity alone", () => { - const competitionPage = readFileSync( - path.join( - REPO_ROOT, - "website/src/content/docs/protocol/models/competition.mdx", - ), - "utf-8", - ); - const { competition } = yaml.load(competitionPage.split("---")[1]) as { - competition: { table: { file: { path: string } } }; - }; - expect(competitionPage).toContain( - "", - ); - expect(competition.table.file.path).toBe( + const competition = filesFor(readPage("competition"), "CompetitionBase"); + expect(competition.table).toBe( "website/public/schemas/yaml/versions/v0.5.0/CompetitionBase.yaml", ); - const table = load(competition.table.file.path); + const table = load(competition.table); expect(table.required).toContain("opportunity"); expect(table.required).not.toContain("opportunityId"); }); it("keeps the JSON Schema tab on the unversioned authoring schema", () => { - expect(form.jsonSchema.file.path).toBe( + expect(formFiles.jsonSchema).toBe( "website/public/schemas/yaml/FormBase.yaml", ); - expect(form.jsonSchema.file.path).not.toBe(form.table.file.path); - expect(load(form.jsonSchema.file.path).required).toEqual( + expect(formFiles.jsonSchema).not.toBe(formFiles.table); + expect(load(formFiles.jsonSchema).required).toEqual( expect.arrayContaining(["name", "title"]), ); }); /** The served file a model page tells readers to validate payloads with. */ const validationTarget = (model: string) => { - const text = readFileSync( - path.join( - REPO_ROOT, - `website/src/content/docs/protocol/models/${model}.mdx`, - ), - "utf-8", - ); + const text = readPage(model); const target = text.match( /To validate a payload, use [^`]*`(\/[^`]+)`/, )?.[1]; @@ -401,7 +408,7 @@ describe("the Form and Competition docs pages", () => { it("links and recommends only files a normal resolver can follow", async () => { for (const download of [ - form.jsonSchema.file.path, + formFiles.jsonSchema, validationTarget("form"), validationTarget("competition"), ]) { diff --git a/website/__tests__/lib/schema/schema-doc-mapper.spec.ts b/website/__tests__/lib/schema/schema-doc-mapper.spec.ts new file mode 100644 index 000000000..3b2207a81 --- /dev/null +++ b/website/__tests__/lib/schema/schema-doc-mapper.spec.ts @@ -0,0 +1,122 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import * as path from "path"; +import { + buildSchemaDocMap, + SchemaDocMapper, +} from "@/lib/schema/schema-doc-mapper"; + +describe("buildSchemaDocMap", () => { + let contentDir: string; + + /** Writes a page under the temporary docs directory. */ + function writePage(relativePath: string, content: string): void { + const file = path.join(contentDir, relativePath); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, content); + } + + beforeAll(() => { + contentDir = mkdtempSync(path.join(tmpdir(), "schema-doc-map-")); + + writePage( + "protocol/models/award.mdx", + [ + "---", + "title: Award", + "---", + "", + "## AwardBase", + "", + '', + "", + "", + "", + "## AwdIds", + "", + '', + "", + "## A template, which has no JSON Schema", + "", + '', + ].join("\n"), + ); + + writePage( + "protocol/types/string.mdx", + [ + "---", + "title: String types", + "url:", + " jsonSchema:", + " code: |", + " $id: url.yaml", + " type: string", + "---", + "", + "", + "", + '', + ].join("\n"), + ); + + // Sorts before types/, so types/string.mdx wins for `email`. + writePage( + "protocol/fields/email.mdx", + '\n', + ); + }); + + afterAll(() => { + rmSync(contentDir, { recursive: true, force: true }); + }); + + it("maps each schema a page names to that page", () => { + const map = buildSchemaDocMap( + path.join(contentDir, "protocol"), + contentDir, + ); + expect(map.get("AwardBase")).toBe("/protocol/models/award"); + expect(map.get("AwdIds")).toBe("/protocol/models/award"); + expect(map.get("ExtensibleEnumT")).toBeUndefined(); + }); + + it("maps an inline schema's JSON type to its page as well", () => { + const map = buildSchemaDocMap( + path.join(contentDir, "protocol"), + contentDir, + ); + expect(map.get("url")).toBe("/protocol/types/string"); + expect(map.get("string")).toBe("/protocol/types/string"); + }); + + it("lets the later page win when two pages name the same schema", () => { + const map = buildSchemaDocMap( + path.join(contentDir, "protocol"), + contentDir, + ); + expect(map.get("email")).toBe("/protocol/types/string"); + }); +}); + +describe("SchemaDocMapper", () => { + it("builds the map from the real protocol pages", () => { + SchemaDocMapper.clearCache(); + expect(SchemaDocMapper.getSchemaDocPath("OrgRef")).toBe( + "/protocol/models/organization", + ); + expect(SchemaDocMapper.getSchemaDocPath("Money")).toBe( + "/protocol/fields/money", + ); + expect(SchemaDocMapper.getSchemaDocPath("PaginatedResultsInfo")).toBe( + "/protocol/pagination", + ); + expect(SchemaDocMapper.getSchemaDocPath("string")).toBe( + "/protocol/types/string", + ); + }); +}); diff --git a/website/package.json b/website/package.json index 80e93bd22..c63666d1b 100644 --- a/website/package.json +++ b/website/package.json @@ -14,10 +14,7 @@ "typespec:prune-tags": "tsx src/scripts/prune-openapi-tags.ts", "typespec:extensions": "tsp compile src/specs/extensions/index.tsp --emit @typespec/json-schema --option \"@typespec/json-schema.seal-object-schemas=false\" && mkdir -p .extension-schemas && cp tsp-output/@typespec/json-schema/** .extension-schemas", "typespec:clear-output": "rm -rf tsp-output && rm -rf public/schemas/yaml/* && rm -rf public/openapi/* && rm -rf .extension-schemas", - "generate": "pnpm generate:schema-docs && pnpm generate:schema-metadata && pnpm generate:type-formatting && pnpm generate:versioned-schemas && pnpm generate:plugin-metadata && pnpm generate:mock-server", - "generate:schema-docs": "tsx src/scripts/generate-schema-docs.ts", - "generate:schema-metadata": "tsx src/scripts/generate-schema-metadata.ts", - "generate:type-formatting": "tsx src/scripts/generate-type-formatting.ts", + "generate": "pnpm generate:versioned-schemas && pnpm generate:plugin-metadata && pnpm generate:mock-server", "generate:versioned-schemas": "tsx src/scripts/generate-versioned-schemas.ts", "generate:plugin-metadata": "tsx src/scripts/fetch-plugin-metadata.ts", "generate:mock-server": "tsx src/scripts/inject-mock-server.ts", diff --git a/website/src/components/SchemaFormatTabs.astro b/website/src/components/SchemaFormatTabs.astro index 68642bb5c..1b66a7854 100644 --- a/website/src/components/SchemaFormatTabs.astro +++ b/website/src/components/SchemaFormatTabs.astro @@ -5,46 +5,68 @@ import { readFileSync } from "fs"; import { join } from "path"; import { Paths } from "../lib/schema/paths"; import { generateSchemaExample } from "../lib/schema/example-generator"; +import { schemaFilePath } from "../lib/schema/schema-files"; +import { + findSnippet, + sourceUrl, + type SourceLanguage, +} from "../lib/schema/source-declarations"; /** - * Configuration for a code block to be displayed in a tab. - * Either provide a literal code string or a file path with optional line range. + * A literal code block, or a file to read whole. Pages give literal code for + * hand-written examples and inline JSON Schemas; the custom field catalog + * gives a file. */ interface CodeBlockConfig { - /** A literal code block to display. If provided, file properties are ignored. */ + /** A literal code block to display. If provided, file is ignored. */ code?: string; - /** Configuration for reading code from a file */ + /** A file to display, by its path relative to the repository root */ file?: { - /** Path to the file relative to the repository root */ path: string; - /** Starting line number (1-based) to extract code from */ - startLine?: number; - /** Ending line number (1-based) to extract code from */ - endLine?: number; }; } +/** + * A source code tab: `true` shows the declaration named after the schema + * (`Money` in TypeSpec and Python, `MoneySchema` in TypeScript); a string + * names the declaration to show, for code named differently from the schema; + * a list of names shows several declarations from one file, such as a + * template and the model built from it. + */ +type SourceTab = true | string | string[]; + /** * Props for the SchemaFormatTabs component. - * Each prop represents a different tab that can be displayed. + * + * Name a schema with `schema` and the Example and JSON Schema tabs come from + * its generated JSON Schema file. Each source tab listed is found by name in + * the TypeSpec or SDK source; the build fails if it can't be found. */ interface Props { - /** Example JSON code block to display in the "Example" tab */ + /** The schema's name, which is also the name of its generated JSON Schema file */ + schema?: string; + /** Example JSON: literal code overrides the example generated from the schema */ example?: CodeBlockConfig; - /** JSON Schema code block to display in the "JSON Schema" tab */ + /** JSON Schema: literal code for schemas with no generated file */ jsonSchema?: CodeBlockConfig; - /** TypeSpec code block to display in the "TypeSpec" tab */ - typeSpec?: CodeBlockConfig; - /** Python code block to display in the "Python" tab */ - python?: CodeBlockConfig; - /** TypeScript code block to display in the "TypeScript" tab */ - typescript?: CodeBlockConfig; + /** TypeSpec tab */ + typeSpec?: SourceTab; + /** Python tab */ + python?: SourceTab; + /** TypeScript tab */ + typescript?: SourceTab; } -const { example, jsonSchema, typeSpec, python, typescript } = Astro.props; +const { schema, example, jsonSchema, typeSpec, python, typescript } = + Astro.props; + +// The schema file the Example and JSON Schema tabs read, if the page named one +const schemaPath = schema && !jsonSchema ? schemaFilePath(schema) : undefined; +const jsonSchemaConfig: CodeBlockConfig | undefined = + jsonSchema ?? (schemaPath ? { file: { path: schemaPath } } : undefined); // Validate that at least one tab is provided -if (!example && !jsonSchema && !typeSpec && !python) { +if (!example && !jsonSchemaConfig && !typeSpec && !python && !typescript) { throw new Error("SchemaFormatTabs requires at least one tab to be provided"); } @@ -52,16 +74,33 @@ const exampleCode = example?.code ? example.code : example?.file?.path ? await generateSchemaExample(example.file.path) - : null; -const jsonSchemaCode = jsonSchema ? extractCode(jsonSchema) : null; -const typeSpecCode = typeSpec ? extractCode(typeSpec) : null; -const pythonCode = python ? extractCode(python) : null; -const typescriptCode = typescript ? extractCode(typescript) : null; + : schemaPath + ? await generateSchemaExample(schemaPath) + : null; +const jsonSchemaCode = jsonSchemaConfig ? extractCode(jsonSchemaConfig) : null; +const jsonSchemaUrl = jsonSchemaConfig + ? extractSchemaUrl(jsonSchemaConfig) + : null; + +const typeSpecSnippet = snippet("typeSpec", typeSpec); +const pythonSnippet = snippet("python", python); +const typescriptSnippet = snippet("typescript", typescript); -const jsonSchemaUrl = jsonSchema ? extractSchemaUrl(jsonSchema) : null; -const typeSpecUrl = typeSpec ? extractGithubUrl(typeSpec) : null; -const pythonUrl = python ? extractGithubUrl(python) : null; -const typescriptUrl = typescript ? extractGithubUrl(typescript) : null; +/** + * Finds the declaration a source tab shows. + * @returns The declaration's code and a link to it, or null if the tab isn't shown + * @throws Error if the declaration can't be found + */ +function snippet( + language: SourceLanguage, + requested: SourceTab | undefined, +): { code: string; url: string } | null { + if (!requested) { + return null; + } + const declaration = findSnippet(language, requested, schema); + return { code: declaration.code, url: sourceUrl(declaration) }; +} /** * Constructs a schema URL from file path. @@ -89,31 +128,6 @@ function extractSchemaUrl(props: CodeBlockConfig): string | null { return `/${filePath}`; } -/** - * Extracts a GitHub URL from file configuration. - * @param props - The code block configuration - * @returns The GitHub URL for the file, or null if no file is specified - */ -function extractGithubUrl(props: CodeBlockConfig): string | null { - if (!props.file) { - return null; - } - - const baseUrl = "https://github.com/HHS/simpler-grants-protocol/tree/main/"; - let url = `${baseUrl}/${props.file.path}`; - - if (props.file.startLine || props.file.endLine) { - const start = props.file.startLine || 1; - const end = props.file.endLine || start; - url += `#L${start}`; - if (end > start) { - url += `-L${end}`; - } - } - - return url; -} - /** * Extracts code from either a literal string or a file. * @param props - The code block configuration @@ -126,17 +140,7 @@ function extractCode(props: CodeBlockConfig): string { } if (props.file) { try { - const filePath = join(Paths.REPO_ROOT, props.file.path); - const content = readFileSync(filePath, "utf-8"); - - if (props.file.startLine || props.file.endLine) { - const lines = content.split("\n"); - const start = props.file.startLine ? props.file.startLine - 1 : 0; - const end = props.file.endLine ? props.file.endLine : lines.length; - return lines.slice(start, end).join("\n"); - } - - return content; + return readFileSync(join(Paths.REPO_ROOT, props.file.path), "utf-8"); } catch (error) { throw new Error(`Error reading file ${props.file.path}: ${error}`, { cause: error, @@ -177,44 +181,52 @@ function extractCode(props: CodeBlockConfig): string { ) } { - typeSpecCode && ( + typeSpecSnippet && (

{"The "} - + TypeSpec code {" for this model."}

- +
) } { - pythonCode && ( + pythonSnippet && (

{"The "} - + Python code {" for this model."}

- +
) } { - typescriptCode && ( + typescriptSnippet && (

{"The "} - + TypeScript code {" for this model."}

- +
) } diff --git a/website/src/components/SchemaTable.astro b/website/src/components/SchemaTable.astro index e83e1bbb9..aaedf1107 100644 --- a/website/src/components/SchemaTable.astro +++ b/website/src/components/SchemaTable.astro @@ -3,16 +3,19 @@ import { SchemaLoader } from "../lib/schema/schema-loader"; import type { JsonSchema } from "../lib/schema/schema-loader"; import { SchemaDocMapper } from "../lib/schema/schema-doc-mapper"; import { TableGenerator } from "../lib/schema/table-generator"; +import { schemaFilePath } from "../lib/schema/schema-files"; import type { PropertyRow, EnumRow } from "../lib/schema/table-generator"; -const { filePath, code } = Astro.props; +const { schema, version, code } = Astro.props; /** * Props for the SchemaTable component. */ interface Props { - /** Path to the schema file relative to the repository root */ - filePath?: string; + /** The schema's name, which is also the name of its generated JSON Schema file */ + schema?: string; + /** Read the schema's copy for one protocol version (e.g. "v0.5.0") instead */ + version?: string; /** Inline schema code (YAML string) */ code?: string; } @@ -29,12 +32,12 @@ const getSchemaDocPath = (schemaName: string): string | undefined => { // Load and parse the schema let schemaData: JsonSchema; try { - if (filePath) { - schemaData = SchemaLoader.loadSchema(filePath); + if (schema) { + schemaData = SchemaLoader.loadSchema(schemaFilePath(schema, version)); } else if (code) { schemaData = SchemaLoader.loadInlineSchema(code); } else { - throw new Error("Either filePath or code must be provided"); + throw new Error("Either schema or code must be provided"); } } catch (error) { console.error(`Loading schema:`, error); diff --git a/website/src/content/docs/protocol/fields/address.mdx b/website/src/content/docs/protocol/fields/address.mdx index 0f59a849a..1936a6211 100644 --- a/website/src/content/docs/protocol/fields/address.mdx +++ b/website/src/content/docs/protocol/fields/address.mdx @@ -1,30 +1,6 @@ --- title: Address description: Data model for an address -address: - example: - file: - path: "website/public/schemas/yaml/Address.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Address.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/address.tsp" - startLine: 3 - endLine: 33 -addressCollection: - example: - file: - path: "website/public/schemas/yaml/AddressCollection.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AddressCollection.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/address.tsp" - startLine: 35 - endLine: 45 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -35,15 +11,11 @@ An address is a physical location. ### Table - + ### Formats - + ### Changelog @@ -55,15 +27,11 @@ A collection of addresses for a person or organization. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/custom-field.mdx b/website/src/content/docs/protocol/fields/custom-field.mdx index a50b4d83b..8f1363564 100644 --- a/website/src/content/docs/protocol/fields/custom-field.mdx +++ b/website/src/content/docs/protocol/fields/custom-field.mdx @@ -1,49 +1,9 @@ --- title: CustomField description: A model for defining custom fields that are specific to a given implementation -customField: - example: - file: - path: "website/public/schemas/yaml/CustomField.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/CustomField.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/custom-field.tsp" - startLine: 47 - endLine: 64 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/custom.py" - startLine: 23 - endLine: 45 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 103 - endLine: 118 customFieldType: example: code: "string" - jsonSchema: - file: - path: "website/public/schemas/yaml/CustomFieldType.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/custom-field.tsp" - startLine: 7 - endLine: 16 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/custom.py" - startLine: 12 - endLine: 20 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 94 - endLine: 101 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -65,13 +25,7 @@ A model for defining custom fields on a record. ### Formats - + ### Changelog @@ -95,11 +49,11 @@ The set of JSON schema types supported by a custom field. ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/fields/email.mdx b/website/src/content/docs/protocol/fields/email.mdx index 81d558beb..fdf2eab35 100644 --- a/website/src/content/docs/protocol/fields/email.mdx +++ b/website/src/content/docs/protocol/fields/email.mdx @@ -4,26 +4,6 @@ description: Data model for an email address email: example: code: '"john.doe@example.com"' - jsonSchema: - file: - path: "website/public/schemas/yaml/email.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/email.tsp" - startLine: 5 - endLine: 6 -emailCollection: - example: - file: - path: "website/public/schemas/yaml/EmailCollection.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/EmailCollection.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/email.tsp" - startLine: 8 - endLine: 17 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -35,9 +15,9 @@ An email address. Alias for the [email](/protocol/types/string#email) type. ### Formats ## EmailCollection @@ -46,15 +26,11 @@ A collection of email addresses for a person or organization. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/event.mdx b/website/src/content/docs/protocol/fields/event.mdx index 86be00d56..450493ad7 100644 --- a/website/src/content/docs/protocol/fields/event.mdx +++ b/website/src/content/docs/protocol/fields/event.mdx @@ -1,138 +1,6 @@ --- title: Event description: A comprehensive model for representing various types of events with dates, date ranges, and custom event types -eventType: - example: - file: - path: "website/public/schemas/yaml/EventType.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/EventType.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/event.tsp" - startLine: 11 - endLine: 27 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/event.py" - startLine: 13 - endLine: 18 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 15 - endLine: 15 -event: - example: - file: - path: "website/public/schemas/yaml/Event.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Event.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/event.tsp" - startLine: 33 - endLine: 45 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/event.py" - startLine: 104 - endLine: 104 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 72 - endLine: 76 -eventBase: - example: - file: - path: "website/public/schemas/yaml/EventBase.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/EventBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/event.tsp" - startLine: 51 - endLine: 62 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/event.py" - startLine: 22 - endLine: 38 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 18 - endLine: 27 -singleDateEvent: - example: - file: - path: "website/public/schemas/yaml/SingleDateEvent.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SingleDateEvent.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/event.tsp" - startLine: 68 - endLine: 81 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/event.py" - startLine: 42 - endLine: 56 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 30 - endLine: 39 -dateRangeEvent: - example: - file: - path: "website/public/schemas/yaml/DateRangeEvent.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/DateRangeEvent.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/event.tsp" - startLine: 86 - endLine: 106 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/event.py" - startLine: 60 - endLine: 86 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 42 - endLine: 57 -otherEvent: - example: - file: - path: "website/public/schemas/yaml/OtherEvent.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OtherEvent.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/event.tsp" - startLine: 112 - endLine: 125 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/event.py" - startLine: 90 - endLine: 100 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 60 - endLine: 69 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -155,11 +23,10 @@ Defines the different types of events that can be represented ### Formats ### Changelog @@ -180,13 +47,7 @@ The `Event` union represents all possible event types. ### Formats - + {/* TODO: Add changelog once unions are supported */} @@ -204,13 +65,7 @@ Base model for all events with common properties ### Formats - + ### Changelog @@ -232,13 +87,7 @@ Represents an event that has a specific date (and optional time) associated with ### Formats - + ### Changelog @@ -262,13 +111,7 @@ Represents an event that spans a period of time with start and end dates (and op ### Formats - + ### Changelog @@ -289,13 +132,7 @@ Represents custom events that don't fit the single date or date range patterns. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/extensible-enum.mdx b/website/src/content/docs/protocol/fields/extensible-enum.mdx index 15a755c12..1ee78dbd0 100644 --- a/website/src/content/docs/protocol/fields/extensible-enum.mdx +++ b/website/src/content/docs/protocol/fields/extensible-enum.mdx @@ -1,24 +1,6 @@ --- title: ExtensibleEnum description: A value from a predefined set of options, with support for custom values -extensibleEnum: - example: - file: - path: "website/public/schemas/yaml/ExtensibleEnum.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/ExtensibleEnum.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/extensible-enum.tsp" - startLine: 39 - endLine: 47 -extensibleEnumT: - typeSpec: - file: - path: "lib/core/lib/core/fields/extensible-enum.tsp" - startLine: 7 - endLine: 37 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -51,7 +33,7 @@ model OppStatus is Fields.ExtensibleEnumT; ### Formats - + ## ExtensibleEnum @@ -68,11 +50,7 @@ The base model for this pattern, derived from the template with an unconstrained ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/file.mdx b/website/src/content/docs/protocol/fields/file.mdx index a0a48dcca..e14b7db49 100644 --- a/website/src/content/docs/protocol/fields/file.mdx +++ b/website/src/content/docs/protocol/fields/file.mdx @@ -1,18 +1,6 @@ --- title: File description: Data model for a file attachment. -file: - example: - file: - path: "website/public/schemas/yaml/File.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/File.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/file.tsp" - startLine: 3 - endLine: 25 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -23,15 +11,11 @@ A file attachment. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/identifier.mdx b/website/src/content/docs/protocol/fields/identifier.mdx index 38e90c4b5..4bf99230b 100644 --- a/website/src/content/docs/protocol/fields/identifier.mdx +++ b/website/src/content/docs/protocol/fields/identifier.mdx @@ -1,42 +1,6 @@ --- title: Identifier description: Models for representing registry-issued identifiers on a record -identifier: - example: - file: - path: "website/public/schemas/yaml/Identifier.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Identifier.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/identifier.tsp" - startLine: 17 - endLine: 62 -systemId: - example: - file: - path: "website/public/schemas/yaml/SystemId.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SystemId.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/identifier.tsp" - startLine: 64 - endLine: 71 -identifierCollection: - example: - file: - path: "website/public/schemas/yaml/IdentifierCollection.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/IdentifierCollection.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/identifier.tsp" - startLine: 77 - endLine: 88 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -55,14 +19,13 @@ Identifiers are keyed by their canonical CommonGrants registry code ### Table - + ### Formats ### Changelog @@ -78,15 +41,11 @@ through their `systemId` field. ### Table - + ### Formats - + ### Changelog @@ -102,15 +61,11 @@ and [OppIds](/protocol/models/opportunity#oppids)) extend it with their base ide ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/metadata.mdx b/website/src/content/docs/protocol/fields/metadata.mdx index f98e4b6be..3026eaf41 100644 --- a/website/src/content/docs/protocol/fields/metadata.mdx +++ b/website/src/content/docs/protocol/fields/metadata.mdx @@ -1,28 +1,6 @@ --- title: SystemMetadata description: System-managed metadata for records -systemMetadata: - example: - file: - path: "website/public/schemas/yaml/SystemMetadata.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SystemMetadata.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/metadata.tsp" - startLine: 21 - endLine: 31 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/metadata.py" - startLine: 10 - endLine: 22 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 124 - endLine: 130 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -33,17 +11,11 @@ System-managed metadata that is automatically added to records. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/money.mdx b/website/src/content/docs/protocol/fields/money.mdx index dedf1c253..fa73cf02c 100644 --- a/website/src/content/docs/protocol/fields/money.mdx +++ b/website/src/content/docs/protocol/fields/money.mdx @@ -1,28 +1,6 @@ --- title: Money description: A model for representing monetary values -money: - example: - file: - path: "website/public/schemas/yaml/Money.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Money.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/money.tsp" - startLine: 21 - endLine: 29 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/fields/money.py" - startLine: 10 - endLine: 22 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/fields.ts" - startLine: 82 - endLine: 88 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -33,17 +11,11 @@ A monetary amount and the currency in which it is denominated. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/name.mdx b/website/src/content/docs/protocol/fields/name.mdx index aed17aad2..32acb60bf 100644 --- a/website/src/content/docs/protocol/fields/name.mdx +++ b/website/src/content/docs/protocol/fields/name.mdx @@ -1,18 +1,6 @@ --- title: Name description: Data model for a person's name -name: - example: - file: - path: "website/public/schemas/yaml/Name.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Name.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/name.tsp" - startLine: 3 - endLine: 21 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -23,15 +11,11 @@ A person's name. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/fields/pcs.mdx b/website/src/content/docs/protocol/fields/pcs.mdx index 57f44e477..6eb0c0e52 100644 --- a/website/src/content/docs/protocol/fields/pcs.mdx +++ b/website/src/content/docs/protocol/fields/pcs.mdx @@ -1,90 +1,6 @@ --- title: PCS term description: A Philanthropy Classification System (PCS) term. -pcsTerm: - example: - file: - path: "website/public/schemas/yaml/PCSTerm.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSTerm.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 15 - endLine: 32 -pcsClass: - example: - file: - path: "website/public/schemas/yaml/PCSClass.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSClass.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 37 - endLine: 46 -pcsOrgType: - example: - file: - path: "website/public/schemas/yaml/PCSOrgType.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSOrgType.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 51 - endLine: 59 -pcsSubject: - example: - file: - path: "website/public/schemas/yaml/PCSSubject.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSSubject.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 61 - endLine: 69 -pcsPopulation: - example: - file: - path: "website/public/schemas/yaml/PCSPopulation.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSPopulation.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 71 - endLine: 79 -pcsSupportStrategy: - example: - file: - path: "website/public/schemas/yaml/PCSSupportStrategy.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSSupportStrategy.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 81 - endLine: 89 -pcsTransactionType: - example: - file: - path: "website/public/schemas/yaml/PCSTransactionType.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PCSTransactionType.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/pcs.tsp" - startLine: 91 - endLine: 99 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -107,11 +23,7 @@ Visit [taxonomy.candid.org](https://taxonomy.candid.org/) for more information. ### Formats - + ### Changelog @@ -133,11 +45,7 @@ The class to which the PCS term belongs. ### Formats - + ## Sub-types @@ -155,11 +63,7 @@ A [PCSTerm](#pcsterm) where the `class` is `"Organization types"`. Categorizes t See [PCS organization types](https://taxonomy.candid.org/organization-type) for more information. - + ### PCSSubject @@ -167,11 +71,7 @@ A [PCSTerm](#pcsterm) where the `class` is `"Subjects"`. Categorizes the subject See [PCS subjects](https://taxonomy.candid.org/subject) for more information. - + ### PCSPopulation @@ -179,11 +79,7 @@ A [PCSTerm](#pcsterm) where the `class` is `"Population groups"`. Categorizes th See [PCS population groups](https://taxonomy.candid.org/population-group) for more information. - + ### PCSSupportStrategy @@ -191,11 +87,7 @@ A [PCSTerm](#pcsterm) where the `class` is `"Support strategies"`. Categorizes t See [PCS support strategies](https://taxonomy.candid.org/support-strategy) for more information. - + ### PCSTransactionType @@ -203,8 +95,4 @@ A [PCSTerm](#pcsterm) where the `class` is `"Transaction types"`. Categorizes th See [PCS transaction types](https://taxonomy.candid.org/transaction-type) for more information. - + diff --git a/website/src/content/docs/protocol/fields/phone.mdx b/website/src/content/docs/protocol/fields/phone.mdx index d0762f7af..25e6d4cf8 100644 --- a/website/src/content/docs/protocol/fields/phone.mdx +++ b/website/src/content/docs/protocol/fields/phone.mdx @@ -1,30 +1,6 @@ --- title: Phone description: A model for representing a phone number -phone: - example: - file: - path: "website/public/schemas/yaml/Phone.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Phone.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/phone.tsp" - startLine: 3 - endLine: 20 -phoneCollection: - example: - file: - path: "website/public/schemas/yaml/PhoneCollection.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PhoneCollection.yaml" - typeSpec: - file: - path: "lib/core/lib/core/fields/phone.tsp" - startLine: 26 - endLine: 39 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -35,15 +11,11 @@ A phone number. ### Table - + ### Formats - + ### Changelog @@ -55,15 +27,11 @@ A collection of phone numbers for a person or organization. ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/filters/base.mdx b/website/src/content/docs/protocol/filters/base.mdx index f69ac5068..0502c4f77 100644 --- a/website/src/content/docs/protocol/filters/base.mdx +++ b/website/src/content/docs/protocol/filters/base.mdx @@ -1,138 +1,6 @@ --- title: Base filters description: Base models used to build field-specific filters. -defaultFilter: - example: - file: - path: "website/public/schemas/yaml/DefaultFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/DefaultFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/base.tsp" - startLine: 75 - endLine: 89 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/base.py" - startLine: 57 - endLine: 70 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 30 - endLine: 33 -equivalenceOperators: - example: - file: - path: "website/public/schemas/yaml/EquivalenceOperators.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/EquivalenceOperators.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/base.tsp" - startLine: 7 - endLine: 15 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/base.py" - startLine: 15 - endLine: 19 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 13 - endLine: 13 -comparisonOperators: - example: - file: - path: "website/public/schemas/yaml/ComparisonOperators.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/ComparisonOperators.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/base.tsp" - startLine: 17 - endLine: 30 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/base.py" - startLine: 22 - endLine: 28 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 14 - endLine: 14 -stringOperators: - example: - file: - path: "website/public/schemas/yaml/StringOperators.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/StringOperators.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/base.tsp" - startLine: 43 - endLine: 50 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/base.py" - startLine: 38 - endLine: 42 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 16 - endLine: 16 -arrayOperators: - example: - file: - path: "website/public/schemas/yaml/ArrayOperators.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/ArrayOperators.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/base.tsp" - startLine: 33 - endLine: 41 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/base.py" - startLine: 31 - endLine: 35 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 15 - endLine: 15 -rangeOperators: - example: - file: - path: "website/public/schemas/yaml/RangeOperators.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/RangeOperators.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/base.tsp" - startLine: 52 - endLine: 59 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/base.py" - startLine: 45 - endLine: 49 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 17 - endLine: 17 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -151,13 +19,7 @@ The default filter model is a base model that can be used to create more specifi ### Formats - + ## EquivalenceOperators @@ -179,11 +41,10 @@ Operators that filter a field based on an exact match to a value. Supported valu ### Formats ## ComparisonOperators @@ -206,11 +67,10 @@ Operators that filter a field based on a comparison to a value. Supported value ### Formats ## StringOperators @@ -227,11 +87,10 @@ Operators that filter a field based on a string value. ### Formats ## ArrayOperators @@ -251,11 +110,10 @@ Operators that filter a field based on an array of values. Supported value types ### Formats ## RangeOperators @@ -276,9 +134,8 @@ Operators that filter a field based on a range of values. Supported value types ### Formats diff --git a/website/src/content/docs/protocol/filters/boolean.mdx b/website/src/content/docs/protocol/filters/boolean.mdx index 5c851dde1..313e352c5 100644 --- a/website/src/content/docs/protocol/filters/boolean.mdx +++ b/website/src/content/docs/protocol/filters/boolean.mdx @@ -1,28 +1,6 @@ --- title: Boolean filters description: Filters that can be applied to boolean fields. -booleanComparisonFilter: - example: - file: - path: "website/public/schemas/yaml/BooleanComparisonFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/BooleanComparisonFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/boolean.tsp" - startLine: 9 - endLine: 18 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/boolean.py" - startLine: 9 - endLine: 31 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 114 - endLine: 117 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -41,13 +19,7 @@ A filter that applies a comparison to a boolean value. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/filters/date.mdx b/website/src/content/docs/protocol/filters/date.mdx index ba538a0da..b244bbc19 100644 --- a/website/src/content/docs/protocol/filters/date.mdx +++ b/website/src/content/docs/protocol/filters/date.mdx @@ -1,50 +1,6 @@ --- title: Date filters description: Filters applied to date fields. -dateRangeFilter: - example: - file: - path: "website/public/schemas/yaml/DateRangeFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/DateRangeFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/date.tsp" - startLine: 24 - endLine: 39 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/date.py" - startLine: 37 - endLine: 52 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 85 - endLine: 91 -dateComparisonFilter: - example: - file: - path: "website/public/schemas/yaml/DateComparisonFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/DateComparisonFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/date.tsp" - startLine: 10 - endLine: 20 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/date.py" - startLine: 55 - endLine: 78 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 80 - endLine: 83 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -72,13 +28,7 @@ Filters by comparing a field to a range of date values. ### Formats - + ### Changelog @@ -97,13 +47,7 @@ Filters by comparing a field to a date value. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/filters/money.mdx b/website/src/content/docs/protocol/filters/money.mdx index f986e97ae..45002aa92 100644 --- a/website/src/content/docs/protocol/filters/money.mdx +++ b/website/src/content/docs/protocol/filters/money.mdx @@ -1,50 +1,6 @@ --- title: Money filters description: Filters applied to monetary values. -moneyRangeFilter: - example: - file: - path: "website/public/schemas/yaml/MoneyRangeFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/MoneyRangeFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/money.tsp" - startLine: 25 - endLine: 41 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/money.py" - startLine: 43 - endLine: 50 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 102 - endLine: 108 -moneyComparisonFilter: - example: - file: - path: "website/public/schemas/yaml/MoneyComparisonFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/MoneyComparisonFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/money.tsp" - startLine: 10 - endLine: 20 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/money.py" - startLine: 72 - endLine: 87 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 97 - endLine: 100 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -72,13 +28,7 @@ Filters by comparing a field to a range of monetary values. ### Formats - + ### Changelog @@ -97,13 +47,7 @@ Filters by comparing a field to a monetary value. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/filters/numeric.mdx b/website/src/content/docs/protocol/filters/numeric.mdx index e41c2f03f..1d9a9bbbb 100644 --- a/website/src/content/docs/protocol/filters/numeric.mdx +++ b/website/src/content/docs/protocol/filters/numeric.mdx @@ -1,72 +1,6 @@ --- title: Numeric filters description: Filters that can be applied to numeric fields. -numberComparisonFilter: - example: - file: - path: "website/public/schemas/yaml/NumberComparisonFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/NumberComparisonFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/numeric.tsp" - startLine: 11 - endLine: 21 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/numeric.py" - startLine: 26 - endLine: 35 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 53 - endLine: 56 -numberRangeFilter: - example: - file: - path: "website/public/schemas/yaml/NumberRangeFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/NumberRangeFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/numeric.tsp" - startLine: 42 - endLine: 54 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/numeric.py" - startLine: 46 - endLine: 61 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 58 - endLine: 64 -numberArrayFilter: - example: - file: - path: "website/public/schemas/yaml/NumberArrayFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/NumberArrayFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/numeric.tsp" - startLine: 60 - endLine: 69 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/numeric.py" - startLine: 64 - endLine: 81 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 66 - endLine: 69 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -85,13 +19,7 @@ Filters by comparing a field to a numeric value. ### Formats - + ### Changelog @@ -119,13 +47,7 @@ Filters by comparing a field to a range of numeric values. ### Formats - + ### Changelog @@ -144,13 +66,7 @@ Filters by comparing a field to an array of numeric values. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/filters/string.mdx b/website/src/content/docs/protocol/filters/string.mdx index 95c4d1780..a9dbab56f 100644 --- a/website/src/content/docs/protocol/filters/string.mdx +++ b/website/src/content/docs/protocol/filters/string.mdx @@ -1,50 +1,6 @@ --- title: String filters description: Filters that can be applied to string or enum fields. -stringComparisonFilter: - example: - file: - path: "website/public/schemas/yaml/StringComparisonFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/StringComparisonFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/string.tsp" - startLine: 9 - endLine: 18 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/string.py" - startLine: 31 - endLine: 49 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 39 - endLine: 42 -stringArrayFilter: - example: - file: - path: "website/public/schemas/yaml/StringArrayFilter.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/StringArrayFilter.yaml" - typeSpec: - file: - path: "lib/core/lib/core/filters/string.tsp" - startLine: 24 - endLine: 33 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/filters/string.py" - startLine: 13 - endLine: 28 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/filters.ts" - startLine: 44 - endLine: 47 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -63,13 +19,7 @@ A filter that applies a comparison to a string value. ### Formats - + ### Changelog @@ -88,13 +38,7 @@ A filter that applies a comparison to an array of string values. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/models/applicant-type.mdx b/website/src/content/docs/protocol/models/applicant-type.mdx index f202b3873..c62ae6e0f 100644 --- a/website/src/content/docs/protocol/models/applicant-type.mdx +++ b/website/src/content/docs/protocol/models/applicant-type.mdx @@ -10,35 +10,9 @@ applicantType: "value": "individual", "description": "An individual applicant" } - jsonSchema: - file: - path: "website/public/schemas/yaml/ApplicantType.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/applicant-type.tsp" - startLine: 7 - endLine: 11 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 54 - endLine: 65 applicantTypeOptions: example: code: '"individual"' - jsonSchema: - file: - path: "website/public/schemas/yaml/ApplicantTypeOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/applicant-type.tsp" - startLine: 17 - endLine: 70 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 34 - endLine: 52 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -59,10 +33,10 @@ The type of applicant for a funding opportunity. ### Formats ### Changelog @@ -96,10 +70,10 @@ The type of applicant for a funding opportunity. ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/application.mdx b/website/src/content/docs/protocol/models/application.mdx index d71042b89..80ff54954 100644 --- a/website/src/content/docs/protocol/models/application.mdx +++ b/website/src/content/docs/protocol/models/application.mdx @@ -28,26 +28,6 @@ applicationBase: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/ApplicationBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/application.tsp" - startLine: 20 - endLine: 51 -appRef: - example: - file: - path: "website/public/schemas/yaml/AppRef.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AppRef.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/application.tsp" - startLine: 3 - endLine: 18 appStatus: example: code: | @@ -55,25 +35,9 @@ appStatus: "value": "submitted", "description": "Application has been submitted." } - jsonSchema: - file: - path: "website/public/schemas/yaml/AppStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/application.tsp" - startLine: 57 - endLine: 60 appStatusOptions: example: code: '"submitted"' - jsonSchema: - file: - path: "website/public/schemas/yaml/AppStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/application.tsp" - startLine: 66 - endLine: 80 appFormResponse: example: code: | @@ -101,14 +65,6 @@ appFormResponse: "createdAt": "2024-01-01T00:00:00Z", "lastModifiedAt": "2024-01-01T00:00:00Z" } - jsonSchema: - file: - path: "website/public/schemas/yaml/AppFormResponse.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/application.tsp" - startLine: 86 - endLine: 95 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -121,14 +77,14 @@ Base model for an application to a funding opportunity. ### Table - + ### Formats ### Changelog @@ -141,15 +97,11 @@ A reference to an application, previewing the key fields a consumer needs to ide ### Table - + ### Formats - + ### Changelog @@ -161,14 +113,14 @@ The status of an application. ### Table - + ### Formats ### Changelog @@ -181,14 +133,14 @@ The default set of values accepted for application status. ### Table - + ### Formats ### Changelog @@ -201,14 +153,14 @@ A form response associated with an application. ### Table - + ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/award.mdx b/website/src/content/docs/protocol/models/award.mdx index 646db84ef..75039284f 100644 --- a/website/src/content/docs/protocol/models/award.mdx +++ b/website/src/content/docs/protocol/models/award.mdx @@ -3,114 +3,6 @@ title: Award description: The data models for a grant award sidebar: order: 11 -awardBase: - example: - file: - path: "website/public/schemas/yaml/AwardBase.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwardBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 155 - endLine: 204 -awdRef: - example: - file: - path: "website/public/schemas/yaml/AwdRef.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdRef.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 114 - endLine: 132 -awdStatus: - example: - file: - path: "website/public/schemas/yaml/AwdStatus.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 32 - endLine: 45 -awdStatusOptions: - example: - file: - path: "website/public/schemas/yaml/AwdStatusOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 18 - endLine: 30 -awdFunding: - example: - file: - path: "website/public/schemas/yaml/AwdFunding.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdFunding.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 51 - endLine: 66 -awdTimeline: - example: - file: - path: "website/public/schemas/yaml/AwdTimeline.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdTimeline.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 72 - endLine: 87 -awdRecipientIndividual: - example: - file: - path: "website/public/schemas/yaml/AwdRecipientIndividual.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdRecipientIndividual.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 138 - endLine: 149 -awdIds: - example: - file: - path: "website/public/schemas/yaml/AwdIds.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdIds.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 98 - endLine: 108 -awdIdFain: - example: - file: - path: "website/public/schemas/yaml/AwdIdFain.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/AwdIdFain.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/award.tsp" - startLine: 93 - endLine: 96 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -123,15 +15,11 @@ A grant award, tracking the funder, recipient, and financial details of a grant ### Table - + ### Formats - + ### Changelog @@ -143,15 +31,11 @@ A reference to an award, previewing the key fields a consumer needs to identify ### Table - + ### Formats - + ### Changelog @@ -163,15 +47,11 @@ The lifecycle status of an award, such as whether it has been awarded or complet ### Table - + ### Formats - + ### Changelog @@ -183,15 +63,11 @@ The set of values accepted for award status. ### Table - + ### Formats - + ### Changelog @@ -203,15 +79,11 @@ Financial details about the award, including the requested, awarded, and disburs ### Table - + ### Formats - + ### Changelog @@ -223,15 +95,11 @@ Key dates in the award's timeline, such as the award date and period of performa ### Table - + ### Formats - + ### Changelog @@ -243,17 +111,11 @@ An individual who received an award, when the recipient is a person rather than ### Table - + ### Formats - + ### Changelog @@ -265,15 +127,11 @@ System and registry-specific identifiers for an award, such as its FAIN. ### Table - + ### Formats - + ### Changelog @@ -285,15 +143,11 @@ An award's Federal Award Identification Number (FAIN), assigned by the awarding ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/models/competition.mdx b/website/src/content/docs/protocol/models/competition.mdx index c5807f6a6..7d92e0573 100644 --- a/website/src/content/docs/protocol/models/competition.mdx +++ b/website/src/content/docs/protocol/models/competition.mdx @@ -61,17 +61,6 @@ competition: "createdAt": "2025-01-01T00:00:00Z", "lastModifiedAt": "2025-01-01T00:00:00Z" } - table: - file: - path: "website/public/schemas/yaml/versions/v0.5.0/CompetitionBase.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/CompetitionBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/competition.tsp" - startLine: 3 - endLine: 49 competitionStatus: example: code: | @@ -80,25 +69,9 @@ competitionStatus: "customValue": "canceled", "description": "Competition has been canceled" } - jsonSchema: - file: - path: "website/public/schemas/yaml/CompetitionStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/competition.tsp" - startLine: 55 - endLine: 58 competitionStatusOptions: example: code: '"open"' - jsonSchema: - file: - path: "website/public/schemas/yaml/CompetitionStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/competition.tsp" - startLine: 64 - endLine: 74 competitionForms: example: code: | @@ -121,14 +94,6 @@ competitionForms: "required": ["formA"] } } - jsonSchema: - file: - path: "website/public/schemas/yaml/CompetitionForms.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/competition.tsp" - startLine: 80 - endLine: 89 competitionTimeline: example: code: | @@ -152,14 +117,6 @@ competitionTimeline: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/CompetitionTimeline.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/competition.tsp" - startLine: 95 - endLine: 107 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -178,16 +135,16 @@ The table and the example below show the v0.5 payload. To validate a payload, us ### Table - + ### Formats The JSON Schema tab shows the unversioned authoring schema, not a v0.5 payload schema. It combines every version's fields, so it requires both `opportunityId` and `opportunity`. ### Changelog @@ -244,14 +201,14 @@ The status of the competition. ### Table - + ### Formats ### Changelog @@ -264,16 +221,14 @@ Enumeration of possible competition status values. ### Table - + ### Formats ### Changelog @@ -286,14 +241,14 @@ Set of forms that need to be completed to apply to the competition. ### Table - + ### Formats ### Changelog @@ -306,14 +261,14 @@ The key dates in the competition's timeline. ### Table - + ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/form-response.mdx b/website/src/content/docs/protocol/models/form-response.mdx index f6b39e4f3..8fba0c698 100644 --- a/website/src/content/docs/protocol/models/form-response.mdx +++ b/website/src/content/docs/protocol/models/form-response.mdx @@ -29,14 +29,6 @@ formResponse: "createdAt": "2024-01-01T00:00:00Z", "lastModifiedAt": "2024-01-01T00:00:00Z" } - jsonSchema: - file: - path: "website/public/schemas/yaml/FormResponseBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/form-response.tsp" - startLine: 3 - endLine: 27 formResponseStatus: example: code: | @@ -44,25 +36,9 @@ formResponseStatus: "value": "complete", "description": "The form response is complete" } - jsonSchema: - file: - path: "website/public/schemas/yaml/FormResponseStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/form-response.tsp" - startLine: 33 - endLine: 36 formResponseStatusOptions: example: code: '"inProgress"' - jsonSchema: - file: - path: "website/public/schemas/yaml/FormResponseStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/form-response.tsp" - startLine: 42 - endLine: 56 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -75,14 +51,14 @@ Base model for a form response. ### Table - + ### Formats ### Changelog @@ -95,14 +71,14 @@ The status of a form response. ### Table - + ### Formats ### Changelog @@ -115,16 +91,14 @@ The options for the status of a form response. ### Table - + ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/form.mdx b/website/src/content/docs/protocol/models/form.mdx index b3d9bd847..579c4e32b 100644 --- a/website/src/content/docs/protocol/models/form.mdx +++ b/website/src/content/docs/protocol/models/form.mdx @@ -57,17 +57,6 @@ form: "createdAt": "2025-01-01T17:01:01Z", "lastModifiedAt": "2025-01-02T17:30:00Z" } - table: - file: - path: "website/public/schemas/yaml/versions/v0.5.0/FormBase.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/FormBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/form.tsp" - startLine: 9 - endLine: 51 formJsonSchema: example: code: | @@ -83,14 +72,6 @@ formJsonSchema: "phone": { "type": "string" } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/FormJsonSchema.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/form.tsp" - startLine: 57 - endLine: 62 formUISchema: example: code: | @@ -109,14 +90,6 @@ formUISchema: { "type": "Control", "scope": "#/properties/phone" } ] } - jsonSchema: - file: - path: "website/public/schemas/yaml/FormUISchema.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/form.tsp" - startLine: 68 - endLine: 73 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -133,16 +106,16 @@ The table and the example below show the v0.5 payload. To validate a payload, us ### Table - + ### Formats The JSON Schema tab shows the unversioned authoring schema, not a v0.5 payload schema. It combines every version's fields, so it requires both `name` and `title`. ### Changelog @@ -195,9 +168,9 @@ The TypeSpec model declares every version's fields at once: `name` is removed in A JSON schema used to validate form responses. ### Changelog @@ -209,9 +182,9 @@ A JSON schema used to validate form responses. A UI schema used to render the form in the browser. ### Changelog diff --git a/website/src/content/docs/protocol/models/mapping.mdx b/website/src/content/docs/protocol/models/mapping.mdx index 8a2ba22af..e20f6834b 100644 --- a/website/src/content/docs/protocol/models/mapping.mdx +++ b/website/src/content/docs/protocol/models/mapping.mdx @@ -19,14 +19,6 @@ mappingSchema: "amount": { "field": "summary.opportunity_amount" } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/MappingSchema.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/mapping.tsp" - startLine: 54 - endLine: 58 mappingFunction: example: code: | @@ -37,42 +29,18 @@ mappingFunction: "lastName": {"field": "last_name"}, }, } - jsonSchema: - file: - path: "website/public/schemas/yaml/MappingFunction.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/mapping.tsp" - startLine: 64 - endLine: 73 mappingConstantFunction: example: code: | { "const": "123", } - jsonSchema: - file: - path: "website/public/schemas/yaml/MappingConstantFunction.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/mapping.tsp" - startLine: 79 - endLine: 84 mappingFieldFunction: example: code: | { "field": "opportunity_status", } - jsonSchema: - file: - path: "website/public/schemas/yaml/MappingFieldFunction.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/mapping.tsp" - startLine: 90 - endLine: 95 mappingSwitchFunction: example: code: | @@ -86,14 +54,6 @@ mappingSwitchFunction: "default": "custom" } } - jsonSchema: - file: - path: "website/public/schemas/yaml/MappingSwitchFunction.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/mapping.tsp" - startLine: 101 - endLine: 115 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -165,9 +125,9 @@ To the following output: ### Formats ### Changelog @@ -189,9 +149,9 @@ A function for mapping data from one schema to another. ### Formats {/* TODO: Add changelog once unions are supported */} @@ -202,16 +162,14 @@ Returns a constant value. ### Table - + ### Formats ### Changelog @@ -224,14 +182,14 @@ Returns the value of a field in the source data. ### Table - + ### Formats ### Changelog @@ -244,16 +202,14 @@ Returns a new value based on the value of a field in the source data using a swi ### Table - + ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/opportunity.mdx b/website/src/content/docs/protocol/models/opportunity.mdx index f408cb196..e65e9e7c8 100644 --- a/website/src/content/docs/protocol/models/opportunity.mdx +++ b/website/src/content/docs/protocol/models/opportunity.mdx @@ -3,28 +3,6 @@ title: Opportunity description: The data models for a funding opportunity sidebar: order: 1 -opportunityBase: - example: - file: - path: "website/public/schemas/yaml/OpportunityBase.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OpportunityBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/base.tsp" - startLine: 45 - endLine: 80 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/models/opp_base.py" - startLine: 15 - endLine: 42 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 115 - endLine: 162 opportunityDetails: example: code: | @@ -226,150 +204,6 @@ opportunityDetails: "createdAt": "2019-08-24T14:15:22Z", "lastModifiedAt": "2019-08-24T14:15:22Z" } - jsonSchema: - file: - path: "website/public/schemas/yaml/OpportunityDetails.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/base.tsp" - startLine: 140 - endLine: 162 -oppRef: - example: - file: - path: "website/public/schemas/yaml/OppRef.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppRef.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/base.tsp" - startLine: 115 - endLine: 134 -oppIds: - example: - file: - path: "website/public/schemas/yaml/OppIds.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppIds.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/base.tsp" - startLine: 96 - endLine: 109 -oppIdFon: - example: - file: - path: "website/public/schemas/yaml/OppIdFon.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppIdFon.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/base.tsp" - startLine: 86 - endLine: 89 -oppIdAln: - example: - file: - path: "website/public/schemas/yaml/OppIdAln.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppIdAln.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/base.tsp" - startLine: 91 - endLine: 94 -oppStatus: - example: - file: - path: "website/public/schemas/yaml/OppStatus.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/status.tsp" - startLine: 25 - endLine: 29 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/models/opp_status.py" - startLine: 30 - endLine: 45 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 17 - endLine: 26 -oppStatusOptions: - example: - file: - path: "website/public/schemas/yaml/OppStatusOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/status.tsp" - startLine: 7 - endLine: 19 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/models/opp_status.py" - startLine: 11 - endLine: 27 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 15 - endLine: 15 -oppFunding: - example: - file: - path: "website/public/schemas/yaml/OppFunding.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppFunding.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/funding.tsp" - startLine: 12 - endLine: 44 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/models/opp_funding.py" - startLine: 11 - endLine: 47 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 73 - endLine: 96 -oppTimeline: - example: - file: - path: "website/public/schemas/yaml/OppTimeline.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OppTimeline.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/opportunity/timeline.tsp" - startLine: 13 - endLine: 28 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/models/opp_timeline.py" - startLine: 11 - endLine: 28 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/models.ts" - startLine: 102 - endLine: 113 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -382,17 +216,11 @@ A funding opportunity, such as a grant or loan. It shares its identity fields wi ### Table - + ### Formats - + ### Changelog @@ -406,15 +234,14 @@ An entry is a reference, not the award record: `GET /awards/` is the canonic ### Table - + ### Formats ### Changelog @@ -427,15 +254,11 @@ A reference to an opportunity, previewing the key fields a consumer needs to ide ### Table - + ### Formats - + ### Changelog @@ -447,15 +270,11 @@ A collection of identifiers associated with an opportunity, keyed by registry co ### Table - + ### Formats - + ### Changelog @@ -467,15 +286,11 @@ An opportunity's Federal Opportunity Number (FON), assigned by the awarding agen ### Table - + ### Formats - + ### Changelog @@ -487,15 +302,11 @@ An opportunity's Assistance Listing Number (ALN), formerly the CFDA number, whic ### Table - + ### Formats - + ### Changelog @@ -507,17 +318,11 @@ The status of an opportunity, such as whether it is accepting applications. ### Table - + ### Formats - + ### Changelog @@ -529,16 +334,15 @@ The set of values accepted for opportunity status. ### Table - + ### Formats ### Changelog @@ -551,17 +355,11 @@ Details about the funding available for an opportunity. ### Table - + ### Formats - + ### Changelog @@ -573,17 +371,11 @@ Key dates in the opportunity's timeline, such as when the application opens and ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/models/organization.mdx b/website/src/content/docs/protocol/models/organization.mdx index 74f660acc..e5ee9423c 100644 --- a/website/src/content/docs/protocol/models/organization.mdx +++ b/website/src/content/docs/protocol/models/organization.mdx @@ -126,206 +126,6 @@ organizationBase: ] } } - jsonSchema: - file: - path: "website/public/schemas/yaml/OrganizationBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 5 - endLine: 60 -orgIds: - example: - file: - path: "website/public/schemas/yaml/OrgIds.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgIds.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 81 - endLine: 96 -orgIdEin: - example: - file: - path: "website/public/schemas/yaml/OrgIdEin.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgIdEin.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 66 - endLine: 69 -orgIdUei: - example: - file: - path: "website/public/schemas/yaml/OrgIdUei.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgIdUei.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 71 - endLine: 74 -orgIdDuns: - example: - file: - path: "website/public/schemas/yaml/OrgIdDuns.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgIdDuns.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 76 - endLine: 79 -orgRef: - example: - file: - path: "website/public/schemas/yaml/OrgRef.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRef.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 102 - endLine: 120 -orgRefCollection: - example: - file: - path: "website/public/schemas/yaml/OrgRefCollection.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRefCollection.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 122 - endLine: 134 -orgRelationships: - example: - file: - path: "website/public/schemas/yaml/OrgRelationships.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRelationships.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 257 - endLine: 288 -orgHierarchyRelationship: - example: - file: - path: "website/public/schemas/yaml/OrgHierarchyRelationship.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgHierarchyRelationship.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 205 - endLine: 240 -orgSuccessionRelationship: - example: - file: - path: "website/public/schemas/yaml/OrgSuccessionRelationship.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgSuccessionRelationship.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 242 - endLine: 245 -orgRecordRelationship: - example: - file: - path: "website/public/schemas/yaml/OrgRecordRelationship.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRecordRelationship.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 247 - endLine: 250 -orgOtherRelationship: - example: - file: - path: "website/public/schemas/yaml/OrgOtherRelationship.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgOtherRelationship.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 252 - endLine: 255 -orgHierarchyKindOptions: - example: - file: - path: "website/public/schemas/yaml/OrgHierarchyKindOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgHierarchyKindOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 140 - endLine: 158 -orgSuccessionKindOptions: - example: - file: - path: "website/public/schemas/yaml/OrgSuccessionKindOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgSuccessionKindOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 160 - endLine: 174 -orgRecordKindOptions: - example: - file: - path: "website/public/schemas/yaml/OrgRecordKindOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRecordKindOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 176 - endLine: 187 -orgOtherKindOptions: - example: - file: - path: "website/public/schemas/yaml/OrgOtherKindOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgOtherKindOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 189 - endLine: 193 -orgRelationshipStatus: - example: - file: - path: "website/public/schemas/yaml/OrgRelationshipStatus.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRelationshipStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 195 - endLine: 203 orgSocialLinks: example: code: | @@ -341,50 +141,6 @@ orgSocialLinks: "tiktok": "https://tiktok.com/example" } } - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgSocialLinks.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 294 - endLine: 318 -orgStatus: - example: - file: - path: "website/public/schemas/yaml/OrgStatus.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 336 - endLine: 341 -orgStatusOptions: - example: - file: - path: "website/public/schemas/yaml/OrgStatusOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization.tsp" - startLine: 324 - endLine: 334 -orgPatchData: - example: - file: - path: "website/public/schemas/yaml/OrgPatchData.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgPatchData.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization-sync.tsp" - startLine: 277 - endLine: 289 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -419,9 +175,9 @@ An organization that can apply to or host funding opportunities. ### Formats ### Changelog @@ -437,15 +193,11 @@ published under `otherIds`. ### Table - + ### Formats - + ### Changelog @@ -459,15 +211,11 @@ An organization's Employer Identification Number (EIN), assigned by the IRS. It ### Table - + ### Formats - + ### Changelog @@ -481,15 +229,11 @@ An organization's Unique Entity Identifier (UEI) from SAM.gov. It pins `registry ### Table - + ### Formats - + ### Changelog @@ -503,15 +247,11 @@ An organization's Data Universal Numbering System (DUNS) number. It pins `regist ### Table - + ### Formats - + ### Changelog @@ -523,15 +263,11 @@ A reference to an organization, previewing the key fields a consumer needs to id ### Table - + ### Formats - + ### Changelog @@ -543,15 +279,11 @@ A group of organization references, with a primary organization and optional oth ### Table - + ### Formats - + ### Changelog @@ -575,15 +307,11 @@ On reads, `relationships`, each list, `aliases`, and an entry's optional members ### Table - + ### Formats - + ### Changelog @@ -603,16 +331,13 @@ An entry with only `org` is valid. Parents and children cover more than containm ### Table - + ### Formats ### Changelog @@ -625,17 +350,11 @@ A succession relationship, added in v0.5.0, with the same shape as [OrgHierarchy ### Table - + ### Formats - + ### Changelog @@ -647,17 +366,11 @@ A record replacement relationship, added in v0.5.0, with the same shape as [OrgH ### Table - + ### Formats - + ### Changelog @@ -669,15 +382,11 @@ A relationship outside the named categories, added in v0.5.0, with the same shap ### Table - + ### Formats - + ### Changelog @@ -689,17 +398,11 @@ The standard subtypes of a parent or child relationship, added in v0.5.0. `dba` ### Table - + ### Formats - + ### Changelog @@ -711,17 +414,11 @@ The standard subtypes of organizational succession, added in v0.5.0. ### Table - + ### Formats - + ### Changelog @@ -733,15 +430,11 @@ The standard subtypes of record replacement, added in v0.5.0. A provider's workf ### Table - + ### Formats - + ### Changelog @@ -753,15 +446,11 @@ The subtypes of an [OrgOtherRelationship](#orgotherrelationship), added in v0.5. ### Table - + ### Formats - + ### Changelog @@ -773,17 +462,11 @@ Whether a relationship is in effect, as stated by the provider, added in v0.5.0. ### Table - + ### Formats - + ### Changelog @@ -808,9 +491,9 @@ A collection of social media and web presence links for an organization. ### Formats ### Changelog @@ -827,15 +510,11 @@ The status of an organization: ### Table - + ### Formats - + ### Changelog @@ -847,15 +526,11 @@ The set of values accepted for organization status. ### Table - + ### Formats - + ### Changelog @@ -869,15 +544,11 @@ From v0.5.0, `relationships` follows the same rules. Each relationship list is a ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/models/person.mdx b/website/src/content/docs/protocol/models/person.mdx index 375742f44..227a155f9 100644 --- a/website/src/content/docs/protocol/models/person.mdx +++ b/website/src/content/docs/protocol/models/person.mdx @@ -56,14 +56,6 @@ personBase: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/PersonBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/person.tsp" - startLine: 6 - endLine: 30 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -76,14 +68,14 @@ A person affiliated with an organization or grant application. ### Table - + ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/proposal.mdx b/website/src/content/docs/protocol/models/proposal.mdx index 83b2fa2a9..6df33da70 100644 --- a/website/src/content/docs/protocol/models/proposal.mdx +++ b/website/src/content/docs/protocol/models/proposal.mdx @@ -108,14 +108,6 @@ proposalBase: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/ProposalBase.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/proposal.tsp" - startLine: 7 - endLine: 34 proposalOpportunity: example: code: | @@ -132,14 +124,6 @@ proposalOpportunity: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/ProposalOpportunity.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/proposal.tsp" - startLine: 40 - endLine: 51 projectTimeline: example: code: | @@ -165,14 +149,6 @@ projectTimeline: }, "timelineDetails": "The project will be conducted over 12 months with quarterly milestones." } - jsonSchema: - file: - path: "website/public/schemas/yaml/ProjectTimeline.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/proposal.tsp" - startLine: 57 - endLine: 71 proposalContacts: example: code: | @@ -209,14 +185,6 @@ proposalContacts: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/ProposalContacts.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/proposal.tsp" - startLine: 77 - endLine: 85 proposalOrgs: example: code: | @@ -239,14 +207,6 @@ proposalOrgs: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/ProposalOrgs.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/proposal.tsp" - startLine: 91 - endLine: 99 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -259,14 +219,14 @@ A proposal for funding. ### Table - + ### Formats ### Changelog @@ -279,14 +239,14 @@ The opportunity to which this proposal is related. ### Table - + ### Formats ### Changelog @@ -299,14 +259,14 @@ The key dates for the project. ### Table - + ### Formats ### Changelog @@ -319,14 +279,14 @@ The point of contact for the project. ### Table - + ### Formats ### Changelog @@ -339,14 +299,14 @@ The organization that is requesting funding. ### Table - + ### Formats ### Changelog diff --git a/website/src/content/docs/protocol/models/revision.mdx b/website/src/content/docs/protocol/models/revision.mdx index 22c5f4118..940208caf 100644 --- a/website/src/content/docs/protocol/models/revision.mdx +++ b/website/src/content/docs/protocol/models/revision.mdx @@ -3,54 +3,6 @@ title: Revision description: Data models for a record of a change to a resource sidebar: order: 13 -revision: - example: - file: - path: "website/public/schemas/yaml/Revision.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Revision.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/revision.tsp" - startLine: 48 - endLine: 98 -revisionStatus: - example: - file: - path: "website/public/schemas/yaml/RevisionStatus.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/RevisionStatus.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/revision.tsp" - startLine: 36 - endLine: 42 -revisionStatusOptions: - example: - file: - path: "website/public/schemas/yaml/RevisionStatusOptions.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/RevisionStatusOptions.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/revision.tsp" - startLine: 13 - endLine: 34 -orgRevision: - example: - file: - path: "website/public/schemas/yaml/OrgRevision.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/OrgRevision.yaml" - typeSpec: - file: - path: "lib/core/lib/core/models/organization-sync.tsp" - startLine: 291 - endLine: 298 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -67,15 +19,11 @@ The generic, untyped record of a change, where `patch` and `snapshot` are open o ### Table - + ### Formats - + ### Changelog @@ -99,15 +47,11 @@ How a receiver resolves a `pending` change (a human review, a policy engine, a b ### Table - + ### Formats - + ### Changelog @@ -119,11 +63,7 @@ The fixed set of values a [RevisionStatus](#revisionstatus) can take: `pending`, ### Formats - + ### Changelog @@ -135,15 +75,11 @@ A [Revision](#revision) bound to organization profiles, where `patch` is an [Org ### Table - + ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/pagination.mdx b/website/src/content/docs/protocol/pagination.mdx index 6e8bd0aae..ded8d7e12 100644 --- a/website/src/content/docs/protocol/pagination.mdx +++ b/website/src/content/docs/protocol/pagination.mdx @@ -1,72 +1,6 @@ --- title: Pagination description: Defines a set of parameters and patterns for paginated routes -paginatedQueryParams: - example: - file: - path: "website/public/schemas/yaml/PaginatedQueryParams.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PaginatedQueryParams.yaml" - typeSpec: - file: - path: "lib/core/lib/core/pagination.tsp" - startLine: 10 - endLine: 24 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/pagination.py" - startLine: 28 - endLine: 29 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/pagination.ts" - startLine: 16 - endLine: 22 -paginatedBodyParams: - example: - file: - path: "website/public/schemas/yaml/PaginatedBodyParams.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PaginatedBodyParams.yaml" - typeSpec: - file: - path: "lib/core/lib/core/pagination.tsp" - startLine: 26 - endLine: 38 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/pagination.py" - startLine: 24 - endLine: 25 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/pagination.ts" - startLine: 29 - endLine: 35 -paginatedResultsInfo: - example: - file: - path: "website/public/schemas/yaml/PaginatedResultsInfo.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/PaginatedResultsInfo.yaml" - typeSpec: - file: - path: "lib/core/lib/core/pagination.tsp" - startLine: 40 - endLine: 60 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/pagination.py" - startLine: 32 - endLine: 46 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/pagination.ts" - startLine: 42 - endLine: 54 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -85,13 +19,7 @@ Query parameters for paginated routes. These parameters should be used on GET ro ### Formats - + ### Changelog @@ -110,13 +38,7 @@ Body parameters for paginated routes. These parameters should be used on POST an ### Formats - + ### Changelog @@ -137,13 +59,7 @@ Details about the paginated results. This model should included in the response ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/responses/error.mdx b/website/src/content/docs/protocol/responses/error.mdx index fc31e765a..d941efb4f 100644 --- a/website/src/content/docs/protocol/responses/error.mdx +++ b/website/src/content/docs/protocol/responses/error.mdx @@ -3,45 +3,6 @@ title: Errors description: A standard error response schema, used to create custom error responses sidebar: order: 5 -error: - example: - file: - path: "website/public/schemas/yaml/Error.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Error.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/error.tsp" - startLine: 15 - endLine: 27 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/responses/error.py" - startLine: 10 - endLine: 26 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/responses.ts" - startLine: 170 - endLine: 179 -applicationSubmissionError: - example: - file: - path: "website/public/schemas/yaml/ApplicationSubmissionError.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/ApplicationSubmissionError.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/error.tsp" - startLine: 32 - endLine: 43 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/responses.ts" - startLine: 192 - endLine: 194 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -63,13 +24,7 @@ Default response schema for 4xx and 5xx HTTP status codes. ### Formats - + ### Usage @@ -106,12 +61,7 @@ A failure to submit an application due to validation errors. ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/responses/filtered.mdx b/website/src/content/docs/protocol/responses/filtered.mdx index 387fea1b6..3c25f9197 100644 --- a/website/src/content/docs/protocol/responses/filtered.mdx +++ b/website/src/content/docs/protocol/responses/filtered.mdx @@ -45,24 +45,6 @@ filtered: } } } - jsonSchema: - file: - path: "website/public/schemas/yaml/Filtered.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 177 - endLine: 198 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/responses/success.py" - startLine: 57 - endLine: 78 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/responses.ts" - startLine: 126 - endLine: 140 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -86,11 +68,11 @@ A 200 response with a paginated list of filtered items. ### Formats ### Usage diff --git a/website/src/content/docs/protocol/responses/paginated.mdx b/website/src/content/docs/protocol/responses/paginated.mdx index 537707e35..d25a70cf3 100644 --- a/website/src/content/docs/protocol/responses/paginated.mdx +++ b/website/src/content/docs/protocol/responses/paginated.mdx @@ -26,24 +26,6 @@ paginated: "totalPages": 3 } } - jsonSchema: - file: - path: "website/public/schemas/yaml/Paginated.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 72 - endLine: 90 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/responses/success.py" - startLine: 32 - endLine: 42 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/responses.ts" - startLine: 71 - endLine: 78 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -65,11 +47,11 @@ A 200 response with a paginated list of items. ### Formats ### Usage diff --git a/website/src/content/docs/protocol/responses/sorted.mdx b/website/src/content/docs/protocol/responses/sorted.mdx index 640467a18..796c7e493 100644 --- a/website/src/content/docs/protocol/responses/sorted.mdx +++ b/website/src/content/docs/protocol/responses/sorted.mdx @@ -30,24 +30,6 @@ sorted: "direction": "asc" } } - jsonSchema: - file: - path: "website/public/schemas/yaml/Sorted.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 125 - endLine: 141 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/responses/success.py" - startLine: 45 - endLine: 54 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/responses.ts" - startLine: 97 - endLine: 101 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -70,11 +52,11 @@ A 200 response with a paginated list of sorted items. ### Formats ### Usage diff --git a/website/src/content/docs/protocol/responses/success.mdx b/website/src/content/docs/protocol/responses/success.mdx index 731a4ef8c..e70254588 100644 --- a/website/src/content/docs/protocol/responses/success.mdx +++ b/website/src/content/docs/protocol/responses/success.mdx @@ -14,14 +14,6 @@ ok: "name": "Test 1" } } - jsonSchema: - file: - path: "website/public/schemas/yaml/Ok.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 31 - endLine: 36 created: example: code: | @@ -33,14 +25,6 @@ created: "name": "Test 1" } } - jsonSchema: - file: - path: "website/public/schemas/yaml/Created.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 239 - endLine: 244 accepted: example: code: | @@ -52,36 +36,6 @@ accepted: "name": "Test 1" } } - jsonSchema: - file: - path: "website/public/schemas/yaml/Accepted.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 268 - endLine: 273 -success: - example: - file: - path: "website/public/schemas/yaml/Success.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/Success.yaml" - typeSpec: - file: - path: "lib/core/lib/core/responses/success.tsp" - startLine: 14 - endLine: 21 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/responses/success.py" - startLine: 17 - endLine: 29 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/responses.ts" - startLine: 19 - endLine: 25 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -100,13 +54,7 @@ Base model for all successful responses. ### Formats - + ### Changelog @@ -126,13 +74,7 @@ A 200 response with data. ### Formats - + ### Usage @@ -175,9 +117,9 @@ A 201 response with data. ### Formats ### Usage @@ -223,9 +165,9 @@ Returned when a request is accepted for processing but may not be applied immedi ### Formats ### Usage diff --git a/website/src/content/docs/protocol/sorting.mdx b/website/src/content/docs/protocol/sorting.mdx index 68c94bde9..fe6e885dc 100644 --- a/website/src/content/docs/protocol/sorting.mdx +++ b/website/src/content/docs/protocol/sorting.mdx @@ -1,94 +1,6 @@ --- title: Sorting description: Defines a set of parameters and patterns for sorting routes -sortOrder: - example: - file: - path: "website/public/schemas/yaml/SortOrder.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SortOrder.yaml" - typeSpec: - file: - path: "lib/core/lib/core/sorting.tsp" - startLine: 21 - endLine: 25 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/sorting.py" - startLine: 9 - endLine: 13 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/sorting.ts" - startLine: 16 - endLine: 16 -sortQueryParams: - example: - file: - path: "website/public/schemas/yaml/SortQueryParams.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SortQueryParams.yaml" - typeSpec: - file: - path: "lib/core/lib/core/sorting.tsp" - startLine: 27 - endLine: 44 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/sorting.py" - startLine: 35 - endLine: 43 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/sorting.ts" - startLine: 23 - endLine: 32 -sortBodyParams: - example: - file: - path: "website/public/schemas/yaml/SortBodyParams.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SortBodyParams.yaml" - typeSpec: - file: - path: "lib/core/lib/core/sorting.tsp" - startLine: 46 - endLine: 60 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/sorting.py" - startLine: 46 - endLine: 54 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/sorting.ts" - startLine: 39 - endLine: 48 -sortedResultsInfo: - example: - file: - path: "website/public/schemas/yaml/SortedResultsInfo.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/SortedResultsInfo.yaml" - typeSpec: - file: - path: "lib/core/lib/core/sorting.tsp" - startLine: 62 - endLine: 79 - python: - file: - path: "lib/python-sdk/common_grants_sdk/schemas/pydantic/sorting.py" - startLine: 57 - endLine: 69 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/sorting.ts" - startLine: 55 - endLine: 67 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -108,11 +20,10 @@ The order or direction to sort results by. ### Formats ### Changelog @@ -133,13 +44,7 @@ Query parameters for sorting. These parameters should be used on GET routes that ### Formats - + ### Changelog @@ -159,13 +64,7 @@ Body parameters for sorting. These parameters should be used on POST and PUT rou ### Formats - + ### Changelog @@ -186,13 +85,7 @@ Information about the sort order of the items returned. This model should be inc ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/types/date.mdx b/website/src/content/docs/protocol/types/date.mdx index d0f398ca3..c562add22 100644 --- a/website/src/content/docs/protocol/types/date.mdx +++ b/website/src/content/docs/protocol/types/date.mdx @@ -3,40 +3,6 @@ title: Date and time types description: Date and time types used throughout the protocol. sidebar: order: 3 -isoDate: - example: - file: - path: "website/public/schemas/yaml/isoDate.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/isoDate.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 88 - endLine: 91 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/types.ts" - startLine: 49 - endLine: 52 -isoTime: - example: - file: - path: "website/public/schemas/yaml/isoTime.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/isoTime.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 83 - endLine: 86 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/types.ts" - startLine: 55 - endLine: 62 utcDateTime: example: code: '"2024-02-28T17:00:00Z"' @@ -47,11 +13,6 @@ utcDateTime: type: string format: date-time description: A date and time with timezone in ISO 8601 format YYYY-MM-DDThh:mm:ssZ - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/types.ts" - startLine: 46 - endLine: 46 offsetDateTime: example: code: '"2024-02-28T17:00:00+01:00"' @@ -62,23 +23,6 @@ offsetDateTime: type: string format: date-time description: A date and time with timezone in ISO 8601 format YYYY-MM-DDThh:mm:ssยฑhh:mm - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/types.ts" - startLine: 65 - endLine: 68 -calendarYear: - example: - file: - path: "website/public/schemas/yaml/calendarYear.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/calendarYear.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 93 - endLine: 97 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -87,12 +31,7 @@ import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; A date on a calendar in ISO 8601 format YYYY-MM-DD. - + ## isoTime @@ -102,12 +41,7 @@ A time on a clock, without a timezone, in ISO 8601 format HH:mm:ss. The `isoTime` type does not include timezone information. When representing a time in a specific timezone, use `utcDateTime` or `offsetDateTime` instead. ::: - + ## utcDateTime @@ -116,7 +50,7 @@ A date and time with timezone in ISO 8601 format YYYY-MM-DDThh:mm:ssZ. ## offsetDateTime @@ -126,15 +60,11 @@ A date and time with timezone in ISO 8601 format YYYY-MM-DDThh:mm:ssยฑhh:mm. ## calendarYear A calendar year in the format YYYY. - + diff --git a/website/src/content/docs/protocol/types/numeric.mdx b/website/src/content/docs/protocol/types/numeric.mdx index 4d2224054..3780caff5 100644 --- a/website/src/content/docs/protocol/types/numeric.mdx +++ b/website/src/content/docs/protocol/types/numeric.mdx @@ -45,19 +45,6 @@ decimalString: // Negative, scale 2 "-100.50" - jsonSchema: - file: - path: "website/public/schemas/yaml/decimalString.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 68 - endLine: 77 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/types.ts" - startLine: 21 - endLine: 23 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -85,10 +72,10 @@ A whole number without decimals, equivalent to `integer` in JSON Schema. A decimal number (with variable scale) encoded as a string, to avoid floating point issues. ## Other numeric types diff --git a/website/src/content/docs/protocol/types/string.mdx b/website/src/content/docs/protocol/types/string.mdx index b8960e7f8..08b43c5d8 100644 --- a/website/src/content/docs/protocol/types/string.mdx +++ b/website/src/content/docs/protocol/types/string.mdx @@ -22,83 +22,6 @@ url: type: string format: uri description: A Uniform Resource Locator (URL) -uuid: - example: - file: - path: "website/public/schemas/yaml/uuid.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/uuid.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 28 - endLine: 32 - typescript: - file: - path: "lib/ts-sdk/src/schemas/zod/types.ts" - startLine: 15 - endLine: 15 -email: - example: - file: - path: "website/public/schemas/yaml/email.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/email.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 34 - endLine: 38 -employerTaxId: - example: - file: - path: "website/public/schemas/yaml/employerTaxId.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/employerTaxId.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 40 - endLine: 44 -samUEI: - example: - file: - path: "website/public/schemas/yaml/samUEI.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/samUEI.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 46 - endLine: 50 -duns: - example: - file: - path: "website/public/schemas/yaml/duns.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/duns.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 52 - endLine: 56 -nonEmptyString: - example: - file: - path: "website/public/schemas/yaml/nonEmptyString.yaml" - jsonSchema: - file: - path: "website/public/schemas/yaml/nonEmptyString.yaml" - typeSpec: - file: - path: "lib/core/lib/core/types.tsp" - startLine: 58 - endLine: 62 --- import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; @@ -125,59 +48,34 @@ A Uniform Resource Locator (URL). A universally unique identifier. - + ## email An email address. - + ## employerTaxId An Employer Identification Number (EIN). - + ## samUEI A Unique Entity Identifier (UEI). - + ## duns A Data Universal Numbering System (DUNS) number. - + ## nonEmptyString A string with at least one character, added in v0.5.0. Used for an organization's [`aliases`](/protocol/models/organization#organizationbase). - + diff --git a/website/src/lib/schema/schema-doc-mapper.ts b/website/src/lib/schema/schema-doc-mapper.ts index e3f218f69..ce368c976 100644 --- a/website/src/lib/schema/schema-doc-mapper.ts +++ b/website/src/lib/schema/schema-doc-mapper.ts @@ -1,56 +1,128 @@ -import { readFileSync } from "fs"; +import { readdirSync, readFileSync } from "fs"; +import * as path from "path"; +import yaml from "js-yaml"; import { Paths } from "./paths"; +/** A `` or `` tag's `schema="Name"` attribute */ +const SCHEMA_ATTRIBUTE = + /]*?\bschema="([^"]+)"/g; + +/** A frontmatter entry holding an inline JSON Schema */ +interface InlineSchemaEntry { + jsonSchema?: { code?: string }; +} + /** - * Schema documentation mapping service + * Maps each schema to the docs page that documents it, by reading which + * schemas each protocol page names. Schema tables use it to link a property's + * type to its page. + * + * Pages name a schema with `schema="Name"` on `` or + * ``. A section whose JSON Schema is written inline in the + * frontmatter (the basic types) maps under its frontmatter key and under the + * schema's JSON `type`. When two pages name a schema, the later page wins. + * + * @param protocolDocsDir - Directory of protocol pages to read + * @param contentDocsDir - Root of the docs content, which page URLs are relative to */ -export class SchemaDocMapper { - private static cache: Map | null = null; +export function buildSchemaDocMap( + protocolDocsDir: string, + contentDocsDir: string, +): Map { + const map = new Map(); - /** - * Gets the schema documentation mapping with memoization - * Loads pre-computed mapping and fails if not available - */ - static getSchemaDocMap(): Map { - if (this.cache) { - return this.cache; + for (const file of listPages(protocolDocsDir)) { + const content = readFileSync(file, "utf-8"); + const docPath = + "/" + + path + .relative(contentDocsDir, file) + .split(path.sep) + .join("/") + .replace(/\.mdx$/, ""); + + for (const match of content.matchAll(SCHEMA_ATTRIBUTE)) { + map.set(match[1], docPath); } - const mappingPath = Paths.SCHEMA_DOCS_MAPPING; + for (const [name, type] of inlineSchemas(content, file)) { + map.set(name, docPath); + if (type) map.set(type, docPath); + } + } - try { - const mappingContent = readFileSync(mappingPath, "utf-8"); - const mappingObject = JSON.parse(mappingContent); + return map; +} - const map = new Map(); - for (const [schemaName, docPath] of Object.entries(mappingObject)) { - map.set(schemaName, docPath as string); - } +/** Lists the inline JSON Schemas in a page's frontmatter, with their types. */ +function inlineSchemas( + content: string, + file: string, +): Array<[string, string | undefined]> { + const frontmatter = content.match(/^---\n([\s\S]*?)\n---/)?.[1]; + if (!frontmatter) return []; - this.cache = map; - console.log( - `Loaded pre-computed schema documentation mapping (${map.size} entries)`, - ); - return map; + const data = yaml.load(frontmatter) as Record; + const result: Array<[string, string | undefined]> = []; + for (const [name, entry] of Object.entries(data ?? {})) { + const code = (entry as InlineSchemaEntry | null)?.jsonSchema?.code; + if (typeof code !== "string") continue; + + let type: string | undefined; + try { + const schema = yaml.load(code) as { type?: unknown }; + if (typeof schema?.type === "string") type = schema.type; } catch (error) { - throw new Error( - `Failed to load schema documentation mapping from ${mappingPath}: ${error}`, - { cause: error }, + throw new Error(`Inline JSON Schema "${name}" in ${file} isn't YAML`, { + cause: error, + }); + } + result.push([name, type]); + } + return result; +} + +/** Lists the MDX pages under a directory, in a stable order. */ +function listPages(dir: string): string[] { + const files: string[] = []; + const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => + a.name < b.name ? -1 : a.name > b.name ? 1 : 0, + ); + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + files.push(...listPages(fullPath)); + } else if (entry.isFile() && entry.name.endsWith(".mdx")) { + files.push(fullPath); + } + } + return files; +} + +/** + * Schema documentation mapping service. Builds the map from the protocol + * pages the first time it's asked, once per build. + */ +export class SchemaDocMapper { + private static cache: Map | null = null; + + /** Gets the schema documentation mapping, building it on first use */ + static getSchemaDocMap(): Map { + if (!this.cache) { + this.cache = buildSchemaDocMap( + Paths.PROTOCOL_DOCS_DIR, + Paths.CONTENT_DOCS_DIR, ); } + return this.cache; } - /** - * Gets documentation path for a specific schema name - */ + /** Gets documentation path for a specific schema name */ static getSchemaDocPath(schemaName: string): string | undefined { - const map = this.getSchemaDocMap(); - return map.get(schemaName); + return this.getSchemaDocMap().get(schemaName); } - /** - * Clears the cache (useful for testing) - */ + /** Clears the cache (useful for testing) */ static clearCache(): void { this.cache = null; } From f463bb1a41fde31b72d7b2e784b9fc219c227676 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Thu, 19 Nov 2026 14:05:13 -0800 Subject: [PATCH 08/20] fix(website): re-read sources on dev reload and show inherited Python fields - The dev server re-reads the TypeSpec, Python and TypeScript sources once per page render, so a source edit shows on reload; a production build still reads them once. - Declarations shown together keep the blank lines the source has between them, so Python classes sit two blank lines apart. - The Python tabs for the pagination and sorting models show their base class (PaginatedBase, SortBase), which holds the inherited fields. - Drop code with no reader: the example file branch, the cache-clearing helper and an export; use the TypeSpec parser's line lookup and one shared recursive file listing. --- .../lib/schema/source-declarations.spec.ts | 50 +++++++++ website/src/components/SchemaFormatTabs.astro | 26 +++-- .../src/content/docs/protocol/pagination.mdx | 21 +++- website/src/content/docs/protocol/sorting.mdx | 21 +++- website/src/lib/schema/schema-doc-mapper.ts | 22 +--- website/src/lib/schema/source-declarations.ts | 101 +++++++++--------- 6 files changed, 159 insertions(+), 82 deletions(-) diff --git a/website/__tests__/lib/schema/source-declarations.spec.ts b/website/__tests__/lib/schema/source-declarations.spec.ts index 8e645a6c6..045518319 100644 --- a/website/__tests__/lib/schema/source-declarations.spec.ts +++ b/website/__tests__/lib/schema/source-declarations.spec.ts @@ -1,4 +1,6 @@ import { describe, it, expect } from "vitest"; +import { readFileSync } from "fs"; +import * as path from "path"; import { listTypeSpecDeclarations, listPythonDeclarations, @@ -6,9 +8,13 @@ import { findDeclaration, findSchemaDeclaration, findSnippet, + refreshDeclarationsForRender, sourceUrl, type Declaration, } from "@/lib/schema/source-declarations"; +import { Paths } from "@/lib/schema/paths"; + +const REPO_ROOT = Paths.REPO_ROOT; /** Picks one declaration out of a listing by name. */ function pick(declarations: Declaration[], name: string): Declaration { @@ -505,6 +511,30 @@ describe("findSnippet", () => { expect(snippet.endLine).toBe(model.endLine); }); + it("separates declarations shown together by the blank lines the source has above the later one", () => { + // Python classes sit two blank lines apart (PEP 8); FilterInfo is directly + // above Filtered, so the tab is an exact excerpt of the source. + const snippet = findSnippet("python", ["FilterInfo", "Filtered"]); + const source = readFileSync(path.join(REPO_ROOT, snippet.path), "utf-8") + .split("\n") + .slice(snippet.startLine - 1, snippet.endLine) + .join("\n"); + expect(snippet.code).toBe(source); + expect(snippet.code).toMatch(/\n\n\nclass Filtered\(/); + }); + + it("uses the later declaration's own spacing when other code sits between them", () => { + // PaginatedBodyParams sits between PaginatedBase and PaginatedQueryParams. + const snippet = findSnippet("python", [ + "PaginatedBase", + "PaginatedQueryParams", + ]); + const base = findDeclaration("python", "PaginatedBase"); + const params = findDeclaration("python", "PaginatedQueryParams"); + expect(snippet.code).toBe(`${base.code}\n\n\n${params.code}`); + expect(snippet.code).not.toMatch(/PaginatedBodyParams/); + }); + it("fails when declarations shown together are in different files", () => { expect(() => findSnippet("typeSpec", ["Money", "AwardBase"])).toThrow( /must be in one file/, @@ -518,6 +548,26 @@ describe("findSnippet", () => { }); }); +describe("refreshDeclarationsForRender", () => { + it("re-reads the sources once for each new render, and not again within it", () => { + const first = findDeclaration("python", "Money"); + expect(findDeclaration("python", "Money")).toBe(first); + + const render = {}; + refreshDeclarationsForRender(render); + const reread = findDeclaration("python", "Money"); + expect(reread).not.toBe(first); + expect(reread).toEqual(first); + + // Further components on the same page reuse what that render read. + refreshDeclarationsForRender(render); + expect(findDeclaration("python", "Money")).toBe(reread); + + refreshDeclarationsForRender({}); + expect(findDeclaration("python", "Money")).not.toBe(reread); + }); +}); + describe("sourceUrl", () => { it("links to the declaration's lines on GitHub", () => { expect(sourceUrl({ path: "lib/a.tsp", startLine: 3, endLine: 9 })).toBe( diff --git a/website/src/components/SchemaFormatTabs.astro b/website/src/components/SchemaFormatTabs.astro index 1b66a7854..a2977f028 100644 --- a/website/src/components/SchemaFormatTabs.astro +++ b/website/src/components/SchemaFormatTabs.astro @@ -8,19 +8,24 @@ import { generateSchemaExample } from "../lib/schema/example-generator"; import { schemaFilePath } from "../lib/schema/schema-files"; import { findSnippet, + refreshDeclarationsForRender, sourceUrl, type SourceLanguage, } from "../lib/schema/source-declarations"; /** * A literal code block, or a file to read whole. Pages give literal code for - * hand-written examples and inline JSON Schemas; the custom field catalog - * gives a file. + * hand-written examples and inline JSON Schemas. */ interface CodeBlockConfig { /** A literal code block to display. If provided, file is ignored. */ code?: string; - /** A file to display, by its path relative to the repository root */ + /** + * A JSON Schema file to display, by its path relative to the repository + * root. Only `jsonSchema` reads it: the custom field catalog passes its + * extension schema this way. Examples are literal code or generated from + * `schema`. + */ file?: { path: string; }; @@ -46,7 +51,7 @@ interface Props { /** The schema's name, which is also the name of its generated JSON Schema file */ schema?: string; /** Example JSON: literal code overrides the example generated from the schema */ - example?: CodeBlockConfig; + example?: Pick; /** JSON Schema: literal code for schemas with no generated file */ jsonSchema?: CodeBlockConfig; /** TypeSpec tab */ @@ -72,16 +77,19 @@ if (!example && !jsonSchemaConfig && !typeSpec && !python && !typescript) { const exampleCode = example?.code ? example.code - : example?.file?.path - ? await generateSchemaExample(example.file.path) - : schemaPath - ? await generateSchemaExample(schemaPath) - : null; + : schemaPath + ? await generateSchemaExample(schemaPath) + : null; const jsonSchemaCode = jsonSchemaConfig ? extractCode(jsonSchemaConfig) : null; const jsonSchemaUrl = jsonSchemaConfig ? extractSchemaUrl(jsonSchemaConfig) : null; +// In the dev server, re-read the sources once per page render so a source +// edit shows on reload; a production build reads them once. +if (import.meta.env.DEV) { + refreshDeclarationsForRender(Astro.locals); +} const typeSpecSnippet = snippet("typeSpec", typeSpec); const pythonSnippet = snippet("python", python); const typescriptSnippet = snippet("typescript", typescript); diff --git a/website/src/content/docs/protocol/pagination.mdx b/website/src/content/docs/protocol/pagination.mdx index ded8d7e12..fb956ab03 100644 --- a/website/src/content/docs/protocol/pagination.mdx +++ b/website/src/content/docs/protocol/pagination.mdx @@ -19,7 +19,12 @@ Query parameters for paginated routes. These parameters should be used on GET ro ### Formats - + ### Changelog @@ -38,7 +43,12 @@ Body parameters for paginated routes. These parameters should be used on POST an ### Formats - + ### Changelog @@ -59,7 +69,12 @@ Details about the paginated results. This model should included in the response ### Formats - + ### Changelog diff --git a/website/src/content/docs/protocol/sorting.mdx b/website/src/content/docs/protocol/sorting.mdx index fe6e885dc..bd135911a 100644 --- a/website/src/content/docs/protocol/sorting.mdx +++ b/website/src/content/docs/protocol/sorting.mdx @@ -44,7 +44,12 @@ Query parameters for sorting. These parameters should be used on GET routes that ### Formats - + ### Changelog @@ -64,7 +69,12 @@ Body parameters for sorting. These parameters should be used on POST and PUT rou ### Formats - + ### Changelog @@ -85,7 +95,12 @@ Information about the sort order of the items returned. This model should be inc ### Formats - + ### Changelog diff --git a/website/src/lib/schema/schema-doc-mapper.ts b/website/src/lib/schema/schema-doc-mapper.ts index ce368c976..ebecf760c 100644 --- a/website/src/lib/schema/schema-doc-mapper.ts +++ b/website/src/lib/schema/schema-doc-mapper.ts @@ -1,7 +1,8 @@ -import { readdirSync, readFileSync } from "fs"; +import { readFileSync } from "fs"; import * as path from "path"; import yaml from "js-yaml"; import { Paths } from "./paths"; +import { listFilesByExtension } from "./source-declarations"; /** A `` or `` tag's `schema="Name"` attribute */ const SCHEMA_ATTRIBUTE = @@ -31,7 +32,7 @@ export function buildSchemaDocMap( ): Map { const map = new Map(); - for (const file of listPages(protocolDocsDir)) { + for (const file of listFilesByExtension(protocolDocsDir, ".mdx")) { const content = readFileSync(file, "utf-8"); const docPath = "/" + @@ -82,23 +83,6 @@ function inlineSchemas( return result; } -/** Lists the MDX pages under a directory, in a stable order. */ -function listPages(dir: string): string[] { - const files: string[] = []; - const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => - a.name < b.name ? -1 : a.name > b.name ? 1 : 0, - ); - for (const entry of entries) { - const fullPath = path.join(dir, entry.name); - if (entry.isDirectory()) { - files.push(...listPages(fullPath)); - } else if (entry.isFile() && entry.name.endsWith(".mdx")) { - files.push(fullPath); - } - } - return files; -} - /** * Schema documentation mapping service. Builds the map from the protocol * pages the first time it's asked, once per build. diff --git a/website/src/lib/schema/source-declarations.ts b/website/src/lib/schema/source-declarations.ts index fcd8399ad..52ea162c0 100644 --- a/website/src/lib/schema/source-declarations.ts +++ b/website/src/lib/schema/source-declarations.ts @@ -70,6 +70,21 @@ const SOURCES: Record< const indexes = new Map>(); +/** The render the indexes were last read for, if any */ +let indexedForRender: object | undefined; + +/** + * Makes the next lookup re-read the sources, once per render. The dev server + * calls this with the request's `Astro.locals`, so a page reload shows a + * source edit while the several tabs on one page still share one read. A + * production build never calls it, so it reads the sources once per build. + */ +export function refreshDeclarationsForRender(render: object): void { + if (render === indexedForRender) return; + indexedForRender = render; + indexes.clear(); +} + /** * TypeSpec namespaces whose declarations a bare name never refers to. * `CommonGrants.Patch` holds compile-time mirrors of the organization models @@ -136,7 +151,7 @@ function matchDeclarations( * its Zod schemas `Schema`. A page names the declaration explicitly * when an SDK doesn't follow this (its enums, for example, end in `Enum`). */ -export function conventionalName( +function conventionalName( language: SourceLanguage, schemaName: string, ): string { @@ -161,7 +176,8 @@ export function findSchemaDeclaration( * declaration's name, for an SDK that names it differently; or lists several * names, to show a template with the model built from it. Several * declarations must be in one file; each is shown whole, in the order listed, - * separated by a blank line. + * separated by as many blank lines as the source has above each later one + * (two between Python classes, one in TypeSpec). * * @throws if a declaration can't be found */ @@ -183,7 +199,7 @@ export function findSnippet( path: found[0].path, startLine: Math.min(...found.map((d) => d.startLine)), endLine: Math.max(...found.map((d) => d.endLine)), - code: found.map((d) => d.code).join("\n\n"), + code: joinAsInSource(found), }; } if (typeof requested === "string") { @@ -197,6 +213,25 @@ export function findSnippet( return findSchemaDeclaration(language, schemaName); } +/** Joins declarations from one file with the blank lines above each in the source. */ +function joinAsInSource(found: FoundDeclaration[]): string { + const lines = readFileSync( + path.join(Paths.REPO_ROOT, found[0].path), + "utf-8", + ).split("\n"); + return found + .map((declaration, i) => { + if (i === 0) return declaration.code; + let blanks = 0; + for (let line = declaration.startLine - 2; line >= 0; line--) { + if (lines[line].trim() !== "") break; + blanks++; + } + return "\n".repeat(Math.max(blanks, 1)) + declaration.code; + }) + .join("\n"); +} + /** * Links to a declaration's lines in the repository on GitHub. Keeps the * double slash the docs have always published. @@ -210,7 +245,7 @@ export function sourceUrl( return `https://github.com/HHS/simpler-grants-protocol/tree/main//${filePath}${lines}`; } -/** Lists every declaration in a language's source, by name, once per build. */ +/** Lists every declaration in a language's source, by name, until the next refresh. */ function getIndex(language: SourceLanguage): Map { const cached = indexes.get(language); if (cached) return cached; @@ -218,7 +253,7 @@ function getIndex(language: SourceLanguage): Map { const { dir, extension, list } = SOURCES[language]; const index = new Map(); - for (const file of listFiles(dir, extension)) { + for (const file of listFilesByExtension(dir, extension)) { const relativePath = path .relative(Paths.REPO_ROOT, file) .split(path.sep) @@ -242,47 +277,21 @@ function getIndex(language: SourceLanguage): Map { return index; } -/** Lists files with an extension under a directory, in a stable order. */ -function listFiles(dir: string, extension: string): string[] { - const files: string[] = []; - const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => - a.name.localeCompare(b.name), - ); - for (const entry of entries) { - const fullPath = path.join(dir, entry.name); - if (entry.isDirectory()) { - files.push(...listFiles(fullPath, extension)); - } else if (entry.isFile() && entry.name.endsWith(extension)) { - files.push(fullPath); - } - } - return files; +/** + * Lists the files with an extension under a directory, recursively, sorted by + * path in code-point order so the result is the same on every machine. + */ +export function listFilesByExtension(dir: string, extension: string): string[] { + return readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(extension)) + .map((entry) => path.join(entry.parentPath, entry.name)) + .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); } // ############################################################################ // Shared helpers // ############################################################################ -/** Converts a character offset to a 1-based line number. */ -function lineAt(lineStarts: number[], offset: number): number { - let low = 0; - let high = lineStarts.length - 1; - while (low < high) { - const mid = Math.ceil((low + high) / 2); - if (lineStarts[mid] <= offset) low = mid; - else high = mid - 1; - } - return low + 1; -} - -function getLineStarts(source: string): number[] { - const starts = [0]; - for (let i = 0; i < source.length; i++) { - if (source[i] === "\n") starts.push(i + 1); - } - return starts; -} - /** Builds a declaration from whole lines of the source. */ function fromLines( lines: string[], @@ -330,7 +339,8 @@ export function listTypeSpecDeclarations(source: string): Declaration[] { throw new Error(`TypeSpec source doesn't parse: ${messages}`); } - const lineStarts = getLineStarts(source); + const lineOf = (offset: number) => + ast.file.getLineAndCharacterOfPosition(offset).line + 1; const lines = source.split("\n"); const declarations: Declaration[] = []; @@ -364,8 +374,8 @@ export function listTypeSpecDeclarations(source: string): Declaration[] { ...fromLines( lines, name, - lineAt(lineStarts, statement.pos), - lineAt(lineStarts, statement.end - 1), + lineOf(statement.pos), + lineOf(statement.end - 1), ), namespace: current.join(".") || undefined, }); @@ -531,8 +541,3 @@ export function listPythonDeclarations(source: string): Declaration[] { return declarations; } - -/** Clears the cached source indexes (for tests). */ -export function clearDeclarationCache(): void { - indexes.clear(); -} From b3245dfd90aa5182f39d2811f5bd9094bc8abea8 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 07:17:21 -0800 Subject: [PATCH 09/20] docs(website): document version negotiation for v0.6.0 Move the specification page to v0.6.0, correct the patch rule, and add the version negotiation rules from ADR 0032, including the successor-version link that announces a change of default. Add the discovery route to the routes tables, v0.6.0 migration notes, and a Versioning page that explains the model with the ADR's examples. --- website/astro.config.mjs | 4 + .../docs/protocol/specification/index.md | 113 ++++++- .../src/content/docs/protocol/versioning.mdx | 292 ++++++++++++++++++ 3 files changed, 405 insertions(+), 4 deletions(-) create mode 100644 website/src/content/docs/protocol/versioning.mdx diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 2762826fa..b31f90028 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -193,6 +193,10 @@ export default defineConfig({ label: "Authentication and scopes", link: "protocol/auth", }, + { + label: "Versioning", + link: "protocol/versioning", + }, ], }, { diff --git a/website/src/content/docs/protocol/specification/index.md b/website/src/content/docs/protocol/specification/index.md index d50bd7aa4..534baa8e2 100644 --- a/website/src/content/docs/protocol/specification/index.md +++ b/website/src/content/docs/protocol/specification/index.md @@ -1,10 +1,10 @@ --- -title: CommonGrants protocol v0.5.0 +title: CommonGrants protocol v0.6.0 description: A specification for the CommonGrants protocol. --- :::tip[Version History] -This is the current specification (v0.5.0). View previous versions: +This is the current specification (v0.6.0). View previous versions: - [v0.1.0](/protocol/specification/v0_1_0) - Original draft specification ::: @@ -99,19 +99,116 @@ The CommonGrants protocol follows the `Major.Minor.Patch` versioning scheme, whe - Adding new optional fields to existing schemas; - Adding new options to existing enum fields; or - Making other changes that introduce new functionality without making existing implementations non-compliant. -- the `Patch` version is incremented when the protocol is updated in a backwards-compatible way that adds new optional functionality. +- the `Patch` version is incremented when the protocol is updated in ways that don't change its contract. A patch never changes schemas, validation, required routes, or status codes; a fix that changes any of these is published as a new `Minor` or `Major` version. Patch changes may include: - Updating the descriptions or metadata of existing routes, operations, and schemas in ways that don't change their behavior; - Fixing typos or other minor changes that don't affect the protocol's behavior; or - - Making other changes that neither introduce new functionality nor make existing implementations non-compliant. + - Making other changes that leave schemas, validation, required routes, and status codes unchanged. :::caution Because experimental routes and operations are considered unstable, breaking changes can be made to these routes and operations without incrementing the `Major` version. ::: +A CommonGrants API MAY serve more than one protocol version. A client selects a version with the CommonGrants version request header, `CG-Version`, and the server reports the version it served with the CommonGrants served-version response header, `CG-Version-Served`. The rest of this section defines how version negotiation works. The [Versioning](/protocol/versioning) page explains it with examples, and [ADR 0032](/governance/adr/0032-api-version-negotiation/) records the rationale. + +The headers, version errors, and discovery route are declared from v0.6.0, and the published v0.1.0 through v0.5.0 contracts don't change. A server that adopts version negotiation applies these rules to every protocol version it serves, including v0.5.0 and earlier. + +It is RECOMMENDED that a server move all its routes to a new version at the same time. A server MAY instead serve different versions on different routes, and advertise those routes in [discovery](#discovering-supported-versions). + +#### Requesting a version + +- A client selects a version only with the `CG-Version` request header. Servers MUST NOT read a version from the URL path, the query string, the `Accept` header, or a vendor media type, and MUST NOT fall back to one. +- `CG-Version` applies only to protocol routes under `/common-grants/`, relative to the API's base URL. Servers MUST ignore it on custom routes and on the discovery route. A host API MAY mount the protocol routes under its own path, such as `/api/v2/common-grants/`; the host's path version and `CG-Version` are independent. +- The value MUST be a full published protocol version: three dot-separated numbers with no leading zeros, such as `0.5.0`. A `v` prefix, a short form such as `0.5`, ranges, and aliases are malformed. The header name is case-insensitive, and servers trim surrounding whitespace before matching the format. +- A request MUST carry at most one value. Because a proxy may fold two header lines into one comma-separated line ([RFC 9110 ยง5.3](https://www.rfc-editor.org/rfc/rfc9110#section-5.3)), servers MUST treat two header lines, or a comma in the value, as more than one value, and MUST check for that before checking the format. +- Servers match the requested version on major and minor. A server hosts one patch of each major and minor version it serves, reports that full version wherever it lists or reports it, and serves a request for any patch of that major and minor in the version it hosts. For example, a request for `0.5.0` is served by a server hosting `0.5.1`. +- A server MUST NOT serve a different major or minor version than the one requested, even if it serves only one version. +- A request without `CG-Version` is served in the server's default version: the baseline default, or the route's own default when discovery lists the route. A server adopting version negotiation MUST set its default to the version it already serves, and adding versions MUST NOT change the default. A default changes only as described in [Changing the default version](#changing-the-default-version). +- One request is served in one version. The whole response, including nested objects, MUST follow that version's schemas, and the request body MUST be validated against them. +- A server matches the route, then resolves the version, then validates the request body, all before any side effect. A route the server doesn't implement returns an ordinary 404. A rejected write changes nothing. + +#### Version response headers + +- Every response produced after a version is selected MUST carry `CG-Version-Served` with the full version served, including responses served by default and errors such as a missing record or a request body that fails validation. Responses to 401 and 403 MAY omit it, because authentication can run before a version is selected. [Version errors](#version-errors) MUST NOT carry it. +- The served version travels in headers only. Response bodies are the same as in a server that doesn't negotiate versions. +- A successful response without `CG-Version-Served` is unconfirmed: the server may predate version negotiation, or something between the client and the server dropped the request header. A response whose served major or minor version differs from the one requested wasn't served as requested. Clients can't assume either was served in the version they asked for. +- Every cacheable response that depends on `CG-Version` MUST carry `Vary: CG-Version`, including responses served by default. +- Cross-origin servers MUST allow `CG-Version` in `Access-Control-Allow-Headers`, and MUST expose `CG-Version-Served`, `Deprecation`, `Sunset`, and `Link` in `Access-Control-Expose-Headers`. +- Ordinary responses MUST NOT carry a header listing the supported versions. The discovery route and the `version.unsupported` and `version.retired` errors carry that list. +- Version header names use hyphens and no `X-` prefix. + +#### Version errors + +A version problem returns one of the following errors. It MUST NOT return 404 or 410, because both can be cached by default and clients read them as a missing route or record. + +| Case | `code` | Status | +| ------------------------------------------------------------------------------------------------------- | --------------------- | ------ | +| Malformed version, such as `banana` or `0.5` | `version.malformed` | 400 | +| More than one version value, as two header lines or one comma-separated line, even the same value twice | `version.conflict` | 400 | +| Version this server, or this route, doesn't serve | `version.unsupported` | 406 | +| Version retired from this server or this route | `version.retired` | 406 | + +Each error uses the standard [error response](/protocol/responses/error) envelope, with one entry in `errors` whose `field` is `CG-Version` and whose `code` is one of the values above. Every entry carries `supported` and `defaultVersion`, which describe the route that was called, and the server's discovery URL in `discovery` when it publishes one. `version.unsupported` and `version.retired` also carry the `requested` version and a `scope` of `deployment` (the whole server) or `operation` (only this route). `version.retired` also carries the `sunset` date in RFC 3339 format. `version.malformed` carries the `requested` value as sent, and `version.conflict` omits `requested`. `code` values are stable, so clients branch on them. The [Versioning](/protocol/versioning#version-error-schemas) page shows the full schemas. + +After a version's sunset date, a server answers requests for it with `version.retired` for a period it chooses, and MAY answer `version.unsupported` after that. + +#### Discovering supported versions + +`GET /common-grants/versions` lists the protocol versions a server serves. The route is OPTIONAL, but a server that serves more than one protocol version MUST implement it. The route status in the [routes tables](#version-routes) is optional, because a route status can't express this condition. + +- The route MUST NOT require stronger authentication than the API's required routes, and SHOULD be readable without authentication. +- It takes no request parameters, ignores `CG-Version`, and never returns a version error. Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. +- It returns the standard success envelope. In `data`, `versions` and `defaultVersion` are the baseline, which applies to every route without an entry in `operations`. A route whose versions differ from the baseline has an entry in `operations`, keyed by its HTTP method and its path as published in the protocol, such as `GET /common-grants/forms/{formId}`. Path parameter names are ignored when matching a key to a route. A server whose routes all serve the baseline omits `operations`. +- A route serves a version only if that version of the protocol defines the route. +- Every route a baseline version requires serves that version, so the baseline is a compliance claim: the server is compliant with every version in it. Supporting a version doesn't mean implementing that version's optional or experimental routes. +- A default is always one of the versions it applies to. +- The optional `upcomingDefault` and `deprecated` fields appear only while a change is pending: at the top level for the baseline, or in a route's entry for that route only. Their dates use RFC 3339. +- Fields are only ever added to the discovery response. Clients MUST ignore fields they don't recognize, and accept version values published after they were built. + +If the discovery route returns 404, the server serves one version that it doesn't advertise. + +#### Retiring a version + +A server retires a version the same way whether the version is leaving the whole server or one route: + +- On every response served in that version on the affected routes, the server MUST send the `Deprecation` header ([RFC 9745](https://www.rfc-editor.org/rfc/rfc9745)), and, once a date is set, the `Sunset` header ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594)). `Deprecation` uses the `@` form, such as `@1796083200`, and `Sunset` uses an HTTP-date, such as `Tue, 01 Jun 2027 00:00:00 GMT`. Both headers keep their standard meaning and always describe the version the response was served in. +- Alongside them, the server MUST send `Link` headers ([RFC 8288](https://www.rfc-editor.org/rfc/rfc8288)) with `rel="deprecation"` and `rel="sunset"` pointing to migration documentation, and with `rel="version-history"` pointing to the discovery route. +- Discovery MUST list the version under `deprecated` with its `deprecation` date and, once set, its `sunset` date: at the top level when the version is leaving the whole server, or in the route's entry when it's leaving one route. +- After the sunset date, the server answers requests for the version with `version.retired`, as described in [Version errors](#version-errors). +- If the version is a default, the server MUST move that default forward to the next newer version no later than the sunset date, announcing the change as described in [Changing the default version](#changing-the-default-version). Responses served by default then carry both the retirement headers and the `successor-version` link. A server can't retire a default unless it serves a newer version for the default to move to. +- A required route can't drop a baseline version that requires the route, so retiring that version from the route means retiring it from the baseline. +- Experimental routes MAY drop a version without notice. + +#### Changing the default version + +A server MAY change a default version whether or not it keeps serving the old one. Before the change, it MUST announce it: + +- On responses served by default from the affected routes, the server MUST send a `Link` header with `rel="successor-version"` ([RFC 5829](https://www.rfc-editor.org/rfc/rfc5829)) pointing to documentation for the new default, and a `Link` header with `rel="version-history"` pointing to the discovery route. +- Discovery MUST show `upcomingDefault` with the new default's `version` and the `date` it takes effect: at the top level for the baseline default, which also covers route entries whose default follows the baseline, or in a route's entry for that route's own default. +- The server MUST NOT send `Deprecation` or `Sunset` for a default change. They appear on responses served by default only when the default version is itself retiring. + +Responses to requests that name a version don't change. At the announced date, the default moves to the next newer version it applies to. + ### Migration notes Guidance for implementers and consumers moving between protocol versions. Each entry is written as its changes land and is reviewed again before the version is published. +#### v0.6.0 + +v0.6.0 adds version negotiation and is purely additive: nothing changes for existing clients or servers. The published v0.1.0 through v0.5.0 contracts are unchanged, and a server that doesn't adopt version negotiation stays compliant with the versions it already implements. + +##### Version negotiation + +- Every protocol route declares the optional `CG-Version` request header, and its responses declare `CG-Version-Served`, `Vary`, `Deprecation`, `Sunset`, and `Link`. 401 and 403 responses declare `CG-Version-Served` as optional. See [Version response headers](#version-response-headers). +- Every protocol route declares the version errors: 400 `version.malformed` and `version.conflict`, and 406 `version.unsupported` and `version.retired`. See [Version errors](#version-errors). +- The new optional `GET /versions` route lists the versions a server serves. A server that serves more than one version MUST implement it. See [Discovering supported versions](#discovering-supported-versions). +- A new `protocolVersion` scalar describes a full `MAJOR.MINOR.PATCH` protocol version, such as `0.6.0`. + +##### Adopting version negotiation + +A server that adopts version negotiation pins its default to the version it already serves, so clients that send no `CG-Version` keep getting the contract they use today. It sends `CG-Version-Served` on every response produced after a version is selected, whatever version it serves, and `Vary: CG-Version` on cacheable responses. A client of an older version gets one extra response header and, because it sends no `CG-Version`, never a version error. + +A client can start sending `CG-Version` to fix the contract it's served in, read `CG-Version-Served` to confirm what it got, call the discovery route to find the versions a server serves, and watch for `Deprecation`, `Sunset`, and `successor-version` links. The [Versioning](/protocol/versioning) page walks through each step. + #### v0.5.0 v0.5.0 renames two fields on competitions and forms, which is a breaking change for anyone who serializes or reads them. Every other change is additive and optional, and the award routes move from experimental to optional. @@ -311,6 +408,14 @@ While omitted for brevity in the following table, all protocol-defined routes MU The award routes were experimental in v0.4.0 and are optional as of v0.5.0, which means a CommonGrants API MAY implement them. They are optional rather than required because an implementation that publishes funding opportunities does not necessarily hold award data, and making the routes required would render those implementations non-compliant. Because they are no longer experimental, breaking changes to these routes now follow the versioning rules in [Versions](#versions) rather than the exemption that applies to experimental routes. See the [v0.5.0 migration notes](#v050) for what the change means when validating an implementation against a v0.4.0 base spec. +#### Version routes + +| Route | Status | Description | +| --------------- | -------- | ------------------------------------------ | +| `GET /versions` | Optional | List the protocol versions this API serves | + +The version discovery route was added in v0.6.0. It is optional, but a server that serves more than one protocol version MUST implement it. A route status can't express that condition, so the requirement lives in this text rather than in the route's status. See [Discovering supported versions](#discovering-supported-versions). + #### Organization routes | Route | Status | Description | diff --git a/website/src/content/docs/protocol/versioning.mdx b/website/src/content/docs/protocol/versioning.mdx new file mode 100644 index 000000000..f9b974880 --- /dev/null +++ b/website/src/content/docs/protocol/versioning.mdx @@ -0,0 +1,292 @@ +--- +title: Versioning +description: How clients find, request, and confirm a CommonGrants protocol version, and how they learn that a version is retiring or a default is changing. +sidebar: + order: 7 +--- + +import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; +import SchemaTable from "@/components/SchemaTable.astro"; + +A CommonGrants API can serve more than one protocol version. A client asks for the version it was built for with the CommonGrants version request header, `CG-Version`, and every response reports the version it was served in with the CommonGrants served-version response header, `CG-Version-Served`. A server lists the versions it serves at a discovery route, and announces retirement with the standard `Deprecation`, `Sunset`, and `Link` headers. + +This page summarizes the model for clients and implementers. The normative rules are in the [Versions](/protocol/specification#versions) section of the specification, and the rationale and the options considered are in [ADR 0032](/governance/adr/0032-api-version-negotiation/). Version negotiation was added in protocol version v0.6.0. + +## Finding the supported versions + +Call `GET /common-grants/versions`, relative to the API's base URL. You don't need to send `CG-Version`, and the route never returns a version error. Here's a server whose baseline is 0.4.0, which also serves form detail in 0.5.0 and serves its form list only in 0.5.0: + +```json +{ + "status": 200, + "message": "Success", + "data": { + "versions": ["0.4.0"], + "defaultVersion": "0.4.0", + "operations": { + "GET /common-grants/forms": { + "versions": ["0.5.0"], + "defaultVersion": "0.5.0" + }, + "GET /common-grants/forms/{formId}": { + "versions": ["0.4.0", "0.5.0"], + "defaultVersion": "0.4.0" + } + } + } +} +``` + +`versions` and `defaultVersion` are the baseline: every route without an entry under `operations` serves them. A route listed under `operations` uses its own entry instead. A route is identified by its HTTP method and its path as published in the protocol, and path parameter names are ignored when matching, so `{id}` and `{formId}` in the same position identify the same route. + +Version values are strings in the `0.5.0` format, not a closed list, so accept versions published after your client was built. Ignore fields you don't recognize: fields are only ever added to this response. + +If discovery returns 404, treat the server as serving one version it doesn't advertise. If its responses also lack `CG-Version-Served`, that version is unknown and every response is unconfirmed. + +The route is optional, but a server that serves more than one version must implement it. It should be readable without authentication. + +## Asking for a version + +Send the full version in the `CG-Version` request header: + +```http +GET /common-grants/opportunities/123 HTTP/1.1 +CG-Version: 0.5.0 + +HTTP/1.1 200 OK +CG-Version-Served: 0.5.1 +Vary: CG-Version +``` + +Send one value per request. The value is three dot-separated numbers with no leading zeros. A `v` prefix, a short form such as `0.5`, ranges, and aliases are malformed. The header only means something on routes under `/common-grants/`, and a version in the path or query string is never read as a selector. + +Servers match on major and minor version, so a request for `0.5.0` is served by a server hosting `0.5.1`. A server never substitutes a different major or minor version, even if it serves only one. + +### If you don't ask + +You're served in the server's default: the baseline default, or the route's own default when the route has an entry in discovery. The default doesn't change when the server adds versions. It changes only after an announced default change (see [Learning that the default is changing](#learning-that-the-default-is-changing)). If you need a fixed contract, send a version. + +### Confirming the version you got + +Read `CG-Version-Served`. It reports the full version served, so it can differ from your request in the patch number only. + +- A successful response without it is unconfirmed: the server may predate version negotiation, or something in between dropped your header. Don't read it as the version you asked for. +- A served version whose major or minor number differs from the one you asked for wasn't served as requested. Don't treat it as your version. + +Browser clients on another origin can read `CG-Version-Served`, because cross-origin servers must expose it. + +## Version errors + +| Case | `code` | Status | +| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------ | +| Malformed version, such as `banana` or `0.5` | `version.malformed` | 400 | +| Version this server doesn't serve | `version.unsupported`, scope `deployment` | 406 | +| Version this route doesn't serve | `version.unsupported`, scope `operation` | 406 | +| Version retired from this server or this route | `version.retired`, scope `deployment` or `operation` | 406 | +| More than one version value, as two header lines or one comma-separated line, even the same value twice | `version.conflict` | 400 | + +Details are entries in the standard [error response](/protocol/responses/error) envelope. `supported` and `defaultVersion` always describe the route you called, so retry with a listed version: + +```json +{ + "status": 406, + "message": "The requested CommonGrants version is not available for this route", + "errors": [ + { + "field": "CG-Version", + "code": "version.unsupported", + "message": "Version 0.4.0 is not served by GET /common-grants/forms. Supported versions: 0.5.0", + "requested": "0.4.0", + "supported": ["0.5.0"], + "scope": "operation", + "defaultVersion": "0.5.0", + "discovery": "https://grants.example.org/common-grants/versions" + } + ] +} +``` + +`version.retired` also carries `sunset`, in RFC 3339 format. `version.conflict` omits `requested`, and its message names the values received. `code` values are stable; branch on them. A version problem never returns 404 or 410, so a 404 still means a missing route or record. Version errors don't carry `CG-Version-Served`, because no version was selected. + +A request body is validated against the version it's served in, so a 0.4.0 search that uses a filter that exists only in 0.5.0 gets an ordinary 400 validation error, with `CG-Version-Served: 0.4.0`. A rejected write changes nothing, and the server never retries it under another version. + +## Learning that a version is retiring + +Responses served in a retiring version carry `Deprecation`, then `Sunset` once a date is set, with `Link` headers to migration documentation and to discovery. These headers always describe the version you were served, and discovery lists the version under `deprecated` with its dates: + +```http +GET /common-grants/opportunities/123 HTTP/1.1 +CG-Version: 0.3.0 + +HTTP/1.1 200 OK +CG-Version-Served: 0.3.0 +Vary: CG-Version +Deprecation: @1796083200 +Sunset: Tue, 01 Jun 2027 00:00:00 GMT +Link: ; rel="deprecation" +Link: ; rel="sunset" +Link: ; rel="version-history" +``` + +The three dates use three formats: `Deprecation` uses the `@` form from [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745), `Sunset` uses an HTTP-date as in [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594), and discovery uses RFC 3339. + +After the sunset date, requests for any patch of that major and minor version get 406 `version.retired`, with the sunset date and the supported versions, for a period the server chooses. After that, the server may answer `version.unsupported` instead, so handle both the same way: retry with a version from `supported`. If the retired version was your default, the default has already moved to the next newer version. + +A single route retires a version the same way as the whole server. Experimental routes may drop a version without notice. + +## Learning that the default is changing + +If you send no version, responses from routes whose default is changing carry a `Link` header with `rel="successor-version"`, and discovery shows `upcomingDefault` with the date the change takes effect. These responses carry no `Deprecation` or `Sunset` unless the default version is itself retiring. If you send a version, nothing changes for you. + +```http +GET /common-grants/opportunities/123 HTTP/1.1 + +HTTP/1.1 200 OK +CG-Version-Served: 0.4.0 +Vary: CG-Version +Link: ; rel="successor-version" +Link: ; rel="version-history" +``` + +Here's the `data` payload of discovery for a server moving its default to 0.5.0 and retiring 0.3.0: + +```json +{ + "versions": ["0.3.0", "0.4.0", "0.5.0"], + "defaultVersion": "0.4.0", + "upcomingDefault": { + "version": "0.5.0", + "date": "2027-03-01T00:00:00Z" + }, + "deprecated": { + "0.3.0": { + "deprecation": "2026-12-01T00:00:00Z", + "sunset": "2027-06-01T00:00:00Z" + } + } +} +``` + +## Implementing version negotiation + +A server that serves one version needs very little: it reads `CG-Version` on routes under `/common-grants/`, rejects other major and minor versions, and reports what it serves. A server that adopts negotiation sets its default to the version it already serves, so its existing clients see no change. The specification's [Versions](/protocol/specification#versions) section is the full set of rules. In summary: + +- **Resolve the version.** Match the route, then resolve the version, then validate the request body against that version's schemas, all before any side effect. Check for more than one value before checking the format. Never read the version from the path, the query string, `Accept`, or a media type. +- **Send the version headers.** Send `CG-Version-Served` on every response produced after a version is selected, whatever version you serve, including errors such as a missing record. Responses to 401 and 403 may omit it, and version errors must not carry it. Send `Vary: CG-Version` on cacheable responses. Cross-origin servers allow `CG-Version` and expose `CG-Version-Served`, `Deprecation`, `Sunset`, and `Link`. +- **Publish discovery** if you serve more than one version. List the baseline, and add an `operations` entry only for routes that differ from it. A version in the baseline is a compliance claim: every route that version requires serves it. +- **Retire a version** by sending `Deprecation`, `Sunset`, and their `Link` headers on responses served in it, listing it under `deprecated` in discovery, and answering `version.retired` after the sunset. +- **Change a default** by sending the `successor-version` and `version-history` links on responses served by default, and showing `upcomingDefault` in discovery. Don't send `Deprecation` or `Sunset` for a default change. A retiring default moves forward to the next newer version no later than the sunset, so you can't retire a default without a newer version to move to. + +We recommend that servers move all their routes to a new version at the same time. A server can instead serve different versions on different routes and advertise those routes in discovery. + +## Schemas + +The SDKs don't declare the version negotiation schemas yet, so the formats below show the TypeSpec source only. + +### Discovery schemas + +#### VersionDiscovery + +The `data` payload of the `GET /versions` response. + + + + + +#### OperationVersions + +The versions a single route serves, when they differ from the baseline. + + + + + +#### UpcomingDefault + +A scheduled change to a default version. + + + + + +#### VersionRetirement + +The retirement schedule for a deprecated version. + + + + + +### Version error schemas + +#### VersionMalformedError + +A 400 response to a `CG-Version` value that isn't a full `MAJOR.MINOR.PATCH` version. + + + + + +#### VersionConflictError + +A 400 response to a request that sent more than one `CG-Version` value. + + + + + +#### VersionUnsupportedError + +A 406 response to a version this server or route doesn't serve. + + + + + +#### VersionRetiredError + +A 406 response to a version that was retired from this server or route. + + + + + +#### VersionErrorDetail + +The fields every version error entry carries, describing the route that was called. + + + + + +#### VersionMalformedDetail + + + + + +#### VersionConflictDetail + + + + + +#### VersionUnsupportedDetail + + + + + +#### VersionRetiredDetail + + + + + +#### VersionErrorScope + +Whether a version is unavailable on the whole server or only on the route called. + + + + From 4ddc23470183a0b8cf7597b6a80f66d8c3410a7a Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 07:20:41 -0800 Subject: [PATCH 10/20] docs(website): state a discovery 404 as what a client assumes --- website/src/content/docs/protocol/specification/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/content/docs/protocol/specification/index.md b/website/src/content/docs/protocol/specification/index.md index 534baa8e2..c205a20af 100644 --- a/website/src/content/docs/protocol/specification/index.md +++ b/website/src/content/docs/protocol/specification/index.md @@ -164,7 +164,7 @@ After a version's sunset date, a server answers requests for it with `version.re - The optional `upcomingDefault` and `deprecated` fields appear only while a change is pending: at the top level for the baseline, or in a route's entry for that route only. Their dates use RFC 3339. - Fields are only ever added to the discovery response. Clients MUST ignore fields they don't recognize, and accept version values published after they were built. -If the discovery route returns 404, the server serves one version that it doesn't advertise. +A client that gets 404 from the discovery route treats the server as serving one version that it doesn't advertise. #### Retiring a version From 74ca36bd70c13ba4a8ba30b977378946105da391 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 07:25:11 -0800 Subject: [PATCH 11/20] docs(website): describe the version error scopes and detail entries --- website/src/content/docs/protocol/versioning.mdx | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/website/src/content/docs/protocol/versioning.mdx b/website/src/content/docs/protocol/versioning.mdx index f9b974880..d22e0cdee 100644 --- a/website/src/content/docs/protocol/versioning.mdx +++ b/website/src/content/docs/protocol/versioning.mdx @@ -261,24 +261,32 @@ The fields every version error entry carries, describing the route that was call #### VersionMalformedDetail +The `CG-Version` value isn't a full `MAJOR.MINOR.PATCH` version. + #### VersionConflictDetail +The request sent more than one `CG-Version` value. + #### VersionUnsupportedDetail +The requested version isn't served by this server or this route. + #### VersionRetiredDetail +The requested version was retired from this server or this route. + @@ -287,6 +295,9 @@ The fields every version error entry carries, describing the route that was call Whether a version is unavailable on the whole server or only on the route called. - +| Value | Description | +| ---------- | ---------------------------------------------------- | +| deployment | The server doesn't serve the version on any route | +| operation | The server serves the version, but not on this route | From 06f53bfd6a9f510ea12bdf4fe5320551fe13145a Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 07:44:22 -0800 Subject: [PATCH 12/20] docs(website): bind the version rules and tighten the versioning wording --- .../content/docs/protocol/specification/index.md | 16 ++++++++-------- website/src/content/docs/protocol/versioning.mdx | 8 +++++--- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/website/src/content/docs/protocol/specification/index.md b/website/src/content/docs/protocol/specification/index.md index c205a20af..57f76276a 100644 --- a/website/src/content/docs/protocol/specification/index.md +++ b/website/src/content/docs/protocol/specification/index.md @@ -118,13 +118,13 @@ It is RECOMMENDED that a server move all its routes to a new version at the same - A client selects a version only with the `CG-Version` request header. Servers MUST NOT read a version from the URL path, the query string, the `Accept` header, or a vendor media type, and MUST NOT fall back to one. - `CG-Version` applies only to protocol routes under `/common-grants/`, relative to the API's base URL. Servers MUST ignore it on custom routes and on the discovery route. A host API MAY mount the protocol routes under its own path, such as `/api/v2/common-grants/`; the host's path version and `CG-Version` are independent. -- The value MUST be a full published protocol version: three dot-separated numbers with no leading zeros, such as `0.5.0`. A `v` prefix, a short form such as `0.5`, ranges, and aliases are malformed. The header name is case-insensitive, and servers trim surrounding whitespace before matching the format. +- The value MUST be a full published protocol version: three dot-separated numbers with no leading zeros, such as `0.5.0`. A `v` prefix, a short form such as `0.5`, ranges, and aliases are malformed. The header name is case-insensitive, and servers MUST trim surrounding whitespace before matching the format. - A request MUST carry at most one value. Because a proxy may fold two header lines into one comma-separated line ([RFC 9110 ยง5.3](https://www.rfc-editor.org/rfc/rfc9110#section-5.3)), servers MUST treat two header lines, or a comma in the value, as more than one value, and MUST check for that before checking the format. -- Servers match the requested version on major and minor. A server hosts one patch of each major and minor version it serves, reports that full version wherever it lists or reports it, and serves a request for any patch of that major and minor in the version it hosts. For example, a request for `0.5.0` is served by a server hosting `0.5.1`. +- Servers MUST match the requested version on major and minor. A server MUST host one patch of each major and minor version it serves and MUST report that full version wherever it lists or reports it. It serves a request for any patch of that major and minor in the version it hosts. For example, a request for `0.5.0` is served by a server hosting `0.5.1`. - A server MUST NOT serve a different major or minor version than the one requested, even if it serves only one version. - A request without `CG-Version` is served in the server's default version: the baseline default, or the route's own default when discovery lists the route. A server adopting version negotiation MUST set its default to the version it already serves, and adding versions MUST NOT change the default. A default changes only as described in [Changing the default version](#changing-the-default-version). - One request is served in one version. The whole response, including nested objects, MUST follow that version's schemas, and the request body MUST be validated against them. -- A server matches the route, then resolves the version, then validates the request body, all before any side effect. A route the server doesn't implement returns an ordinary 404. A rejected write changes nothing. +- A server MUST match the route, then resolve the version, then validate the request body, all before any side effect. A route the server doesn't implement returns an ordinary 404. A rejected write MUST change nothing. #### Version response headers @@ -149,11 +149,11 @@ A version problem returns one of the following errors. It MUST NOT return 404 or Each error uses the standard [error response](/protocol/responses/error) envelope, with one entry in `errors` whose `field` is `CG-Version` and whose `code` is one of the values above. Every entry carries `supported` and `defaultVersion`, which describe the route that was called, and the server's discovery URL in `discovery` when it publishes one. `version.unsupported` and `version.retired` also carry the `requested` version and a `scope` of `deployment` (the whole server) or `operation` (only this route). `version.retired` also carries the `sunset` date in RFC 3339 format. `version.malformed` carries the `requested` value as sent, and `version.conflict` omits `requested`. `code` values are stable, so clients branch on them. The [Versioning](/protocol/versioning#version-error-schemas) page shows the full schemas. -After a version's sunset date, a server answers requests for it with `version.retired` for a period it chooses, and MAY answer `version.unsupported` after that. +After a version's sunset date, requests for it get `version.retired`, as described in [Retiring a version](#retiring-a-version). #### Discovering supported versions -`GET /common-grants/versions` lists the protocol versions a server serves. The route is OPTIONAL, but a server that serves more than one protocol version MUST implement it. The route status in the [routes tables](#version-routes) is optional, because a route status can't express this condition. +`GET /common-grants/versions` lists the protocol versions a server serves. The route is OPTIONAL, but a server that serves more than one protocol version MUST implement it (see [Version routes](#version-routes)). - The route MUST NOT require stronger authentication than the API's required routes, and SHOULD be readable without authentication. - It takes no request parameters, ignores `CG-Version`, and never returns a version error. Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. @@ -173,7 +173,7 @@ A server retires a version the same way whether the version is leaving the whole - On every response served in that version on the affected routes, the server MUST send the `Deprecation` header ([RFC 9745](https://www.rfc-editor.org/rfc/rfc9745)), and, once a date is set, the `Sunset` header ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594)). `Deprecation` uses the `@` form, such as `@1796083200`, and `Sunset` uses an HTTP-date, such as `Tue, 01 Jun 2027 00:00:00 GMT`. Both headers keep their standard meaning and always describe the version the response was served in. - Alongside them, the server MUST send `Link` headers ([RFC 8288](https://www.rfc-editor.org/rfc/rfc8288)) with `rel="deprecation"` and `rel="sunset"` pointing to migration documentation, and with `rel="version-history"` pointing to the discovery route. - Discovery MUST list the version under `deprecated` with its `deprecation` date and, once set, its `sunset` date: at the top level when the version is leaving the whole server, or in the route's entry when it's leaving one route. -- After the sunset date, the server answers requests for the version with `version.retired`, as described in [Version errors](#version-errors). +- After the sunset date, the server MUST answer requests for the version with `version.retired`, as described in [Version errors](#version-errors), for a period it chooses, and MAY answer `version.unsupported` after that. - If the version is a default, the server MUST move that default forward to the next newer version no later than the sunset date, announcing the change as described in [Changing the default version](#changing-the-default-version). Responses served by default then carry both the retirement headers and the `successor-version` link. A server can't retire a default unless it serves a newer version for the default to move to. - A required route can't drop a baseline version that requires the route, so retiring that version from the route means retiring it from the baseline. - Experimental routes MAY drop a version without notice. @@ -198,8 +198,8 @@ v0.6.0 adds version negotiation and is purely additive: nothing changes for exis ##### Version negotiation -- Every protocol route declares the optional `CG-Version` request header, and its responses declare `CG-Version-Served`, `Vary`, `Deprecation`, `Sunset`, and `Link`. 401 and 403 responses declare `CG-Version-Served` as optional. See [Version response headers](#version-response-headers). -- Every protocol route declares the version errors: 400 `version.malformed` and `version.conflict`, and 406 `version.unsupported` and `version.retired`. See [Version errors](#version-errors). +- Every protocol route except `GET /versions` declares the optional `CG-Version` request header, and its responses declare `CG-Version-Served`, `Vary`, `Deprecation`, `Sunset`, and `Link`. 401 and 403 responses declare `CG-Version-Served` as optional. See [Version response headers](#version-response-headers). +- Every protocol route except `GET /versions` declares the version errors: 400 `version.malformed` and `version.conflict`, and 406 `version.unsupported` and `version.retired`. See [Version errors](#version-errors). - The new optional `GET /versions` route lists the versions a server serves. A server that serves more than one version MUST implement it. See [Discovering supported versions](#discovering-supported-versions). - A new `protocolVersion` scalar describes a full `MAJOR.MINOR.PATCH` protocol version, such as `0.6.0`. diff --git a/website/src/content/docs/protocol/versioning.mdx b/website/src/content/docs/protocol/versioning.mdx index d22e0cdee..07ac63100 100644 --- a/website/src/content/docs/protocol/versioning.mdx +++ b/website/src/content/docs/protocol/versioning.mdx @@ -8,7 +8,7 @@ sidebar: import SchemaFormatTabs from "@/components/SchemaFormatTabs.astro"; import SchemaTable from "@/components/SchemaTable.astro"; -A CommonGrants API can serve more than one protocol version. A client asks for the version it was built for with the CommonGrants version request header, `CG-Version`, and every response reports the version it was served in with the CommonGrants served-version response header, `CG-Version-Served`. A server lists the versions it serves at a discovery route, and announces retirement with the standard `Deprecation`, `Sunset`, and `Link` headers. +A CommonGrants API can serve more than one protocol version. A client asks for the version it was built for with the CommonGrants version request header, `CG-Version`, and every response produced after a version is selected reports the version it was served in with the CommonGrants served-version response header, `CG-Version-Served`. A server lists the versions it serves at a discovery route, and announces retirement with the standard `Deprecation`, `Sunset`, and `Link` headers. This page summarizes the model for clients and implementers. The normative rules are in the [Versions](/protocol/specification#versions) section of the specification, and the rationale and the options considered are in [ADR 0032](/governance/adr/0032-api-version-negotiation/). Version negotiation was added in protocol version v0.6.0. @@ -62,9 +62,11 @@ Send one value per request. The value is three dot-separated numbers with no lea Servers match on major and minor version, so a request for `0.5.0` is served by a server hosting `0.5.1`. A server never substitutes a different major or minor version, even if it serves only one. +The value is always a CommonGrants protocol version, never a plugin's package version ([ADR 0022](/governance/adr/0022-plugin-framework/)). + ### If you don't ask -You're served in the server's default: the baseline default, or the route's own default when the route has an entry in discovery. The default doesn't change when the server adds versions. It changes only after an announced default change (see [Learning that the default is changing](#learning-that-the-default-is-changing)). If you need a fixed contract, send a version. +You're served in the server's default: the baseline default, or the route's own default when the route has an entry in discovery. The default doesn't change when the server adds versions. It changes only after an announced default change (see [Learning that the default is changing](#learning-that-the-default-is-changing)). If you need a fixed contract, send a version. Before 1.0, a new default may not be compatible with the old one. ### Confirming the version you got @@ -80,10 +82,10 @@ Browser clients on another origin can read `CG-Version-Served`, because cross-or | Case | `code` | Status | | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------ | | Malformed version, such as `banana` or `0.5` | `version.malformed` | 400 | +| More than one version value, as two header lines or one comma-separated line, even the same value twice | `version.conflict` | 400 | | Version this server doesn't serve | `version.unsupported`, scope `deployment` | 406 | | Version this route doesn't serve | `version.unsupported`, scope `operation` | 406 | | Version retired from this server or this route | `version.retired`, scope `deployment` or `operation` | 406 | -| More than one version value, as two header lines or one comma-separated line, even the same value twice | `version.conflict` | 400 | Details are entries in the standard [error response](/protocol/responses/error) envelope. `supported` and `defaultVersion` always describe the route you called, so retry with a listed version: From 742134c78dbe4a4a7129c03bbe556f421e3be0d1 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 08:50:16 -0800 Subject: [PATCH 13/20] docs(website): forbid retrying a rejected write under another version --- website/src/content/docs/protocol/specification/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/content/docs/protocol/specification/index.md b/website/src/content/docs/protocol/specification/index.md index 57f76276a..eba19f115 100644 --- a/website/src/content/docs/protocol/specification/index.md +++ b/website/src/content/docs/protocol/specification/index.md @@ -124,7 +124,7 @@ It is RECOMMENDED that a server move all its routes to a new version at the same - A server MUST NOT serve a different major or minor version than the one requested, even if it serves only one version. - A request without `CG-Version` is served in the server's default version: the baseline default, or the route's own default when discovery lists the route. A server adopting version negotiation MUST set its default to the version it already serves, and adding versions MUST NOT change the default. A default changes only as described in [Changing the default version](#changing-the-default-version). - One request is served in one version. The whole response, including nested objects, MUST follow that version's schemas, and the request body MUST be validated against them. -- A server MUST match the route, then resolve the version, then validate the request body, all before any side effect. A route the server doesn't implement returns an ordinary 404. A rejected write MUST change nothing. +- A server MUST match the route, then resolve the version, then validate the request body, all before any side effect. A route the server doesn't implement returns an ordinary 404. A rejected write MUST change nothing and MUST NOT be retried under another version. #### Version response headers From b64d2febae931766bdf85f1e1ab851c6376e11e8 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Mon, 9 Nov 2026 07:56:08 -0800 Subject: [PATCH 14/20] feat(core): add the versions discovery route Adds GET /common-grants/versions to the 0.6.0 base API, tagged optional, with the VersionDiscovery, OperationVersions, UpcomingDefault and VersionRetirement models and a protocolVersion type. The route lets a server publish its default version, the versions every route serves, per-route exceptions, an upcoming default and deprecated versions, per the API version negotiation ADR draft (#1159, #1372). Versions.v0_6 and Types.protocolVersion are stubs owned by #1386 and are dropped when that PR lands. The 0.1.0 through 0.5.0 OpenAPI documents are unchanged. Refs #1387 --- lib/core/lib/api.tsp | 20 +++ lib/core/lib/core/models/index.tsp | 1 + .../lib/core/models/version-discovery.tsp | 132 ++++++++++++++++++ lib/core/lib/core/routes/index.tsp | 1 + .../lib/core/routes/version-discovery.tsp | 49 +++++++ .../schemas/yaml/OperationVersions.yaml | 30 ++++ .../public/schemas/yaml/UpcomingDefault.yaml | 17 +++ .../public/schemas/yaml/VersionDiscovery.yaml | 75 ++++++++++ .../schemas/yaml/VersionRetirement.yaml | 17 +++ 9 files changed, 342 insertions(+) create mode 100644 lib/core/lib/core/models/version-discovery.tsp create mode 100644 lib/core/lib/core/routes/version-discovery.tsp create mode 100644 website/public/schemas/yaml/OperationVersions.yaml create mode 100644 website/public/schemas/yaml/UpcomingDefault.yaml create mode 100644 website/public/schemas/yaml/VersionDiscovery.yaml create mode 100644 website/public/schemas/yaml/VersionRetirement.yaml diff --git a/lib/core/lib/api.tsp b/lib/core/lib/api.tsp index 55d868182..d8626375d 100644 --- a/lib/core/lib/api.tsp +++ b/lib/core/lib/api.tsp @@ -30,6 +30,12 @@ using Versioning; description: "Endpoints that MUST be implemented by all CommonGrants APIs", } ) +@tagMetadata( + "Versions", + #{ + description: "Endpoints related to discovering the protocol versions an API serves", + } +) @tagMetadata("Forms", #{ description: "Endpoints related to forms" }) @tagMetadata("Awards", #{ description: "Endpoints related to grant awards" }) @tagMetadata( @@ -246,3 +252,17 @@ namespace Forms { @added(Versions.v0_2) op read is Router.read; } + +// ######################################################### +// Versions +// ######################################################### + +@tag("Versions") +@route("/versions") +namespace ProtocolVersions { + alias Router = Routes.ProtocolVersions; + + @added(Versions.v0_6) + @tag("optional") + op read is Router.read; +} diff --git a/lib/core/lib/core/models/index.tsp b/lib/core/lib/core/models/index.tsp index 028834a10..60e383cbe 100644 --- a/lib/core/lib/core/models/index.tsp +++ b/lib/core/lib/core/models/index.tsp @@ -15,6 +15,7 @@ import "./form.tsp"; import "./form-response.tsp"; import "./mapping.tsp"; import "./applicant-type.tsp"; +import "./version-discovery.tsp"; using TypeSpec.JsonSchema; diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp new file mode 100644 index 000000000..381f95b1e --- /dev/null +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -0,0 +1,132 @@ +import "../types.tsp"; + +namespace CommonGrants.Models; + +// ######################################################### +// UpcomingDefault +// ######################################################### + +/** A scheduled change to the version a server serves by default */ +@Versioning.added(CommonGrants.Versions.v0_6) +model UpcomingDefault { + /** The version that will become the default */ + version: Types.protocolVersion; + + /** When the new default takes effect */ + date: utcDateTime; +} + +// ######################################################### +// VersionRetirement +// ######################################################### + +/** The retirement schedule for a deprecated version */ +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionRetirement { + /** When the version was or will be deprecated */ + deprecation: utcDateTime; + + /** When the server will stop serving the version, if scheduled */ + sunset?: utcDateTime; +} + +// ######################################################### +// OperationVersions +// ######################################################### + +/** The versions a single route serves, when they differ from the API-wide values */ +@Versioning.added(CommonGrants.Versions.v0_6) +model OperationVersions { + /** The versions this route serves */ + versions: Types.protocolVersion[]; + + /** The version this route serves when a request doesn't name one */ + defaultVersion: Types.protocolVersion; + + /** A scheduled change to this route's default version, if any */ + upcomingDefault?: UpcomingDefault; + + /** Deprecated versions of this route, keyed by version, with their retirement schedule */ + deprecated?: Record; +} + +// ######################################################### +// VersionDiscovery +// ######################################################### + +/** The protocol versions an API serves + * + * The top-level fields describe every route. Routes that differ from them + * have an entry in `operations`. New fields are only ever added to this + * model; clients ignore fields they don't recognize. + */ +@example( + Examples.VersionDiscovery.routeEntries, + #{ title: "Baseline with route entries" } +) +@example( + Examples.VersionDiscovery.lifecycle, + #{ title: "Upcoming default and deprecated version" } +) +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionDiscovery { + /** The versions every route serves */ + versions: Types.protocolVersion[]; + + /** The version every route serves when a request doesn't name one */ + defaultVersion: Types.protocolVersion; + + /** A scheduled change to the API-wide default version, if any */ + upcomingDefault?: UpcomingDefault; + + /** Deprecated versions, keyed by version, with their retirement schedule */ + deprecated?: Record; + + /** Routes whose versions differ from the API-wide values + * + * Each key is the HTTP method and the route's published path, separated + * by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + * names are ignored when matching a key to a route. Omitted when every + * route serves the API-wide values. + */ + operations?: Record; +} + +// ######################################################### +// Examples +// ######################################################### + +/** Examples of version discovery responses */ +namespace Examples.VersionDiscovery { + /** A 0.4.0 baseline with routes that serve other versions */ + const routeEntries = #{ + versions: #["0.4.0"], + defaultVersion: "0.4.0", + operations: #{ + `GET /common-grants/forms`: #{ + versions: #["0.5.0"], + defaultVersion: "0.5.0", + }, + `GET /common-grants/forms/{formId}`: #{ + versions: #["0.4.0", "0.5.0"], + defaultVersion: "0.4.0", + }, + }, + }; + + /** A scheduled default change and a deprecated version */ + const lifecycle = #{ + versions: #["0.3.0", "0.4.0", "0.5.0"], + defaultVersion: "0.4.0", + upcomingDefault: #{ + version: "0.5.0", + date: utcDateTime.fromISO("2027-03-01T00:00:00Z"), + }, + deprecated: #{ + `0.3.0`: #{ + deprecation: utcDateTime.fromISO("2026-12-01T00:00:00Z"), + sunset: utcDateTime.fromISO("2027-06-01T00:00:00Z"), + }, + }, + }; +} diff --git a/lib/core/lib/core/routes/index.tsp b/lib/core/lib/core/routes/index.tsp index 8f4e4f8f7..bdcba2661 100644 --- a/lib/core/lib/core/routes/index.tsp +++ b/lib/core/lib/core/routes/index.tsp @@ -9,6 +9,7 @@ import "./applications.tsp"; import "./form-responses.tsp"; import "./forms.tsp"; import "./competitions.tsp"; +import "./version-discovery.tsp"; /** A series of routing interfaces for CommonGrants API endpoints * diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp new file mode 100644 index 000000000..dc01c40d3 --- /dev/null +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -0,0 +1,49 @@ +import "../models/index.tsp"; +import "../responses/index.tsp"; + +// Define the top-level namespace for CommonGrants routes +namespace CommonGrants.Routes; + +// Expose the contents of the Http and Rest namespaces +// these include the decorators @route, @get, etc. +using TypeSpec.Http; +using TypeSpec.Versioning; + +/** A re-usable interface for the versions discovery router + * + * Unlike the other routers, `read` is deliberately not templated: adopters + * don't extend the discovery response. Routes that differ from the API-wide + * versions are described in the response's `operations` field instead. + * + * @example Declaring the versions discovery route: + * ```typespec + * using TypeSpec.Http; + * + * @tag("Versions") + * @route("/versions") + * namespace ProtocolVersions { + * alias Router = Routes.ProtocolVersions; + * + * op read is Router.read; + * } + * ``` + */ +@added(CommonGrants.Versions.v0_6) +interface ProtocolVersions { + // ############################### + // List supported versions + // ############################### + + /** `GET /versions` List the protocol versions this API serves */ + @summary("List supported versions") + @doc(""" + List the protocol versions this API serves, its default version, and any routes whose versions differ. + + This route is optional, but a server that serves more than one protocol version MUST implement it. + It ignores the `CG-Version` request header, because clients call it before they know which version to request. + It SHOULD be readable without authentication. + Fields are only ever added to the response; clients ignore fields they don't recognize. + """) + @get + read(): Responses.OkT; +} diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml new file mode 100644 index 000000000..c4c6ecae8 --- /dev/null +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -0,0 +1,30 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: OperationVersions.yaml +type: object +properties: + versions: + type: array + items: + $ref: protocolVersion.yaml + description: The versions this route serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version this route serves when a request doesn't name one + upcomingDefault: + $ref: UpcomingDefault.yaml + description: A scheduled change to this route's default version, if any + deprecated: + $ref: "#/$defs/RecordVersionRetirement" + description: Deprecated versions of this route, keyed by version, with their retirement schedule +required: + - versions + - defaultVersion +unevaluatedProperties: + not: {} +description: The versions a single route serves, when they differ from the API-wide values +$defs: + RecordVersionRetirement: + type: object + properties: {} + unevaluatedProperties: + $ref: VersionRetirement.yaml diff --git a/website/public/schemas/yaml/UpcomingDefault.yaml b/website/public/schemas/yaml/UpcomingDefault.yaml new file mode 100644 index 000000000..355fcbb32 --- /dev/null +++ b/website/public/schemas/yaml/UpcomingDefault.yaml @@ -0,0 +1,17 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: UpcomingDefault.yaml +type: object +properties: + version: + $ref: protocolVersion.yaml + description: The version that will become the default + date: + type: string + format: date-time + description: When the new default takes effect +required: + - version + - date +unevaluatedProperties: + not: {} +description: A scheduled change to the version a server serves by default diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml new file mode 100644 index 000000000..1c2ad16d1 --- /dev/null +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -0,0 +1,75 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionDiscovery.yaml +type: object +properties: + versions: + type: array + items: + $ref: protocolVersion.yaml + description: The versions every route serves + defaultVersion: + $ref: protocolVersion.yaml + description: The version every route serves when a request doesn't name one + upcomingDefault: + $ref: UpcomingDefault.yaml + description: A scheduled change to the API-wide default version, if any + deprecated: + $ref: "#/$defs/RecordVersionRetirement" + description: Deprecated versions, keyed by version, with their retirement schedule + operations: + $ref: "#/$defs/RecordOperationVersions" + description: |- + Routes whose versions differ from the API-wide values + + Each key is the HTTP method and the route's published path, separated + by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + names are ignored when matching a key to a route. Omitted when every + route serves the API-wide values. +required: + - versions + - defaultVersion +unevaluatedProperties: + not: {} +examples: + - versions: + - 0.3.0 + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 + upcomingDefault: + version: 0.5.0 + date: 2027-03-01T00:00:00Z + deprecated: + 0.3.0: + deprecation: 2026-12-01T00:00:00Z + sunset: 2027-06-01T00:00:00Z + - versions: + - 0.4.0 + defaultVersion: 0.4.0 + operations: + GET /common-grants/forms: + versions: + - 0.5.0 + defaultVersion: 0.5.0 + GET /common-grants/forms/{formId}: + versions: + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 +description: |- + The protocol versions an API serves + + The top-level fields describe every route. Routes that differ from them + have an entry in `operations`. New fields are only ever added to this + model; clients ignore fields they don't recognize. +$defs: + RecordVersionRetirement: + type: object + properties: {} + unevaluatedProperties: + $ref: VersionRetirement.yaml + RecordOperationVersions: + type: object + properties: {} + unevaluatedProperties: + $ref: OperationVersions.yaml diff --git a/website/public/schemas/yaml/VersionRetirement.yaml b/website/public/schemas/yaml/VersionRetirement.yaml new file mode 100644 index 000000000..bd0df99de --- /dev/null +++ b/website/public/schemas/yaml/VersionRetirement.yaml @@ -0,0 +1,17 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionRetirement.yaml +type: object +properties: + deprecation: + type: string + format: date-time + description: When the version was or will be deprecated + sunset: + type: string + format: date-time + description: When the server will stop serving the version, if scheduled +required: + - deprecation +unevaluatedProperties: + not: {} +description: The retirement schedule for a deprecated version From b75fbbbffceea9d45727a1b2347491f10c6486d9 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Mon, 9 Nov 2026 08:15:10 -0800 Subject: [PATCH 15/20] feat(core): keep the discovery models open to new fields Discovery sits outside version selection, so its models tolerate fields they don't know instead of being versioned per document, as the route description promises. The baseline fields now say they describe routes without an operations entry, versions requires at least one entry, and the deprecated map documents its keys. Refs #1387 --- .../lib/core/models/version-discovery.tsp | 32 +++++++++++++++---- .../schemas/yaml/OperationVersions.yaml | 9 ++++-- .../public/schemas/yaml/UpcomingDefault.yaml | 3 +- .../public/schemas/yaml/VersionDiscovery.yaml | 20 +++++++----- .../schemas/yaml/VersionRetirement.yaml | 3 +- 5 files changed, 45 insertions(+), 22 deletions(-) diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp index 381f95b1e..4d87dae09 100644 --- a/lib/core/lib/core/models/version-discovery.tsp +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -14,6 +14,9 @@ model UpcomingDefault { /** When the new default takes effect */ date: utcDateTime; + + // Discovery sits outside version selection, so new fields must be tolerated rather than versioned + ...Record; } // ######################################################### @@ -28,6 +31,8 @@ model VersionRetirement { /** When the server will stop serving the version, if scheduled */ sunset?: utcDateTime; + + ...Record; } // ######################################################### @@ -38,6 +43,7 @@ model VersionRetirement { @Versioning.added(CommonGrants.Versions.v0_6) model OperationVersions { /** The versions this route serves */ + @minItems(1) versions: Types.protocolVersion[]; /** The version this route serves when a request doesn't name one */ @@ -46,8 +52,13 @@ model OperationVersions { /** A scheduled change to this route's default version, if any */ upcomingDefault?: UpcomingDefault; - /** Deprecated versions of this route, keyed by version, with their retirement schedule */ + /** Deprecated versions of this route, keyed by version, with their retirement schedule + * + * Each key is a full protocol version listed in `versions`, matched on major and minor. + */ deprecated?: Record; + + ...Record; } // ######################################################### @@ -56,9 +67,10 @@ model OperationVersions { /** The protocol versions an API serves * - * The top-level fields describe every route. Routes that differ from them - * have an entry in `operations`. New fields are only ever added to this - * model; clients ignore fields they don't recognize. + * The top-level fields describe every route that has no entry in + * `operations`. Routes that differ from them have an entry in `operations`. + * New fields are only ever added to this model; clients ignore fields they + * don't recognize. */ @example( Examples.VersionDiscovery.routeEntries, @@ -70,16 +82,20 @@ model OperationVersions { ) @Versioning.added(CommonGrants.Versions.v0_6) model VersionDiscovery { - /** The versions every route serves */ + /** The versions every route without an `operations` entry serves */ + @minItems(1) versions: Types.protocolVersion[]; - /** The version every route serves when a request doesn't name one */ + /** The version every route without an `operations` entry serves when a request doesn't name one */ defaultVersion: Types.protocolVersion; /** A scheduled change to the API-wide default version, if any */ upcomingDefault?: UpcomingDefault; - /** Deprecated versions, keyed by version, with their retirement schedule */ + /** Deprecated versions, keyed by version, with their retirement schedule + * + * Each key is a full protocol version listed in `versions`, matched on major and minor. + */ deprecated?: Record; /** Routes whose versions differ from the API-wide values @@ -90,6 +106,8 @@ model VersionDiscovery { * route serves the API-wide values. */ operations?: Record; + + ...Record; } // ######################################################### diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml index c4c6ecae8..97785f237 100644 --- a/website/public/schemas/yaml/OperationVersions.yaml +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -6,6 +6,7 @@ properties: type: array items: $ref: protocolVersion.yaml + minItems: 1 description: The versions this route serves defaultVersion: $ref: protocolVersion.yaml @@ -15,12 +16,14 @@ properties: description: A scheduled change to this route's default version, if any deprecated: $ref: "#/$defs/RecordVersionRetirement" - description: Deprecated versions of this route, keyed by version, with their retirement schedule + description: |- + Deprecated versions of this route, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. required: - versions - defaultVersion -unevaluatedProperties: - not: {} +unevaluatedProperties: {} description: The versions a single route serves, when they differ from the API-wide values $defs: RecordVersionRetirement: diff --git a/website/public/schemas/yaml/UpcomingDefault.yaml b/website/public/schemas/yaml/UpcomingDefault.yaml index 355fcbb32..266e7a54a 100644 --- a/website/public/schemas/yaml/UpcomingDefault.yaml +++ b/website/public/schemas/yaml/UpcomingDefault.yaml @@ -12,6 +12,5 @@ properties: required: - version - date -unevaluatedProperties: - not: {} +unevaluatedProperties: {} description: A scheduled change to the version a server serves by default diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml index 1c2ad16d1..55f32c579 100644 --- a/website/public/schemas/yaml/VersionDiscovery.yaml +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -6,16 +6,20 @@ properties: type: array items: $ref: protocolVersion.yaml - description: The versions every route serves + minItems: 1 + description: The versions every route without an `operations` entry serves defaultVersion: $ref: protocolVersion.yaml - description: The version every route serves when a request doesn't name one + description: The version every route without an `operations` entry serves when a request doesn't name one upcomingDefault: $ref: UpcomingDefault.yaml description: A scheduled change to the API-wide default version, if any deprecated: $ref: "#/$defs/RecordVersionRetirement" - description: Deprecated versions, keyed by version, with their retirement schedule + description: |- + Deprecated versions, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. operations: $ref: "#/$defs/RecordOperationVersions" description: |- @@ -28,8 +32,7 @@ properties: required: - versions - defaultVersion -unevaluatedProperties: - not: {} +unevaluatedProperties: {} examples: - versions: - 0.3.0 @@ -59,9 +62,10 @@ examples: description: |- The protocol versions an API serves - The top-level fields describe every route. Routes that differ from them - have an entry in `operations`. New fields are only ever added to this - model; clients ignore fields they don't recognize. + The top-level fields describe every route that has no entry in + `operations`. Routes that differ from them have an entry in `operations`. + New fields are only ever added to this model; clients ignore fields they + don't recognize. $defs: RecordVersionRetirement: type: object diff --git a/website/public/schemas/yaml/VersionRetirement.yaml b/website/public/schemas/yaml/VersionRetirement.yaml index bd0df99de..7aad7db8e 100644 --- a/website/public/schemas/yaml/VersionRetirement.yaml +++ b/website/public/schemas/yaml/VersionRetirement.yaml @@ -12,6 +12,5 @@ properties: description: When the server will stop serving the version, if scheduled required: - deprecation -unevaluatedProperties: - not: {} +unevaluatedProperties: {} description: The retirement schedule for a deprecated version From 176bce4964e4ad0898c55ca924973cf4eea637ee Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Wed, 18 Nov 2026 08:39:19 -0800 Subject: [PATCH 16/20] feat(core): give discovery its own 200 response without version headers OkT now spreads the version response headers, so discovery would have advertised CG-Version-Served and Vary. ADR 0032 says discovery carries neither, because clients call it before they know which version to request. The route returns a dedicated VersionDiscoveryResponse instead. Refs #1387 --- lib/core/lib/core/responses/success.tsp | 16 ++ .../lib/core/routes/version-discovery.tsp | 3 +- website/public/openapi/openapi.0.6.0.yaml | 158 ++++++++++++++++++ .../yaml/VersionDiscoveryResponse.yaml | 14 ++ 4 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 website/public/schemas/yaml/VersionDiscoveryResponse.yaml diff --git a/lib/core/lib/core/responses/success.tsp b/lib/core/lib/core/responses/success.tsp index e6c13588c..9c8722a8f 100644 --- a/lib/core/lib/core/responses/success.tsp +++ b/lib/core/lib/core/responses/success.tsp @@ -64,6 +64,22 @@ model OkT extends Success { data: T; } +// ############################################################################ +// 200 version discovery response +// ############################################################################ + +/** A 200 response listing the protocol versions an API serves + * + * Discovery sits outside version selection, so unlike `OkT` this response + * carries no version headers: neither `CG-Version-Served` nor `Vary`. + */ +@doc("A 200 response listing the protocol versions an API serves") +@Versioning.added(CommonGrants.Versions.v0_6) +model VersionDiscoveryResponse extends Success { + /** The protocol versions the API serves */ + data: Models.VersionDiscovery; +} + // ############################################################################ // 200 paginated response // ############################################################################ diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp index dc01c40d3..328596e50 100644 --- a/lib/core/lib/core/routes/version-discovery.tsp +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -41,9 +41,10 @@ interface ProtocolVersions { This route is optional, but a server that serves more than one protocol version MUST implement it. It ignores the `CG-Version` request header, because clients call it before they know which version to request. + Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. It SHOULD be readable without authentication. Fields are only ever added to the response; clients ignore fields they don't recognize. """) @get - read(): Responses.OkT; + read(): Responses.VersionDiscoveryResponse; } diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index 3adb2e665..aabc6ca79 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -22,6 +22,8 @@ tags: description: Endpoints related to grant awards - name: Forms description: Endpoints related to forms + - name: Versions + description: Endpoints related to discovering the protocol versions an API serves - name: required description: Endpoints that MUST be implemented by all CommonGrants APIs - name: optional @@ -3585,6 +3587,29 @@ paths: security: - OAuth2Auth: - org.changes:read + /common-grants/versions: + get: + operationId: ProtocolVersions_read + summary: List supported versions + description: |- + List the protocol versions this API serves, its default version, and any routes whose versions differ. + + This route is optional, but a server that serves more than one protocol version MUST implement it. + It ignores the `CG-Version` request header, because clients call it before they know which version to request. + Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. + It SHOULD be readable without authentication. + Fields are only ever added to the response; clients ignore fields they don't recognize. + parameters: [] + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CommonGrants.Responses.VersionDiscoveryResponse' + tags: + - Versions + - optional components: parameters: CommonGrants.Headers.VersionRequest: @@ -6279,6 +6304,36 @@ components: active: open inactive: closed default: custom + CommonGrants.Models.OperationVersions: + type: object + required: + - versions + - defaultVersion + properties: + versions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions this route serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version this route serves when a request doesn't name one + upcomingDefault: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' + description: A scheduled change to this route's default version, if any + deprecated: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.VersionRetirement' + description: |- + Deprecated versions of this route, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. + additionalProperties: {} + description: The versions a single route serves, when they differ from the API-wide values CommonGrants.Models.OppDefaultFilters: type: object properties: @@ -8102,6 +8157,97 @@ components: A revision moves once from `pending` into a terminal state; a terminal revision is never restated. How a receiver resolves a `pending` change (a human review, a policy engine, a batch job) is out of scope for this contract. + CommonGrants.Models.UpcomingDefault: + type: object + required: + - version + - date + properties: + version: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version that will become the default + date: + type: string + format: date-time + description: When the new default takes effect + additionalProperties: {} + description: A scheduled change to the version a server serves by default + CommonGrants.Models.VersionDiscovery: + type: object + required: + - versions + - defaultVersion + properties: + versions: + type: array + items: + $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + minItems: 1 + description: The versions every route without an `operations` entry serves + defaultVersion: + allOf: + - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' + description: The version every route without an `operations` entry serves when a request doesn't name one + upcomingDefault: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' + description: A scheduled change to the API-wide default version, if any + deprecated: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.VersionRetirement' + description: |- + Deprecated versions, keyed by version, with their retirement schedule + + Each key is a full protocol version listed in `versions`, matched on major and minor. + operations: + type: object + additionalProperties: + $ref: '#/components/schemas/CommonGrants.Models.OperationVersions' + description: |- + Routes whose versions differ from the API-wide values + + Each key is the HTTP method and the route's published path, separated + by a space, such as `GET /common-grants/forms/{formId}`. Path parameter + names are ignored when matching a key to a route. Omitted when every + route serves the API-wide values. + additionalProperties: {} + description: |- + The protocol versions an API serves + + The top-level fields describe every route that has no entry in + `operations`. Routes that differ from them have an entry in `operations`. + New fields are only ever added to this model; clients ignore fields they + don't recognize. + example: + versions: + - 0.3.0 + - 0.4.0 + - 0.5.0 + defaultVersion: 0.4.0 + upcomingDefault: + version: 0.5.0 + date: '2027-03-01T00:00:00Z' + deprecated: + 0.3.0: + deprecation: '2026-12-01T00:00:00Z' + sunset: '2027-06-01T00:00:00Z' + CommonGrants.Models.VersionRetirement: + type: object + required: + - deprecation + properties: + deprecation: + type: string + format: date-time + description: When the version was or will be deprecated + sunset: + type: string + format: date-time + description: When the server will stop serving the version, if scheduled + additionalProperties: {} + description: The retirement schedule for a deprecated version CommonGrants.Pagination.PaginatedBodyParams: type: object properties: @@ -8899,6 +9045,18 @@ components: - 0.6.0 defaultVersion: 0.5.0 discovery: https://grants.example.org/common-grants/versions + CommonGrants.Responses.VersionDiscoveryResponse: + type: object + required: + - data + properties: + data: + allOf: + - $ref: '#/components/schemas/CommonGrants.Models.VersionDiscovery' + description: The protocol versions the API serves + allOf: + - $ref: '#/components/schemas/CommonGrants.Responses.Success' + description: A 200 response listing the protocol versions an API serves CommonGrants.Responses.VersionErrorDetail: type: object required: diff --git a/website/public/schemas/yaml/VersionDiscoveryResponse.yaml b/website/public/schemas/yaml/VersionDiscoveryResponse.yaml new file mode 100644 index 000000000..f2f1792f4 --- /dev/null +++ b/website/public/schemas/yaml/VersionDiscoveryResponse.yaml @@ -0,0 +1,14 @@ +$schema: https://json-schema.org/draft/2020-12/schema +$id: VersionDiscoveryResponse.yaml +type: object +properties: + data: + $ref: VersionDiscovery.yaml + description: The protocol versions the API serves +required: + - data +allOf: + - $ref: Success.yaml +unevaluatedProperties: + not: {} +description: A 200 response listing the protocol versions an API serves From a56a2698a1aecb9ac37cc2d768003c146f2d235c Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Wed, 18 Nov 2026 09:27:42 -0800 Subject: [PATCH 17/20] docs(core): state the discovery rules ADR 0032 settles The defaultVersion docs now say a default is one of the listed versions, which the schema can't express. The route description adds the ADR's authentication ceiling and narrows "fields are only ever added" to data, since the response envelope stays closed. The interface comment says adopters don't type-parameterize the response, now that the models accept unknown fields. Refs #1387 --- lib/core/lib/core/models/version-discovery.tsp | 4 ++-- lib/core/lib/core/routes/version-discovery.tsp | 6 +++--- website/public/openapi/openapi.0.6.0.yaml | 8 ++++---- website/public/schemas/yaml/OperationVersions.yaml | 2 +- website/public/schemas/yaml/VersionDiscovery.yaml | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp index 4d87dae09..37a896c47 100644 --- a/lib/core/lib/core/models/version-discovery.tsp +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -46,7 +46,7 @@ model OperationVersions { @minItems(1) versions: Types.protocolVersion[]; - /** The version this route serves when a request doesn't name one */ + /** The version this route serves when a request doesn't name one, one of `versions` */ defaultVersion: Types.protocolVersion; /** A scheduled change to this route's default version, if any */ @@ -86,7 +86,7 @@ model VersionDiscovery { @minItems(1) versions: Types.protocolVersion[]; - /** The version every route without an `operations` entry serves when a request doesn't name one */ + /** The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` */ defaultVersion: Types.protocolVersion; /** A scheduled change to the API-wide default version, if any */ diff --git a/lib/core/lib/core/routes/version-discovery.tsp b/lib/core/lib/core/routes/version-discovery.tsp index 328596e50..e5bba00f3 100644 --- a/lib/core/lib/core/routes/version-discovery.tsp +++ b/lib/core/lib/core/routes/version-discovery.tsp @@ -12,7 +12,7 @@ using TypeSpec.Versioning; /** A re-usable interface for the versions discovery router * * Unlike the other routers, `read` is deliberately not templated: adopters - * don't extend the discovery response. Routes that differ from the API-wide + * don't type-parameterize the discovery response. Routes that differ from the API-wide * versions are described in the response's `operations` field instead. * * @example Declaring the versions discovery route: @@ -42,8 +42,8 @@ interface ProtocolVersions { This route is optional, but a server that serves more than one protocol version MUST implement it. It ignores the `CG-Version` request header, because clients call it before they know which version to request. Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. - It SHOULD be readable without authentication. - Fields are only ever added to the response; clients ignore fields they don't recognize. + It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. + Fields are only ever added to `data`; clients ignore fields they don't recognize. """) @get read(): Responses.VersionDiscoveryResponse; diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index aabc6ca79..42e67701d 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -3597,8 +3597,8 @@ paths: This route is optional, but a server that serves more than one protocol version MUST implement it. It ignores the `CG-Version` request header, because clients call it before they know which version to request. Its responses carry neither `CG-Version-Served` nor `Vary: CG-Version`. - It SHOULD be readable without authentication. - Fields are only ever added to the response; clients ignore fields they don't recognize. + It requires no stronger authentication than the API's required routes, and SHOULD be readable without authentication. + Fields are only ever added to `data`; clients ignore fields they don't recognize. parameters: [] responses: '200': @@ -6319,7 +6319,7 @@ components: defaultVersion: allOf: - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' - description: The version this route serves when a request doesn't name one + description: The version this route serves when a request doesn't name one, one of `versions` upcomingDefault: allOf: - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' @@ -8188,7 +8188,7 @@ components: defaultVersion: allOf: - $ref: '#/components/schemas/CommonGrants.Types.protocolVersion' - description: The version every route without an `operations` entry serves when a request doesn't name one + description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` upcomingDefault: allOf: - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml index 97785f237..7937f7f98 100644 --- a/website/public/schemas/yaml/OperationVersions.yaml +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -10,7 +10,7 @@ properties: description: The versions this route serves defaultVersion: $ref: protocolVersion.yaml - description: The version this route serves when a request doesn't name one + description: The version this route serves when a request doesn't name one, one of `versions` upcomingDefault: $ref: UpcomingDefault.yaml description: A scheduled change to this route's default version, if any diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml index 55f32c579..6858332a7 100644 --- a/website/public/schemas/yaml/VersionDiscovery.yaml +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -10,7 +10,7 @@ properties: description: The versions every route without an `operations` entry serves defaultVersion: $ref: protocolVersion.yaml - description: The version every route without an `operations` entry serves when a request doesn't name one + description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` upcomingDefault: $ref: UpcomingDefault.yaml description: A scheduled change to the API-wide default version, if any From d9e532d88c7d251c750a463be072f313e7673cc8 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 08:16:05 -0800 Subject: [PATCH 18/20] feat(core): check deprecated keys and state the upcoming default rule Validate each key of `deprecated` against the protocol version format in the JSON Schema files, and say that an upcoming default is one of `versions`, as ADR 0032 requires of every default. --- lib/core/lib/core/models/version-discovery.tsp | 12 ++++++++++-- website/public/openapi/openapi.0.6.0.yaml | 4 ++-- website/public/schemas/yaml/OperationVersions.yaml | 4 +++- website/public/schemas/yaml/VersionDiscovery.yaml | 4 +++- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp index 37a896c47..6186dff21 100644 --- a/lib/core/lib/core/models/version-discovery.tsp +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -49,13 +49,17 @@ model OperationVersions { /** The version this route serves when a request doesn't name one, one of `versions` */ defaultVersion: Types.protocolVersion; - /** A scheduled change to this route's default version, if any */ + /** A scheduled change to this route's default version, if any. Its `version` is one of `versions` */ upcomingDefault?: UpcomingDefault; /** Deprecated versions of this route, keyed by version, with their retirement schedule * * Each key is a full protocol version listed in `versions`, matched on major and minor. */ + @TypeSpec.JsonSchema.extension( + "propertyNames", + #{ $ref: "protocolVersion.yaml" } + ) deprecated?: Record; ...Record; @@ -89,13 +93,17 @@ model VersionDiscovery { /** The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` */ defaultVersion: Types.protocolVersion; - /** A scheduled change to the API-wide default version, if any */ + /** A scheduled change to the API-wide default version, if any. Its `version` is one of `versions` */ upcomingDefault?: UpcomingDefault; /** Deprecated versions, keyed by version, with their retirement schedule * * Each key is a full protocol version listed in `versions`, matched on major and minor. */ + @TypeSpec.JsonSchema.extension( + "propertyNames", + #{ $ref: "protocolVersion.yaml" } + ) deprecated?: Record; /** Routes whose versions differ from the API-wide values diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index 42e67701d..e63437dd7 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -6323,7 +6323,7 @@ components: upcomingDefault: allOf: - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' - description: A scheduled change to this route's default version, if any + description: A scheduled change to this route's default version, if any. Its `version` is one of `versions` deprecated: type: object additionalProperties: @@ -8192,7 +8192,7 @@ components: upcomingDefault: allOf: - $ref: '#/components/schemas/CommonGrants.Models.UpcomingDefault' - description: A scheduled change to the API-wide default version, if any + description: A scheduled change to the API-wide default version, if any. Its `version` is one of `versions` deprecated: type: object additionalProperties: diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml index 7937f7f98..6a7c8dcae 100644 --- a/website/public/schemas/yaml/OperationVersions.yaml +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -13,13 +13,15 @@ properties: description: The version this route serves when a request doesn't name one, one of `versions` upcomingDefault: $ref: UpcomingDefault.yaml - description: A scheduled change to this route's default version, if any + description: A scheduled change to this route's default version, if any. Its `version` is one of `versions` deprecated: $ref: "#/$defs/RecordVersionRetirement" description: |- Deprecated versions of this route, keyed by version, with their retirement schedule Each key is a full protocol version listed in `versions`, matched on major and minor. + propertyNames: + $ref: protocolVersion.yaml required: - versions - defaultVersion diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml index 6858332a7..36015f13a 100644 --- a/website/public/schemas/yaml/VersionDiscovery.yaml +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -13,13 +13,15 @@ properties: description: The version every route without an `operations` entry serves when a request doesn't name one, one of `versions` upcomingDefault: $ref: UpcomingDefault.yaml - description: A scheduled change to the API-wide default version, if any + description: A scheduled change to the API-wide default version, if any. Its `version` is one of `versions` deprecated: $ref: "#/$defs/RecordVersionRetirement" description: |- Deprecated versions, keyed by version, with their retirement schedule Each key is a full protocol version listed in `versions`, matched on major and minor. + propertyNames: + $ref: protocolVersion.yaml operations: $ref: "#/$defs/RecordOperationVersions" description: |- From 3df872fb9f95ba7a795e06d44e83d7ad7e990152 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 08:46:20 -0800 Subject: [PATCH 19/20] docs(core): separate the deprecated key rule from the client lookup A key is written exactly as its version appears in `versions`. Matching on major and minor is how a client finds the entry for the version it requested, so say that separately, with an example. --- lib/core/lib/core/models/version-discovery.tsp | 16 ++++++++++++++-- website/public/openapi/openapi.0.6.0.yaml | 16 ++++++++++++++-- .../public/schemas/yaml/OperationVersions.yaml | 8 +++++++- .../public/schemas/yaml/VersionDiscovery.yaml | 8 +++++++- 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/lib/core/lib/core/models/version-discovery.tsp b/lib/core/lib/core/models/version-discovery.tsp index 6186dff21..ae6b1d834 100644 --- a/lib/core/lib/core/models/version-discovery.tsp +++ b/lib/core/lib/core/models/version-discovery.tsp @@ -54,7 +54,13 @@ model OperationVersions { /** Deprecated versions of this route, keyed by version, with their retirement schedule * - * Each key is a full protocol version listed in `versions`, matched on major and minor. + * Each key is a version from `versions`, written exactly as it appears + * there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + * `0.3.1` as the key here. + * + * To check whether the version you request is deprecated, compare only + * the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + * its entry is under `0.3.1`. */ @TypeSpec.JsonSchema.extension( "propertyNames", @@ -98,7 +104,13 @@ model VersionDiscovery { /** Deprecated versions, keyed by version, with their retirement schedule * - * Each key is a full protocol version listed in `versions`, matched on major and minor. + * Each key is a version from `versions`, written exactly as it appears + * there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + * `0.3.1` as the key here. + * + * To check whether the version you request is deprecated, compare only + * the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + * its entry is under `0.3.1`. */ @TypeSpec.JsonSchema.extension( "propertyNames", diff --git a/website/public/openapi/openapi.0.6.0.yaml b/website/public/openapi/openapi.0.6.0.yaml index e63437dd7..16c54ae8d 100644 --- a/website/public/openapi/openapi.0.6.0.yaml +++ b/website/public/openapi/openapi.0.6.0.yaml @@ -6331,7 +6331,13 @@ components: description: |- Deprecated versions of this route, keyed by version, with their retirement schedule - Each key is a full protocol version listed in `versions`, matched on major and minor. + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. additionalProperties: {} description: The versions a single route serves, when they differ from the API-wide values CommonGrants.Models.OppDefaultFilters: @@ -8200,7 +8206,13 @@ components: description: |- Deprecated versions, keyed by version, with their retirement schedule - Each key is a full protocol version listed in `versions`, matched on major and minor. + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. operations: type: object additionalProperties: diff --git a/website/public/schemas/yaml/OperationVersions.yaml b/website/public/schemas/yaml/OperationVersions.yaml index 6a7c8dcae..a36a7304b 100644 --- a/website/public/schemas/yaml/OperationVersions.yaml +++ b/website/public/schemas/yaml/OperationVersions.yaml @@ -19,7 +19,13 @@ properties: description: |- Deprecated versions of this route, keyed by version, with their retirement schedule - Each key is a full protocol version listed in `versions`, matched on major and minor. + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. propertyNames: $ref: protocolVersion.yaml required: diff --git a/website/public/schemas/yaml/VersionDiscovery.yaml b/website/public/schemas/yaml/VersionDiscovery.yaml index 36015f13a..872c54906 100644 --- a/website/public/schemas/yaml/VersionDiscovery.yaml +++ b/website/public/schemas/yaml/VersionDiscovery.yaml @@ -19,7 +19,13 @@ properties: description: |- Deprecated versions, keyed by version, with their retirement schedule - Each key is a full protocol version listed in `versions`, matched on major and minor. + Each key is a version from `versions`, written exactly as it appears + there. A server hosting `0.3.1` lists `0.3.1` in `versions` and uses + `0.3.1` as the key here. + + To check whether the version you request is deprecated, compare only + the major and minor. A client requesting `0.3.0` is served `0.3.1`, so + its entry is under `0.3.1`. propertyNames: $ref: protocolVersion.yaml operations: From 2e809dd83497c901051fd6e85efba01e5c3751eb Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 09:10:25 -0800 Subject: [PATCH 20/20] docs(website): state the deprecated key rule and optional sunset date --- .../docs/governance/adr/0032-api-version-negotiation.md | 2 +- website/src/content/docs/protocol/specification/index.md | 3 ++- website/src/content/docs/protocol/versioning.mdx | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/website/src/content/docs/governance/adr/0032-api-version-negotiation.md b/website/src/content/docs/governance/adr/0032-api-version-negotiation.md index 538d2b2cc..8e908a4f1 100644 --- a/website/src/content/docs/governance/adr/0032-api-version-negotiation.md +++ b/website/src/content/docs/governance/adr/0032-api-version-negotiation.md @@ -31,7 +31,7 @@ We recommend that servers move all their routes to a new version at the same tim - A server publishes `GET /common-grants/versions`: a baseline (the default version and the versions every route serves) plus entries for routes that differ, in the standard success envelope. - The route is optional, and required for servers that serve more than one version. It SHOULD be readable without authentication. - It takes no request parameters, ignores `CG-Version`, and never returns a version error. -- Optional lifecycle fields appear while a change is pending: the upcoming default and its date, and deprecated versions with their deprecation and sunset dates. Dates use RFC 3339. +- Optional lifecycle fields appear while a change is pending: the upcoming default and its date, and deprecated versions with their deprecation date and, once set, their sunset date. Dates use RFC 3339. - Fields are only ever added, and clients ignore fields they don't recognize. - Ordinary responses don't carry a supported-versions header. Discovery and unsupported-version errors carry the list. diff --git a/website/src/content/docs/protocol/specification/index.md b/website/src/content/docs/protocol/specification/index.md index eba19f115..d93223f5c 100644 --- a/website/src/content/docs/protocol/specification/index.md +++ b/website/src/content/docs/protocol/specification/index.md @@ -160,8 +160,9 @@ After a version's sunset date, requests for it get `version.retired`, as describ - It returns the standard success envelope. In `data`, `versions` and `defaultVersion` are the baseline, which applies to every route without an entry in `operations`. A route whose versions differ from the baseline has an entry in `operations`, keyed by its HTTP method and its path as published in the protocol, such as `GET /common-grants/forms/{formId}`. Path parameter names are ignored when matching a key to a route. A server whose routes all serve the baseline omits `operations`. - A route serves a version only if that version of the protocol defines the route. - Every route a baseline version requires serves that version, so the baseline is a compliance claim: the server is compliant with every version in it. Supporting a version doesn't mean implementing that version's optional or experimental routes. -- A default is always one of the versions it applies to. +- A default is always one of the versions it applies to, and `upcomingDefault.version` MUST be one of the `versions` it applies to. - The optional `upcomingDefault` and `deprecated` fields appear only while a change is pending: at the top level for the baseline, or in a route's entry for that route only. Their dates use RFC 3339. +- Each key in `deprecated` MUST be a version from the `versions` beside it, written exactly as it appears there. A client finds the entry for the version it requested by comparing only the major and minor: a client requesting `0.3.0` from a server that lists `0.3.1` finds its entry under `0.3.1`. - Fields are only ever added to the discovery response. Clients MUST ignore fields they don't recognize, and accept version values published after they were built. A client that gets 404 from the discovery route treats the server as serving one version that it doesn't advertise. diff --git a/website/src/content/docs/protocol/versioning.mdx b/website/src/content/docs/protocol/versioning.mdx index 07ac63100..5c252a60a 100644 --- a/website/src/content/docs/protocol/versioning.mdx +++ b/website/src/content/docs/protocol/versioning.mdx @@ -130,7 +130,7 @@ Link: ; rel="sunset" Link: ; rel="version-history" ``` -The three dates use three formats: `Deprecation` uses the `@` form from [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745), `Sunset` uses an HTTP-date as in [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594), and discovery uses RFC 3339. +The three dates use three formats: `Deprecation` uses the `@` form from [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745), `Sunset` uses an HTTP-date as in [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594), and discovery uses RFC 3339. Discovery keys `deprecated` by the exact versions it lists, so look up the version you requested by its major and minor alone: a request for `0.3.0` served as `0.3.1` finds its entry under `0.3.1`. After the sunset date, requests for any patch of that major and minor version get 406 `version.retired`, with the sunset date and the supported versions, for a period the server chooses. After that, the server may answer `version.unsupported` instead, so handle both the same way: retry with a version from `supported`. If the retired version was your default, the default has already moved to the next newer version.