diff --git a/.github/workflows/ci-mock-api.yml b/.github/workflows/ci-mock-api.yml new file mode 100644 index 000000000..e3568b7d4 --- /dev/null +++ b/.github/workflows/ci-mock-api.yml @@ -0,0 +1,165 @@ +name: "CI - Mock API: Run Checks and Deploy Worker" + +# Deliberately minimal, and deliberately NOT modelled on ci-website-preview.yml. +# That workflow uploads *versions* of the shared `common-grants` Worker and +# aliases them per PR; this is a separate service with its own name +# (`cg-mock-api` in mock-api/wrangler.jsonc), so a plain `wrangler deploy` is the +# right primitive. Do not merge the two flows. +# +# Deploys target a PERSONAL Cloudflare account and a `*.workers.dev` URL — a +# known interim state for the #1077 experiment, not a productionized setup. Moving +# to the org account is tracked separately; see mock-api/FINDINGS.md (#1077-T7). + +on: + workflow_call: + pull_request: + paths: + - mock-api/** + - .github/workflows/ci-mock-api.yml + # Deploying is manual on purpose: the experiment is timeboxed and a single + # fixed Worker name means every deploy claims the same slot, so an automatic + # deploy-per-push would just fight itself. + workflow_dispatch: + +# One deploy at a time — `cg-mock-api` is a single deployment slot. Deliberately NOT +# keyed on `github.ref`: every ref deploys to the same Worker, so a ref-scoped group +# would put two dispatches from different branches in different groups and let them +# race the one slot — exactly what this is meant to prevent. +concurrency: + group: mock-api-deploy + cancel-in-progress: false + +jobs: + validate: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Install Node.js + uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + + - name: Install pnpm + uses: pnpm/action-setup@v6 + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build Worker bundle + run: pnpm --filter @common-grants/mock-api run build + + - name: Run checks + run: pnpm --filter @common-grants/mock-api run checks + + # The conformance suite (#1077-T4) validates the fixture against the docs + # pipeline's generated per-version schemas, which are gitignored build + # output. This step is that pipeline — it compiles the website's TypeSpec + # and emits `website/public/schemas/yaml/versions/`. Kept as its own step + # rather than folded into `run ci` so the cross-package dependency is + # visible in the CI log; the suite fails loudly if it is ever skipped. + - name: Generate versioned schemas (for conformance tests) + run: pnpm --filter @common-grants/mock-api run schemas + + - name: Run tests + run: pnpm --filter @common-grants/mock-api run test + + - name: Audit dependencies + # Gated to PRs into `main` (and main-context workflow_call invocations) so + # advisories that live on `main` and can only be fixed there don't block + # PRs into HOLD-* batching branches or other non-main bases. The HOLD → main + # checkpoint PR re-runs this audit, so anything live at merge time is gated + # at the actionable boundary. + # + # `workflow_dispatch` is added to the sibling workflows' condition because + # here `validate` gates a real `wrangler deploy`. `base_ref` is empty for + # dispatch, so without this the condition collapses to `ref == main` and a + # dispatch from any other branch would skip the audit — silently publishing + # a public Worker whose lockfile was never audited. + if: | + github.event_name == 'workflow_dispatch' + || github.base_ref == 'main' + || github.ref == 'refs/heads/main' + run: pnpm --filter @common-grants/mock-api run audit + + deploy: + runs-on: ubuntu-latest + needs: validate + # Manual dispatch only, and only after validate passes. + if: github.event_name == 'workflow_dispatch' + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Install Node.js + uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + + - name: Install pnpm + uses: pnpm/action-setup@v6 + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Deploy Worker + id: deploy + working-directory: ./mock-api + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + # pipefail matters: without it the pipeline reports `tee`'s exit code and a + # failed deploy would pass. Steps with no `shell:` key run under GitHub's + # default `bash -e {0}`; only an explicit `shell: bash` gets + # `--noprofile --norc -eo pipefail {0}`. So this is load-bearing, not decoration. + run: | + set -o pipefail + pnpm exec wrangler deploy 2>&1 | tee deploy.log + + # The deployed URL is the ticket's verification artifact, so pull it out of + # the deploy log rather than leaving it buried there. + - name: Resolve deployed URL + id: url + working-directory: ./mock-api + run: | + url="$(grep -Eo 'https://[a-z0-9.-]+\.workers\.dev' deploy.log | head -n 1)" + if [ -z "$url" ]; then + echo "No workers.dev URL found in wrangler output" >&2 + exit 1 + fi + echo "url=$url" >> "$GITHUB_OUTPUT" + + # A deploy that succeeds while serving a broken Worker should fail the run, + # so assert the two routes #1077-T5 names as its verification: the health + # route, and a versioned opportunity list that actually returns records. + - name: Smoke-test the deployed Worker + env: + URL: ${{ steps.url.outputs.url }} + run: | + set -euo pipefail + + echo "Health route:" + curl -fsS --retry 5 --retry-connrefused --retry-delay 2 "$URL/" | tee health.json + jq -e '.name == "@common-grants/mock-api" and (.supportedVersions | index("0.3.0"))' health.json > /dev/null + + echo "Opportunity list (v0.3.0):" + curl -fsS --retry 3 --retry-connrefused --retry-delay 2 "$URL/v0.3.0/common-grants/opportunities" | tee list.json > /dev/null + count="$(jq '.items | length' list.json)" + echo " returned $count records" + test "$count" -gt 0 + + - name: Summarize deployment + env: + URL: ${{ steps.url.outputs.url }} + run: | + { + echo "### Mock API deployed" + echo + echo "- URL: \`$URL\`" + echo "- Health: \`$URL/\`" + echo "- Opportunities (v0.3.0): \`$URL/v0.3.0/common-grants/opportunities\`" + echo "- Smoke test: passed" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/mock-api/.gitignore b/mock-api/.gitignore new file mode 100644 index 000000000..910aa38c4 --- /dev/null +++ b/mock-api/.gitignore @@ -0,0 +1,20 @@ +# Dependencies +node_modules/ + +# Build output +dist/ + +# Wrangler local state +.wrangler/ + +# Coverage reports +coverage/ + +# Environment variables +.dev.vars +.env +.env.local +.env.*.local + +# TypeScript cache +*.tsbuildinfo diff --git a/mock-api/.prettierrc b/mock-api/.prettierrc new file mode 100644 index 000000000..81c9a74c4 --- /dev/null +++ b/mock-api/.prettierrc @@ -0,0 +1,10 @@ +{ + "semi": true, + "trailingComma": "es5", + "singleQuote": false, + "printWidth": 100, + "tabWidth": 2, + "useTabs": false, + "bracketSpacing": true, + "arrowParens": "avoid" +} diff --git a/mock-api/DEPLOYMENT.md b/mock-api/DEPLOYMENT.md new file mode 100644 index 000000000..ffd2a29be --- /dev/null +++ b/mock-api/DEPLOYMENT.md @@ -0,0 +1,144 @@ +# Deployment overhead (#1077-T5) + +The "deployment overhead" rubric input for the #1077 experiment: what it actually +takes to get this Worker onto a real URL, and what is still missing before that +setup would be acceptable outside a spike. + +Fold this into `FINDINGS.md` at #1077-T7. + +## What exists + +`.github/workflows/ci-mock-api.yml`, path-filtered to `mock-api/**` plus the +workflow file itself. Two jobs: + +| Job | Trigger | Does | +| ---------- | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | +| `validate` | `pull_request`, `workflow_dispatch`, `workflow_call` | build → checks → generate versioned schemas → test → audit | +| `deploy` | `workflow_dispatch` only, `needs: validate` | `wrangler deploy` → resolve the `*.workers.dev` URL → smoke-test health + v0.3.0 list → write both to the run summary | + +Deliberately a plain `wrangler deploy`, not the `wrangler versions upload +--preview-alias` flow that `ci-website-preview.yml` uses via +`.github/scripts/upload-worker-preview.sh`. That flow versions the _shared_ +`common-grants` Worker; this is a separate service with its own name, so the +simpler primitive is the correct one. + +## Secrets + +No new secrets. Reuses the two the website preview flow already relies on, both +confirmed present on the repo: + +| Secret | Added | +| ----------------------- | ---------- | +| `CLOUDFLARE_API_TOKEN` | 2026-08-06 | +| `CLOUDFLARE_ACCOUNT_ID` | 2026-08-06 | + +They point at a **personal** Cloudflare account, so the deployed URL is a personal +`*.workers.dev` subdomain. Sufficient per the ticket, but it means the experiment's +one public artifact lives outside org control — the single biggest gap between this +and a productionized deploy. Moving to the org account is tracked separately. + +## Cost / duration + +Measured locally (Apple silicon, warm `node_modules`); CI adds checkout, Node and +pnpm setup, and a cold `pnpm install --frozen-lockfile`, which dominates: + +| Step | Local | +| ------------------------------------------------------------ | ------- | +| `build` (`wrangler deploy --dry-run`) | ~1s | +| `checks` (eslint + prettier + tsc ×2) | ~3s | +| `schemas` (website TypeSpec compile + versioned-schema emit) | ~3s | +| `test` (232 tests) | ~1s | +| **validate total, excluding install** | **~8s** | + +Worker bundle: 29.80 KiB (7.48 KiB gzipped). + +The `schemas` step being only ~3s is the useful surprise here — the conformance +test's dependency on the website pipeline is cheap in wall-clock terms. The cost of +that coupling is structural, not temporal (see below). + +> **Pending a real run.** The CI-measured duration of `validate` and `deploy`, and +> the deployed URL, are not filled in yet — see "Not yet verified". + +## Not yet verified + +**No deploy has been run.** `wrangler deploy` publishes a public service, so it +needs an explicit human decision, and two things block CI from doing it today: + +1. This branch is not pushed to GitHub. +2. `workflow_dispatch` only exposes a "Run workflow" control once the workflow file + exists on the **default branch**. This is a one-time bootstrap gate, not a + standing requirement: once `ci-mock-api.yml` has landed on `main` once, the ref + picker can target any branch carrying the same file, so later feature branches + won't each need their own merge-to-`main` cycle. But today it means the deploy + job cannot be dispatched from this branch at all — a consequence of choosing + manual dispatch to keep the experiment cheap, not anticipated in the plan. + +## Runbook: first deploy (manual, one time) + +Run from the repo root. Step 1 opens a browser for Cloudflare OAuth, so it can't be +automated in a headless session. + +1. Authenticate wrangler against the Cloudflare account that should own the Worker: + + ```bash + pnpm --filter @common-grants/mock-api exec wrangler login + ``` + +2. Confirm the account it picked, so the Worker doesn't land somewhere unexpected: + + ```bash + pnpm --filter @common-grants/mock-api exec wrangler whoami + ``` + +3. Deploy. This publishes a **public** Worker at + `https://cg-mock-api..workers.dev`: + + ```bash + pnpm --filter @common-grants/mock-api run deploy + ``` + +4. Verify the two routes the ticket names, substituting the URL wrangler printed: + + ```bash + curl -s https://cg-mock-api..workers.dev/ | jq + ``` + + ```bash + curl -s https://cg-mock-api..workers.dev/v0.3.0/common-grants/opportunities | jq '.items | length' + ``` + + Expected: the first prints `name` plus all four `supportedVersions`; the second + prints `11`. + +If attaching this to a personal account is unwanted, `wrangler deploy --temporary` +uses a throwaway preview account — but the URL is ephemeral, and #1077-T6 and +#1077-T7 need a stable origin for the docs "Try it out" and the SDK continuity +check, so they would need a real deploy anyway. + +### Alternatives to deploying by hand + +- Merge `ci-mock-api.yml` to `main`, then use the Actions "Run workflow" button. The + workflow's own smoke test verifies both routes for you. +- Add a `push` trigger scoped to the experiment branch — auto-deploys, and gives up + the "manual, therefore cheap" property the ticket asked for. + +### Deployed URL + +Not yet deployed. + +## Gaps to flag for #1077-T7 + +- **Personal account.** The public URL is not org-controlled. +- **Single deployment slot.** One fixed Worker name (`cg-mock-api`) means no + staging/per-env split; a `concurrency` group keeps deploys from racing, but that + is a guard, not a solution. +- **Path filter misses its real dependency.** The trigger watches `mock-api/**`, + per the ticket. But the conformance suite validates against schemas generated + from `website/`, so a protocol or pipeline change under `lib/core/**` or + `website/**` can break `mock-api` tests _without_ running this workflow. The + reverse coupling is unguarded too. Widening the filter would catch it at the cost + of running mock-api CI on most PRs. +- **No rollback path** beyond redeploying an older commit. +- **Smoke test covers two routes only** — the health route and the v0.3.0 list. The + detail and search endpoints, the other three versions, and CORS/preflight are + exercised by unit tests but never against the deployed Worker. diff --git a/mock-api/__tests__/conformance/fixtures-vs-schemas.spec.ts b/mock-api/__tests__/conformance/fixtures-vs-schemas.spec.ts new file mode 100644 index 000000000..104178549 --- /dev/null +++ b/mock-api/__tests__/conformance/fixtures-vs-schemas.spec.ts @@ -0,0 +1,204 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, it, expect } from "vitest"; +import yaml from "js-yaml"; +import { + OPPORTUNITY_FIXTURES, + SUPPORTED_VERSIONS, + CANONICAL_OPPORTUNITY_ID, + shapeOpportunityForVersion, + type Version, +} from "../../src/data/fixtures"; +import { getOpportunityValidator, schemasAvailable } from "../utils/schema-validator"; + +// Resolved relative to this file rather than `process.cwd()`, so it holds +// regardless of whether vitest is invoked from the package or the repo root. +const TEST_DIR = path.dirname(fileURLToPath(import.meta.url)); +const SCHEMA_VERSIONS_DIR = path.resolve(TEST_DIR, "../../../website/public/schemas/yaml/versions"); + +function loadYamlSchema( + version: string, + schemaFile: string +): { properties?: Record } { + const filePath = path.join(SCHEMA_VERSIONS_DIR, `v${version}`, schemaFile); + return yaml.load(readFileSync(filePath, "utf-8")) as { properties?: Record }; +} + +// (A) Guard: fail loudly (never silently skip) if the generated schemas aren't on +// disk, so a missing build step can't make CI falsely green. Deliberately at module +// scope rather than in `beforeAll`: the `describe.each` blocks below call +// `getOpportunityValidator` during vitest's collection phase, which runs before any +// hook fires, so a `beforeAll` version of this check would be dead code that only +// looked load-bearing. +if (!schemasAvailable()) { + throw new Error( + "Generated schemas not found. Run `pnpm --filter @common-grants/mock-api run schemas` " + + "to generate them before running this suite." + ); +} + +describe("fixtures vs. generated schemas (#1077-T4)", () => { + // Schema resolution itself is asserted, not assumed. `getOpportunityValidator` + // falls back to OpportunityBase when a version has no OpportunityDetails, which + // is correct only for v0.1.0 (the model was added in v0.2). Without this, a + // version whose OpportunityDetails went missing from the generated output would + // silently downgrade to OpportunityBase and every detail test below would still + // pass — validating a weaker schema while reporting green. + describe("schema resolution", () => { + it.each(SUPPORTED_VERSIONS)("uses the real OpportunityBase for %s list", version => { + const { schemaName, isFallback } = getOpportunityValidator(version, "list"); + + expect(schemaName).toBe("OpportunityBase.yaml"); + expect(isFallback).toBe(false); + }); + + it.each(SUPPORTED_VERSIONS)("resolves the expected detail schema for %s", version => { + const { schemaName, isFallback } = getOpportunityValidator(version, "detail"); + + // v0.1 predates OpportunityDetails, so there the fallback IS the real answer. + const expectFallback = version === "0.1.0"; + + expect(isFallback).toBe(expectFallback); + expect(schemaName).toBe(expectFallback ? "OpportunityBase.yaml" : "OpportunityDetails.yaml"); + }); + }); + + // (B) List variant: every record, every version, projects to a valid + // OpportunityBase. This variant carries no known deviation — all green. + describe("list variant conformance", () => { + describe.each(SUPPORTED_VERSIONS)("version %s", (version: Version) => { + const { validate, errorText, schemaName } = getOpportunityValidator(version, "list"); + + it.each(OPPORTUNITY_FIXTURES)("shapes $id into a valid list record", opp => { + const shaped = shapeOpportunityForVersion(opp, version, "list"); + const ok = validate(shaped); + + expect(ok, `${schemaName} (list, ${version}) rejected ${opp.id}: ${errorText()}`).toBe( + true + ); + }); + }); + }); + + // (C) Detail variant: every record, every version, projects to a valid + // OpportunityDetails (or, for v0.1.0, the OpportunityBase fallback) — + // *after* dropping `competitions`. That omission is the known, deliberate + // deviation pinned separately in the "competitions deviation" suite below; + // it is spelled out here rather than folded into a helper so it stays + // visible at the call site. + describe("detail variant conformance (competitions omitted, see deviation suite below)", () => { + describe.each(SUPPORTED_VERSIONS)("version %s", (version: Version) => { + const { validate, errorText, schemaName } = getOpportunityValidator(version, "detail"); + + it.each(OPPORTUNITY_FIXTURES)("shapes $id into a valid detail record", opp => { + const shaped = shapeOpportunityForVersion(opp, version, "detail"); + + // The fixture's `Competition` shape deliberately omits the full + // model's required `forms` field (see the `Competition` interface + // docstring in src/data/fixtures.ts), so any record still carrying + // `competitions` fails OpportunityDetails validation. Drop it here so + // this suite pins the rest of the shape; the deviation itself is + // asserted explicitly below. + const withoutCompetitions = { ...shaped }; + delete withoutCompetitions.competitions; + + const ok = validate(withoutCompetitions); + + expect(ok, `${schemaName} (detail, ${version}) rejected ${opp.id}: ${errorText()}`).toBe( + true + ); + }); + }); + }); + + // (D) Pin the deviation: assert it still exists exactly as measured, so a + // silent fix (or regression) is caught either way. + describe("competitions deviation (pinned, not fixed)", () => { + const recordsWithCompetitions = OPPORTUNITY_FIXTURES.filter( + opp => opp.competitions !== undefined + ); + + it("carries competitions on exactly 3 of the 11 fixture records", () => { + expect(OPPORTUNITY_FIXTURES.length).toBe(11); + expect(recordsWithCompetitions.length).toBe(3); + }); + + // Every version that has a real OpportunityDetails, not just v0.3.0 — so the + // same regression appearing on v0.2.0 or v0.4.0 is caught too. + const DETAIL_VERSIONS = SUPPORTED_VERSIONS.filter(v => v !== "0.1.0"); + + // If these start failing, it means the fixture's `Competition` type grew a + // `forms` object and now matches the full model — DELETE this block and fold + // `competitions` back into "detail variant conformance" above (drop the + // omission there) instead of patching these assertions. + it.each(DETAIL_VERSIONS)( + "fails OpportunityDetails validation for %s when competitions are left in", + version => { + const { validate, errorText } = getOpportunityValidator(version, "detail"); + + for (const record of recordsWithCompetitions) { + const shaped = shapeOpportunityForVersion(record, version, "detail"); + + expect(validate(shaped), `${record.id} unexpectedly validated`).toBe(false); + expect(errorText()).toContain("forms"); + } + } + ); + }); + + // (E) v0.1 stripping proof (edge case). The schema-level fact holds: v0.1's + // OpportunityBase predates `acceptedApplicantTypes` and v0.2's has it. + describe("v0.1 stripping proof", () => { + it("lacks acceptedApplicantTypes on v0.1.0's OpportunityBase, unlike v0.2.0's", () => { + const v01 = loadYamlSchema("0.1.0", "OpportunityBase.yaml"); + const v02 = loadYamlSchema("0.2.0", "OpportunityBase.yaml"); + + expect(v01.properties).not.toHaveProperty("acceptedApplicantTypes"); + expect(v02.properties).toHaveProperty("acceptedApplicantTypes"); + }); + + // Empirically checked (see PR description / probe): the generated v0.1.0 + // OpportunityBase schema does NOT set `additionalProperties: false`, so it + // is "unsealed" — a record that still carries `acceptedApplicantTypes` + // after v0.1 shaping validates successfully anyway. Schema validation + // alone can't catch a failure to strip that field; the + // `shapeOpportunityForVersion` unit tests in + // __tests__/data/fixtures.spec.ts are what actually pin the stripping + // behavior. This test just records why a schema-validation assertion + // here would be a false negative. + it("does not reject a v0.1.0 record with acceptedApplicantTypes added back (the schema is unsealed)", () => { + const canonical = OPPORTUNITY_FIXTURES.find(opp => opp.id === CANONICAL_OPPORTUNITY_ID)!; + const shaped = shapeOpportunityForVersion(canonical, "0.1.0", "list"); + const withFieldAddedBack = { + ...shaped, + acceptedApplicantTypes: canonical.acceptedApplicantTypes, + }; + + const { validate } = getOpportunityValidator("0.1.0", "list"); + + expect(validate(withFieldAddedBack)).toBe(true); + }); + }); + + // (F) Negative path: a deliberately drifted record fails, with a readable, + // non-empty error naming the offending field. + describe("drifted record (negative path)", () => { + it("fails validation with a readable error naming the offending field", () => { + const canonical = OPPORTUNITY_FIXTURES.find(opp => opp.id === CANONICAL_OPPORTUNITY_ID)!; + const shaped = shapeOpportunityForVersion(canonical, "0.3.0", "list"); + + // Deliberately drift the record: `status` must be an OppStatus object; + // no version of the schema accepts a bare string here. + const drifted = { ...shaped, status: "open" }; + + const { validate, errorText } = getOpportunityValidator("0.3.0", "list"); + const ok = validate(drifted); + + expect(ok).toBe(false); + const message = errorText(); + expect(message.length).toBeGreaterThan(0); + expect(message).toContain("status"); + }); + }); +}); diff --git a/mock-api/__tests__/data/fixtures.spec.ts b/mock-api/__tests__/data/fixtures.spec.ts new file mode 100644 index 000000000..1920ba502 --- /dev/null +++ b/mock-api/__tests__/data/fixtures.spec.ts @@ -0,0 +1,175 @@ +import { describe, it, expect } from "vitest"; +import { + CANONICAL_OPPORTUNITY_ID, + OPPORTUNITY_FIXTURES, + RESERVED_MISSING_OPPORTUNITY_ID, + SUPPORTED_VERSIONS, + isSupportedVersion, + shapeOpportunityForVersion, + getById, + allForVersion, + type Opportunity, +} from "../../src/data/fixtures"; + +const STATUS_VALUES = ["forecasted", "open", "closed", "custom"]; + +describe("OPPORTUNITY_FIXTURES", () => { + it("contains between 8 and 12 detail-shaped records", () => { + expect(OPPORTUNITY_FIXTURES.length).toBeGreaterThanOrEqual(8); + expect(OPPORTUNITY_FIXTURES.length).toBeLessThanOrEqual(12); + }); + + // Swagger UI pre-fills the `oppId` box with the specs' `Types.uuid` example. + // If no fixture carries that id, the first Execute a visitor runs — with the + // field untouched — answers 404 instead of the documented record. + it("carries the id the specs publish as their uuid example", () => { + const canonical = getById(CANONICAL_OPPORTUNITY_ID); + + expect(canonical).toBeDefined(); + expect(canonical!.title).toBe("Small business grant program"); + expect(canonical!.description).toBe( + "This program provides funding to small businesses to help them grow and create jobs" + ); + expect(canonical!.status).toEqual({ + value: "open", + description: "The opportunity is currently accepting applications", + }); + expect(canonical!.funding?.totalAmountAvailable).toEqual({ + amount: "1000000.00", + currency: "USD", + }); + }); + + it("sorts the documented example first under the list endpoint's default ordering", () => { + const newestFirst = [...OPPORTUNITY_FIXTURES].sort( + (a, b) => new Date(b.lastModifiedAt).getTime() - new Date(a.lastModifiedAt).getTime() + ); + + expect(newestFirst[0].id).toBe(CANONICAL_OPPORTUNITY_ID); + }); + + it("leaves the reserved 404 id absent from the fixture set", () => { + expect(getById(RESERVED_MISSING_OPPORTUNITY_ID)).toBeUndefined(); + }); + + it("gives every record the OpportunityBase-emitted shape", () => { + for (const opp of OPPORTUNITY_FIXTURES) { + expect(typeof opp.id).toBe("string"); + expect(typeof opp.title).toBe("string"); + expect(typeof opp.description).toBe("string"); + expect(typeof opp.createdAt).toBe("string"); + expect(typeof opp.lastModifiedAt).toBe("string"); + + expect(typeof opp.status).toBe("object"); + expect(STATUS_VALUES).toContain(opp.status.value); + + expect(opp.funding).toBeDefined(); + const amounts = [ + opp.funding?.totalAmountAvailable, + opp.funding?.minAwardAmount, + opp.funding?.maxAwardAmount, + ].filter(Boolean); + expect(amounts.length).toBeGreaterThan(0); + expect(typeof amounts[0]?.amount).toBe("string"); + expect(typeof amounts[0]?.currency).toBe("string"); + + expect(opp.keyDates?.closeDate).toBeDefined(); + } + }); + + it("includes all four status values, and 'custom' records carry a customValue", () => { + const values = OPPORTUNITY_FIXTURES.map(opp => opp.status.value); + for (const status of STATUS_VALUES) { + expect(values).toContain(status); + } + + const customRecords = OPPORTUNITY_FIXTURES.filter(opp => opp.status.value === "custom"); + expect(customRecords.length).toBeGreaterThan(0); + for (const opp of customRecords) { + expect(typeof opp.status.customValue).toBe("string"); + } + }); +}); + +describe("shapeOpportunityForVersion", () => { + const detailRecord = OPPORTUNITY_FIXTURES.find( + opp => Boolean(opp.competitions) && Boolean(opp.acceptedApplicantTypes) + ) as Opportunity; + + it("strips v0.2+-only fields for v0.1 detail records", () => { + expect(detailRecord).toBeDefined(); + + const shaped = shapeOpportunityForVersion(detailRecord, "0.1.0", "detail"); + + expect(shaped).not.toHaveProperty("competitions"); + expect(shaped).not.toHaveProperty("acceptedApplicantTypes"); + }); + + it("retains acceptedApplicantTypes and competitions for v0.2 detail records", () => { + const shaped = shapeOpportunityForVersion(detailRecord, "0.2.0", "detail"); + + expect(shaped).toHaveProperty("acceptedApplicantTypes"); + expect(shaped).toHaveProperty("competitions"); + }); + + it("never includes competitions on a v0.3 list-variant record", () => { + const shaped = shapeOpportunityForVersion(detailRecord, "0.3.0", "list"); + + expect(shaped).not.toHaveProperty("competitions"); + }); + + it("allForVersion('0.1.0') strips acceptedApplicantTypes/competitions from every record", () => { + const shaped = allForVersion("0.1.0"); + + for (const opp of shaped) { + expect(opp).not.toHaveProperty("acceptedApplicantTypes"); + expect(opp).not.toHaveProperty("competitions"); + } + }); + + it("allForVersion('0.3.0') returns the same number of (list-shaped) records", () => { + const shaped = allForVersion("0.3.0"); + + expect(shaped.length).toBe(OPPORTUNITY_FIXTURES.length); + }); + + it("shapes 0.4.0 identically to 0.3.0 for both list and detail variants", () => { + expect(shapeOpportunityForVersion(detailRecord, "0.4.0", "list")).toEqual( + shapeOpportunityForVersion(detailRecord, "0.3.0", "list") + ); + expect(shapeOpportunityForVersion(detailRecord, "0.4.0", "detail")).toEqual( + shapeOpportunityForVersion(detailRecord, "0.3.0", "detail") + ); + }); +}); + +describe("getById", () => { + it("has unique ids across the fixture set", () => { + const ids = OPPORTUNITY_FIXTURES.map(opp => opp.id); + expect(new Set(ids).size).toBe(ids.length); + }); + + it("resolves the STEM Education Grant Program seeded from the mock API server", () => { + const opp = getById("573525f2-8e15-4405-83fb-e6523511d893"); + + expect(opp?.title).toBe("STEM Education Grant Program"); + }); + + it("returns undefined for an unknown id", () => { + expect(getById("does-not-exist")).toBeUndefined(); + }); +}); + +describe("isSupportedVersion", () => { + it.each(SUPPORTED_VERSIONS)("accepts the supported version %s", version => { + expect(isSupportedVersion(version)).toBe(true); + }); + + it("accepts 0.4.0 as a supported version", () => { + expect(isSupportedVersion("0.4.0")).toBe(true); + }); + + it("rejects a version the fixture cannot shape", () => { + expect(isSupportedVersion("0.5.0")).toBe(false); + }); +}); diff --git a/mock-api/__tests__/handlers/opportunities.spec.ts b/mock-api/__tests__/handlers/opportunities.spec.ts new file mode 100644 index 000000000..75ab20842 --- /dev/null +++ b/mock-api/__tests__/handlers/opportunities.spec.ts @@ -0,0 +1,952 @@ +import { describe, it, expect } from "vitest"; +import worker from "../../src/index"; +import { + CANONICAL_OPPORTUNITY_ID, + OPPORTUNITY_FIXTURES, + RESERVED_MISSING_OPPORTUNITY_ID, + type Version, +} from "../../src/data/fixtures"; + +const VERSIONS: Version[] = ["0.1.0", "0.2.0", "0.3.0", "0.4.0"]; + +/** Builds `https://mock.example/v{version}/common-grants/opportunities{suffix}`. */ +function opportunitiesUrl(version: string, suffix = ""): string { + return `https://mock.example/v${version}/common-grants/opportunities${suffix}`; +} + +describe("opportunities routes", () => { + describe("GET /v{version}/common-grants/opportunities (list)", () => { + it("returns a 200 with all fixtures sorted by lastModifiedAt descending and default pagination", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0"))); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + status: number; + message: string; + items: Array<{ lastModifiedAt: string }>; + paginationInfo: { + page: number; + pageSize: number; + totalItems: number; + totalPages: number; + }; + }; + + expect(body.status).toBe(200); + expect(typeof body.message).toBe("string"); + + expect(Array.isArray(body.items)).toBe(true); + expect(body.items).toHaveLength(OPPORTUNITY_FIXTURES.length); + + for (let i = 1; i < body.items.length; i++) { + expect(new Date(body.items[i - 1].lastModifiedAt).getTime()).toBeGreaterThanOrEqual( + new Date(body.items[i].lastModifiedAt).getTime() + ); + } + + expect(body.paginationInfo).toEqual({ + page: 1, + pageSize: 100, + totalItems: OPPORTUNITY_FIXTURES.length, + totalPages: 1, + }); + }); + + it("returns an empty items array with valid paginationInfo when page is past the end", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0", "?page=999"))); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + items: unknown[]; + paginationInfo: { + page: number; + pageSize: number; + totalItems: number; + totalPages: number; + }; + }; + + expect(Array.isArray(body.items)).toBe(true); + expect(body.items).toHaveLength(0); + + expect(body.paginationInfo).toEqual({ + page: 999, + pageSize: 100, + totalItems: OPPORTUNITY_FIXTURES.length, + totalPages: 1, + }); + }); + + it("honors a pageSize above the default, since the spec declares no maximum", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0", "?pageSize=9999"))); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + paginationInfo: { pageSize: number; totalPages: number }; + }; + + expect(body.paginationInfo.pageSize).toBe(9999); + expect(body.paginationInfo.totalPages).toBe(1); + }); + + it.each([ + ["pageSize", "0"], + ["pageSize", "-5"], + ["page", "0"], + ])( + "returns 400 with the protocol Error shape when %s=%s falls below the spec minimum", + async (param, value) => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", `?${param}=${value}`)) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: Array<{ field: string; message: string }>; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.errors).toEqual([{ field: param, message: "Must be at least 1" }]); + } + ); + + it("returns 400 when a pagination param is present but not an integer", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0", "?pageSize=abc"))); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + errors: Array<{ field: string; message: string }>; + }; + + expect(body.errors).toHaveLength(1); + expect(body.errors[0].field).toBe("pageSize"); + expect(body.errors[0].message).toContain("integer"); + }); + + it("applies both spec defaults when the pagination params are omitted entirely", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0"))); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + paginationInfo: { page: number; pageSize: number }; + }; + + expect(body.paginationInfo.page).toBe(1); + expect(body.paginationInfo.pageSize).toBe(100); + }); + }); + + describe("GET /v{version}/common-grants/opportunities/{oppId} (detail)", () => { + // Picks a fixture that carries `competitions` (present on the + // OpportunityDetails shape, stripped from the OpportunityBase/list + // projection) so this test can't pass by accident on a record where the + // two shapes happen to coincide. + const STEM_ID = "573525f2-8e15-4405-83fb-e6523511d893"; + + // Swagger UI pre-fills the `oppId` box with the specs' `Types.uuid` + // example, so this is the request a visitor sends when they click "Try it + // out" and then "Execute" without touching anything. It must not 404. + it.each(VERSIONS)("answers 200 for the id Swagger UI pre-fills, for v%s", async version => { + const response = await worker.fetch( + new Request(opportunitiesUrl(version, `/${CANONICAL_OPPORTUNITY_ID}`)) + ); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + data: { id: string; title: string }; + }; + + expect(body.data.id).toBe(CANONICAL_OPPORTUNITY_ID); + // The values the spec's own "Example Value" pane advertises. + expect(body.data.title).toBe("Small business grant program"); + }); + + it("echoes the requested oppId and matches the list item's shared fields, while adding the detail-only competitions field", async () => { + const listResponse = await worker.fetch(new Request(opportunitiesUrl("0.3.0"))); + + const listBody = (await listResponse.json()) as { + items: Array & { id: string }>; + }; + const listItem = listBody.items.find(item => item.id === STEM_ID); + expect(listItem).toBeDefined(); + // The list (OpportunityBase) projection never carries `competitions`. + expect(listItem).not.toHaveProperty("competitions"); + + const detailResponse = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", `/${STEM_ID}`)) + ); + + expect(detailResponse.status).toBe(200); + + const detailBody = (await detailResponse.json()) as { + status: number; + message: string; + data: Record & { id: string; competitions: unknown }; + }; + + expect(detailBody.status).toBe(200); + // id echo: the returned record's id matches the requested :oppId. + expect(detailBody.data.id).toBe(STEM_ID); + // consistency: every field the list projection carries matches the + // detail record's value for that same field (same underlying record). + for (const [field, value] of Object.entries(listItem!)) { + expect(detailBody.data[field]).toEqual(value); + } + // detail-only field: OpportunityDetails adds `competitions`. + expect(detailBody.data.competitions).toBeDefined(); + }); + + it.each(VERSIONS)( + "returns 404 with the protocol Error shape for a well-formed but unknown UUID, for v%s", + async version => { + const response = await worker.fetch( + new Request(opportunitiesUrl(version, `/${RESERVED_MISSING_OPPORTUNITY_ID}`)) + ); + + expect(response.status).toBe(404); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(404); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + } + ); + + it.each(VERSIONS)( + "returns 400 with a field-level validation error for a malformed (non-UUID) oppId, for v%s", + async version => { + const response = await worker.fetch(new Request(opportunitiesUrl(version, "/not-a-uuid"))); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: Array<{ field: string; message: string }>; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + + const oppIdError = body.errors.find(error => error.field === "oppId"); + expect(oppIdError).toBeDefined(); + expect(typeof oppIdError!.message).toBe("string"); + expect(oppIdError!.message.length).toBeGreaterThan(0); + } + ); + + it("omits competitions and acceptedApplicantTypes from a v0.1 detail response", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.1.0", `/${STEM_ID}`))); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + status: number; + message: string; + data: Record & { id: string }; + }; + + expect(body.data).not.toHaveProperty("competitions"); + expect(body.data).not.toHaveProperty("acceptedApplicantTypes"); + expect(body.data.id).toBe(STEM_ID); + }); + }); + + describe("determinism", () => { + it.each(VERSIONS)( + "returns identical bodies across two calls to the list endpoint for v%s", + async version => { + const responseA = await worker.fetch(new Request(opportunitiesUrl(version))); + const responseB = await worker.fetch(new Request(opportunitiesUrl(version))); + + const bodyA = await responseA.json(); + const bodyB = await responseB.json(); + + expect(bodyA).toEqual(bodyB); + } + ); + + it.each(VERSIONS)( + "returns identical bodies across two calls to the detail endpoint for the same oppId for v%s", + async version => { + const STEM_ID = "573525f2-8e15-4405-83fb-e6523511d893"; + + const responseA = await worker.fetch(new Request(opportunitiesUrl(version, `/${STEM_ID}`))); + const responseB = await worker.fetch(new Request(opportunitiesUrl(version, `/${STEM_ID}`))); + + const bodyA = await responseA.json(); + const bodyB = await responseB.json(); + + expect(bodyA).toEqual(bodyB); + } + ); + + it.each(VERSIONS)( + "list→detail: every field on the list item deep-equals the corresponding detail field, and the detail echoes the requested id, for v%s", + async version => { + const STEM_ID = "573525f2-8e15-4405-83fb-e6523511d893"; + + const listResponse = await worker.fetch(new Request(opportunitiesUrl(version))); + + const listBody = (await listResponse.json()) as { + items: Array & { id: string }>; + }; + const listItem = listBody.items.find(item => item.id === STEM_ID); + expect(listItem).toBeDefined(); + + const detailResponse = await worker.fetch( + new Request(opportunitiesUrl(version, `/${STEM_ID}`)) + ); + + expect(detailResponse.status).toBe(200); + + const detailBody = (await detailResponse.json()) as { + status: number; + message: string; + data: Record & { id: string }; + }; + + expect(detailBody.status).toBe(200); + // id echo: the returned record's id matches the requested :oppId. + expect(detailBody.data.id).toBe(STEM_ID); + // consistency: every field the list projection carries matches the + // detail record's value for that same field (same underlying record). + for (const [field, value] of Object.entries(listItem!)) { + expect(detailBody.data[field]).toEqual(value); + } + } + ); + }); + + describe("POST /v{version}/common-grants/opportunities/search", () => { + async function runSearch(version: string, body: unknown) { + const response = await worker.fetch( + new Request(opportunitiesUrl(version, "/search"), { + method: "POST", + body: JSON.stringify(body), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(200); + + return (await response.json()) as { + status: number; + message: string; + items: Array<{ id: string; status: { value: string } }>; + paginationInfo: unknown; + sortInfo: unknown; + filterInfo: { + filters: Record & { + status?: { operator: string; value: string[] }; + customFilters?: Record; + }; + errors?: unknown[]; + }; + }; + } + + it.each(VERSIONS)( + "filters to a proper subset matching the status filter, relative to the unfiltered result set, for v%s", + async version => { + const unfilteredBody = await runSearch(version, {}); + expect(Array.isArray(unfilteredBody.items)).toBe(true); + expect(unfilteredBody.items.length).toBe(OPPORTUNITY_FIXTURES.length); + + const inBody = await runSearch(version, { + filters: { status: { operator: "in", value: ["open"] } }, + }); + + expect(inBody.items.length).toBeLessThan(OPPORTUNITY_FIXTURES.length); + for (const item of inBody.items) { + expect(item.status.value).toBe("open"); + } + + const notInBody = await runSearch(version, { + filters: { status: { operator: "notIn", value: ["open"] } }, + }); + + for (const item of notInBody.items) { + expect(item.status.value).not.toBe("open"); + } + } + ); + + it.each(VERSIONS)( + "reorders items in reverse when sortOrder flips from asc to desc, for the same sortBy field, for v%s", + async version => { + // `funding.maxAwardAmount` is present (and distinct) on every fixture + // record, so this sort key has no ties/undefined-handling ambiguity. + const ascBody = await runSearch(version, { + sorting: { sortBy: "funding.maxAwardAmount", sortOrder: "asc" }, + }); + const descBody = await runSearch(version, { + sorting: { sortBy: "funding.maxAwardAmount", sortOrder: "desc" }, + }); + + const ascIds = ascBody.items.map(item => item.id); + const descIds = descBody.items.map(item => item.id); + + // Guard against a no-op sort implementation trivially "passing" by both + // orderings being identical (e.g. both left in fixture/insertion order). + expect(ascIds).not.toEqual(descIds); + expect(ascIds).toEqual([...descIds].reverse()); + } + ); + + it.each(VERSIONS)( + "returns 400 with the protocol Error shape for an unknown sortBy value, for v%s", + async version => { + const response = await worker.fetch( + new Request(opportunitiesUrl(version, "/search"), { + method: "POST", + body: JSON.stringify({ + sorting: { sortBy: "not_a_real_sort_field" }, + }), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: Array<{ field: string; message: string }>; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + + const sortByError = body.errors.find(error => "field" in error); + expect(sortByError).toBeDefined(); + } + ); + + it("echoes customFilters in filterInfo.filters without letting them narrow results beyond the applied status filter", async () => { + const requestFilters = { + status: { operator: "in" as const, value: ["open"] }, + customFilters: { legacyId: { operator: "eq", value: 12345 } }, + }; + + const body = await runSearch("0.3.0", { filters: requestFilters }); + + expect(body.filterInfo.filters).toEqual(requestFilters); + expect(body.filterInfo.filters.customFilters).toEqual({ + legacyId: { operator: "eq", value: 12345 }, + }); + expect(body.filterInfo.filters.status).toEqual({ + operator: "in", + value: ["open"], + }); + + // customFilters is echoed only, so results are still narrowed purely by + // the applied `status` filter. + expect(body.items.length).toBeGreaterThan(0); + for (const item of body.items) { + expect(item.status.value).toBe("open"); + } + }); + + it("returns 400 with the protocol Error shape for a malformed JSON body", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: "{not valid json", + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + }); + + // `JSON.parse` accepts any JSON *value*, not just an object, so these bodies + // clear the try/catch around `request.json()` and then get treated as an + // `OppSearchRequest`. Reaching for `.filters` on a non-object is a crash, not + // a 400 — and a crash escaping the handler means the browser sees an opaque + // CORS failure instead of the protocol error envelope. + it.each(["null", "[]", '"a string"', "42", "true"])( + "returns 400 with the protocol Error shape for the valid-JSON-but-not-an-object body %s", + async rawBody => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: rawBody, + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + } + ); + + // The router sends GET on the `/search` path to the detail handler, which + // rejects `search` as a non-UUID `oppId`. That mirrors the #1049 spike, where + // only POST was registered on `/search` and a GET fell through to the + // `:oppId` pattern. Pinned because the router comments call it out by name. + it("answers GET on the search path with the detail handler's 400, as the spike's :oppId pattern did", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0", "/search"))); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: Array<{ field: string; message: string }>; + }; + + expect(body.status).toBe(400); + expect(body.errors[0]).toEqual({ + field: "oppId", + message: "Must be a valid UUID", + }); + }); + + it("partitions the fixture set into disjoint, complementary halves when the same maxAwardAmountRange bound is queried with `between` vs `outside`", async () => { + // Bound chosen against the real fixture data (see fixtures.ts): splits + // the records' `funding.maxAwardAmount` values (25k, 30k, 50k, 50k, 60k, + // 75k, 100k, 120k, 250k, 500k, 2M) across [50000, 250000], so neither + // half is degenerate. + const bound = { + min: { amount: "50000.00", currency: "USD" }, + max: { amount: "250000.00", currency: "USD" }, + }; + + const recordsWithMaxAward = OPPORTUNITY_FIXTURES.filter( + opp => opp.funding?.maxAwardAmount !== undefined + ); + + const betweenBody = await runSearch("0.3.0", { + filters: { + maxAwardAmountRange: { operator: "between", value: bound }, + }, + }); + const outsideBody = await runSearch("0.3.0", { + filters: { + maxAwardAmountRange: { operator: "outside", value: bound }, + }, + }); + + const betweenIds = new Set(betweenBody.items.map(item => item.id)); + const outsideIds = new Set(outsideBody.items.map(item => item.id)); + + expect(betweenIds.size).toBeGreaterThan(0); + expect(outsideIds.size).toBeGreaterThan(0); + + // Disjoint: no id appears in both the "between" and "outside" results. + for (const id of betweenIds) { + expect(outsideIds.has(id)).toBe(false); + } + + // Complementary: together they cover every fixture record that has a + // `funding.maxAwardAmount` value at all. + const unionIds = new Set([...betweenIds, ...outsideIds]); + expect(unionIds.size).toBe(recordsWithMaxAward.length); + for (const opp of recordsWithMaxAward) { + expect(unionIds.has(opp.id)).toBe(true); + } + }); + + it("returns an empty items array with a well-formed envelope when a maxAwardAmountRange bound matches no fixture record", async () => { + // Every fixture's `funding.maxAwardAmount` tops out at 2,000,000.00, so + // this bound is clearly outside all of them. + const body = await runSearch("0.3.0", { + filters: { + maxAwardAmountRange: { + operator: "between", + value: { + min: { amount: "999999999.00", currency: "USD" }, + max: { amount: "1000000000.00", currency: "USD" }, + }, + }, + }, + }); + + expect(body.status).toBe(200); + expect(Array.isArray(body.items)).toBe(true); + expect(body.items).toHaveLength(0); + + expect(body.paginationInfo).toEqual({ + page: 1, + pageSize: 100, + totalItems: 0, + // An empty result set reports zero pages, matching how the list + // endpoint derives `totalPages` (both go through `paginationInfo()`). + totalPages: 0, + }); + + expect(body.sortInfo).toBeTypeOf("object"); + expect(body.sortInfo).not.toBeNull(); + expect(body.filterInfo).toBeTypeOf("object"); + expect(body.filterInfo).not.toBeNull(); + expect(body.filterInfo.filters).toBeDefined(); + }); + + it("excludes every fixture record from a maxAwardAmountRange bound denominated in a different currency, regardless of operator", async () => { + // Every fixture's `funding.maxAwardAmount` is USD-denominated (see + // fixtures.ts's `usd()` helper), and this EUR-denominated bound is wide + // enough to numerically contain every fixture's amount if currency were + // ignored. Per the protocol (`lib/core/lib/core/models/opportunity/search.tsp`), + // a currency mismatch excludes the record regardless of `operator`. + const bound = { + min: { amount: "0.00", currency: "EUR" }, + max: { amount: "999999999.00", currency: "EUR" }, + }; + + const betweenBody = await runSearch("0.3.0", { + filters: { + maxAwardAmountRange: { operator: "between", value: bound }, + }, + }); + + expect(betweenBody.status).toBe(200); + expect(Array.isArray(betweenBody.items)).toBe(true); + expect(betweenBody.items).toHaveLength(0); + expect(betweenBody.paginationInfo).toBeTypeOf("object"); + expect(betweenBody.sortInfo).toBeTypeOf("object"); + expect(betweenBody.filterInfo).toBeTypeOf("object"); + expect(betweenBody.filterInfo.filters).toBeDefined(); + + const outsideBody = await runSearch("0.3.0", { + filters: { + maxAwardAmountRange: { operator: "outside", value: bound }, + }, + }); + + // The currency mismatch excludes the record unconditionally, before the + // operator is even considered, so `outside` also returns zero items + // rather than inverting to the whole fixture set. + expect(outsideBody.items).toHaveLength(0); + }); + + it("returns 400 with the protocol Error shape for an unknown filter operator", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({ + filters: { status: { operator: "contains", value: ["open"] } }, + }), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + }); + + it("returns 400 with the protocol Error shape for a status filter whose value is not an array", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({ + filters: { status: { operator: "in", value: 5 } }, + }), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + }); + + it("returns 400 with the protocol Error shape for a range filter with no value", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({ + filters: { closeDateRange: { operator: "between" } }, + }), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(400); + expect(typeof body.message).toBe("string"); + expect(body.message.length).toBeGreaterThan(0); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + }); + + it("filters using only the given bound when a maxAwardAmountRange filter omits max", async () => { + // Bound chosen against the real fixture data (see fixtures.ts): the + // records' `funding.maxAwardAmount` values (25k, 30k, 50k, 50k, 60k, + // 75k, 100k, 120k, 250k, 500k, 2M) split into those at-or-above 50000 + // and two below it, so this is a proper, non-degenerate subset. + const body = await runSearch("0.3.0", { + filters: { + maxAwardAmountRange: { + operator: "between", + value: { min: { amount: "50000.00", currency: "USD" } }, + }, + }, + }); + + expect(body.items.length).toBeGreaterThan(0); + expect(body.items.length).toBeLessThan(OPPORTUNITY_FIXTURES.length); + + const fullBody = await runSearch("0.3.0", {}); + const itemsById = new Map( + fullBody.items.map(item => [ + item.id, + item as unknown as { + funding?: { maxAwardAmount?: { amount: string } }; + }, + ]) + ); + + for (const item of body.items) { + const fullItem = itemsById.get(item.id); + expect(fullItem?.funding?.maxAwardAmount?.amount).toBeDefined(); + expect(Number(fullItem!.funding!.maxAwardAmount!.amount)).toBeGreaterThanOrEqual(50000); + } + }); + + // A malformed bound used to be dropped silently, which answered a + // filtered request with the entire unfiltered set — the response + // contradicting the filter the caller sent. + it.each([ + [ + "closeDateRange", + { operator: "between", value: { min: "not-a-date" } }, + "filters.closeDateRange.value.min", + ], + [ + "maxAwardAmountRange", + { + operator: "between", + value: { max: { amount: "lots", currency: "USD" } }, + }, + "filters.maxAwardAmountRange.value.max", + ], + [ + "totalFundingAvailableRange", + { operator: "between", value: { min: "50000.00" } }, + "filters.totalFundingAvailableRange.value.min", + ], + ])( + "returns 400 rather than silently dropping a malformed %s bound", + async (field, filter, expectedErrorField) => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({ filters: { [field]: filter } }), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + status: number; + message: string; + errors: Array<{ field: string; message: string }>; + }; + + expect(body.status).toBe(400); + expect(body.errors.map(error => error.field)).toContain(expectedErrorField); + } + ); + + it("reports unapplied customFilters via filterInfo.errors", async () => { + const body = await runSearch("0.3.0", { + filters: { + customFilters: { + agency: { operator: "in", value: ["NSF"] }, + region: { operator: "in", value: ["Northeast"] }, + }, + }, + }); + + // Echoed, but explicitly not applied — so the echo can't be read as + // "these narrowed the results". + expect(body.items).toHaveLength(OPPORTUNITY_FIXTURES.length); + expect(body.filterInfo.filters.customFilters).toEqual({ + agency: { operator: "in", value: ["NSF"] }, + region: { operator: "in", value: ["Northeast"] }, + }); + expect(body.filterInfo.errors).toHaveLength(1); + expect(body.filterInfo.errors![0]).toContain("agency"); + expect(body.filterInfo.errors![0]).toContain("region"); + }); + + it("omits filterInfo.errors when every filter sent was applied", async () => { + const body = await runSearch("0.3.0", { + filters: { status: { operator: "in", value: ["open"] } }, + }); + + expect(body.filterInfo.errors).toBeUndefined(); + }); + + it("returns 400 for a body pagination value below the spec minimum", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({ pagination: { page: 0, pageSize: -1 } }), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + + const body = (await response.json()) as { + errors: Array<{ field: string; message: string }>; + }; + + expect(body.errors.map(error => error.field)).toEqual([ + "pagination.page", + "pagination.pageSize", + ]); + }); + }); +}); + +describe("version path prefix", () => { + it.each(VERSIONS)("resolves the list, detail, and search routes for v%s", async version => { + const listResponse = await worker.fetch(new Request(opportunitiesUrl(version))); + expect(listResponse.status).toBe(200); + + const detailResponse = await worker.fetch( + new Request(opportunitiesUrl(version, `/${CANONICAL_OPPORTUNITY_ID}`)) + ); + expect(detailResponse.status).toBe(200); + + const searchResponse = await worker.fetch( + new Request(opportunitiesUrl(version, "/search"), { + method: "POST", + body: JSON.stringify({}), + headers: { "Content-Type": "application/json" }, + }) + ); + expect(searchResponse.status).toBe(200); + }); + + it("returns 404 with the protocol error envelope for an unsupported version prefix", async () => { + const response = await worker.fetch( + new Request("https://mock.example/v9.9.9/common-grants/opportunities") + ); + + expect(response.status).toBe(404); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(404); + expect(typeof body.message).toBe("string"); + expect(Array.isArray(body.errors)).toBe(true); + }); + + it("returns 404 with the protocol error envelope when the version prefix is missing entirely", async () => { + const response = await worker.fetch( + new Request("https://mock.example/common-grants/opportunities") + ); + + expect(response.status).toBe(404); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(404); + expect(typeof body.message).toBe("string"); + expect(Array.isArray(body.errors)).toBe(true); + }); + + it("returns 404 with the protocol error envelope for a malformed version prefix", async () => { + const response = await worker.fetch( + new Request("https://mock.example/vabc/common-grants/opportunities") + ); + + expect(response.status).toBe(404); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(404); + expect(typeof body.message).toBe("string"); + expect(Array.isArray(body.errors)).toBe(true); + }); +}); diff --git a/mock-api/__tests__/handlers/sdk-envelope.spec.ts b/mock-api/__tests__/handlers/sdk-envelope.spec.ts new file mode 100644 index 000000000..243f68a09 --- /dev/null +++ b/mock-api/__tests__/handlers/sdk-envelope.spec.ts @@ -0,0 +1,210 @@ +/** + * Pins the envelope details the TS SDK's zod schemas depend on (#1077-T3, + * PLAN.md): the search response's `sortInfo` + strict-parsed `filterInfo` + * (no extra keys), and `paginationInfo.totalPages: 0` for empty result sets + * on both the search and list endpoints. + * + * These aren't asserted against `@common-grants/sdk` directly — this package + * doesn't depend on it — but the key sets below are transcribed from the + * actual zod schemas so a drift here is a drift the SDK would choke on: + * + * - `lib/ts-sdk/src/schemas/zod/responses.ts:132-139` — `filterInfo` is a + * `.strict()` zod object with exactly `filters` and an optional `errors`. + * `.strict()` means any *other* key inside `filterInfo` makes the SDK's + * `client.opportunities.search()` throw rather than ignore it. + * - `lib/ts-sdk/src/schemas/zod/sorting.ts:55-67` — `SortedResultsInfoSchema` + * (the `sortInfo` value) requires `sortBy` (string) and `sortOrder` + * (`"asc" | "desc"`), with optional `customSortBy` and `errors`. Not + * `.strict()`, but missing either required field fails SDK parsing. + */ + +import { describe, it, expect } from "vitest"; +import worker from "../../src/index"; +import { OPPORTUNITY_FIXTURES } from "../../src/data/fixtures"; + +/** Builds `https://mock.example/v{version}/common-grants/opportunities{suffix}`. */ +function opportunitiesUrl(version: string, suffix = ""): string { + return `https://mock.example/v${version}/common-grants/opportunities${suffix}`; +} + +/** Runs a search POST and returns the parsed envelope, asserting a 200 first. */ +async function runSearch(body: unknown) { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify(body), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(200); + + return (await response.json()) as { + status: number; + message: string; + items: unknown[]; + paginationInfo: { + page: number; + pageSize: number; + totalItems: number; + totalPages: number; + }; + sortInfo: Record & { + sortBy: string; + sortOrder: string; + }; + filterInfo: Record & { + filters: Record; + errors?: string[]; + }; + }; +} + +describe("search/list envelope shapes the TS SDK's strict zod schemas depend on", () => { + describe("filterInfo carries no keys beyond filters and errors", () => { + // lib/ts-sdk/src/schemas/zod/responses.ts:132-139 — `.strict()` object. + // These three requests never populate filterInfo.errors, so the allowed + // key set is exactly `["filters"]`. + it.each([ + ["a bare {} body with no filters at all", {}], + [ + "a body with a status filter only", + { filters: { status: { operator: "in", value: ["open"] } } }, + ], + [ + // "archived" is a `customValue`, never a `status.value` on any + // fixture record (see src/data/fixtures.ts), so this matches zero. + "a body whose filters match zero records", + { filters: { status: { operator: "in", value: ["archived"] } } }, + ], + ])("holds for %s", async (_label, requestBody) => { + const body = await runSearch(requestBody); + + expect(Object.keys(body.filterInfo).sort()).toEqual(["filters"]); + }); + + it("holds on the customFilters path too, where filterInfo.errors is also present", async () => { + // customFilters is the path that populates filterInfo.errors (see + // "reports unapplied customFilters via filterInfo.errors" in + // opportunities.spec.ts), so here the allowed set is exactly the two + // fields — this is the path most likely to accidentally grow a third. + const body = await runSearch({ + filters: { customFilters: { agency: { operator: "in", value: ["NSF"] } } }, + }); + + expect(Object.keys(body.filterInfo).sort()).toEqual(["errors", "filters"]); + }); + }); + + describe("sortInfo is present on every search response with the SDK's required fields", () => { + // lib/ts-sdk/src/schemas/zod/sorting.ts:55-67 — sortBy/sortOrder required. + it("defaults to lastModifiedAt/desc when the request body omits sorting entirely", async () => { + const body = await runSearch({}); + + expect(typeof body.sortInfo.sortBy).toBe("string"); + expect(["asc", "desc"]).toContain(body.sortInfo.sortOrder); + expect(body.sortInfo.sortBy).toBe("lastModifiedAt"); + expect(body.sortInfo.sortOrder).toBe("desc"); + + expect(Object.keys(body.sortInfo).sort()).toEqual(["sortBy", "sortOrder"]); + }); + + it("carries only sortBy/customSortBy/sortOrder/errors when sorting is given explicitly", async () => { + const body = await runSearch({ + sorting: { sortBy: "funding.maxAwardAmount", sortOrder: "asc" }, + }); + + expect(typeof body.sortInfo.sortBy).toBe("string"); + expect(["asc", "desc"]).toContain(body.sortInfo.sortOrder); + + for (const key of Object.keys(body.sortInfo)) { + expect(["sortBy", "customSortBy", "sortOrder", "errors"]).toContain(key); + } + }); + }); + + describe("paginationInfo.totalPages is 0, not 1, for an empty result set", () => { + it("reports totalPages: 0 when a search's filters match zero fixture records", async () => { + // Math.ceil(0 / pageSize) === 0. An SDK that auto-paginates on + // `page < totalPages` would loop forever against a `1` here. + const body = await runSearch({ + filters: { status: { operator: "in", value: ["archived"] } }, + }); + + expect(body.items).toHaveLength(0); + expect(body.paginationInfo).toEqual({ + page: 1, + pageSize: 100, + totalItems: 0, + totalPages: 0, + }); + }); + }); + + describe("the list endpoint's paginationInfo uses the identical derivation", () => { + // The fixture list is non-empty, so the list route itself can never + // produce a `totalPages: 0` case — that's pinned above via search, which + // shares the same `paginationInfo()` helper (src/handlers/opportunities.ts). + it.each([100, 4])( + "derives totalPages via Math.ceil(totalItems / pageSize) for pageSize=%i", + async pageSize => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", `?pageSize=${pageSize}`)) + ); + + expect(response.status).toBe(200); + + const body = (await response.json()) as { + paginationInfo: { + page: number; + pageSize: number; + totalItems: number; + totalPages: number; + }; + }; + + expect(Object.keys(body.paginationInfo).sort()).toEqual([ + "page", + "pageSize", + "totalItems", + "totalPages", + ]); + expect(body.paginationInfo.totalPages).toBe( + Math.ceil(OPPORTUNITY_FIXTURES.length / pageSize) + ); + } + ); + }); + + describe("top-level envelope key sets", () => { + it("search envelope carries exactly status/message/items/paginationInfo/sortInfo/filterInfo", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({}), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(200); + + const body = (await response.json()) as Record; + + expect(Object.keys(body).sort()).toEqual( + ["status", "message", "items", "paginationInfo", "sortInfo", "filterInfo"].sort() + ); + }); + + it("list envelope carries exactly status/message/items/paginationInfo", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0"))); + + expect(response.status).toBe(200); + + const body = (await response.json()) as Record; + + expect(Object.keys(body).sort()).toEqual( + ["status", "message", "items", "paginationInfo"].sort() + ); + }); + }); +}); diff --git a/mock-api/__tests__/http/cors.spec.ts b/mock-api/__tests__/http/cors.spec.ts new file mode 100644 index 000000000..843f7db9c --- /dev/null +++ b/mock-api/__tests__/http/cors.spec.ts @@ -0,0 +1,257 @@ +import { describe, it, expect, vi } from "vitest"; +import worker from "../../src/index"; +import { + CANONICAL_OPPORTUNITY_ID, + RESERVED_MISSING_OPPORTUNITY_ID, + SUPPORTED_VERSIONS, +} from "../../src/data/fixtures"; +import { withCors } from "../../src/http/cors"; +import { withErrorBoundary } from "../../src/http/envelope"; + +/** Builds `https://mock.example/v{version}/common-grants/opportunities{suffix}`. */ +function opportunitiesUrl(version: string, suffix = ""): string { + return `https://mock.example/v${version}/common-grants/opportunities${suffix}`; +} + +describe("CORS", () => { + describe("success responses carry Access-Control-Allow-Origin: *", () => { + it.each(SUPPORTED_VERSIONS)("list route, for v%s", async version => { + const response = await worker.fetch(new Request(opportunitiesUrl(version))); + + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("detail route", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", `/${CANONICAL_OPPORTUNITY_ID}`)) + ); + + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("search route", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({}), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + }); + + describe("error responses carry Access-Control-Allow-Origin: * too", () => { + it("400 for a malformed (non-UUID) detail oppId", async () => { + const response = await worker.fetch(new Request(opportunitiesUrl("0.3.0", "/not-a-uuid"))); + + expect(response.status).toBe(400); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("404 for a well-formed but unknown detail oppId", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", `/${RESERVED_MISSING_OPPORTUNITY_ID}`)) + ); + + expect(response.status).toBe(404); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("400 for a malformed search request body", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: "{not valid json", + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("404 for an unsupported protocol version prefix", async () => { + const response = await worker.fetch( + new Request("https://mock.example/v9.9.9/common-grants/opportunities") + ); + + expect(response.status).toBe(404); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("404 for an unmatched route", async () => { + const response = await worker.fetch(new Request("https://mock.example/nonexistent")); + + expect(response.status).toBe(404); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("200 health route", async () => { + const response = await worker.fetch(new Request("https://mock.example/")); + + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + }); + + describe("OPTIONS preflight", () => { + const preflightTargets: Array<[string, string]> = [ + ["list", opportunitiesUrl("0.3.0")], + ["detail", opportunitiesUrl("0.3.0", `/${CANONICAL_OPPORTUNITY_ID}`)], + ["search", opportunitiesUrl("0.3.0", "/search")], + ["health", "https://mock.example/"], + ["an unmatched path", "https://mock.example/nonexistent"], + ]; + + it.each(preflightTargets)( + "is answered with preflight headers and no body, for %s", + async (_name, url) => { + const response = await worker.fetch(new Request(url, { method: "OPTIONS" })); + + // 204 is the conventional preflight answer; allowing 200 too so this + // doesn't fail on that choice alone. + expect([200, 204]).toContain(response.status); + + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + + const allowMethods = ( + response.headers.get("Access-Control-Allow-Methods") ?? "" + ).toLowerCase(); + expect(allowMethods).toContain("get"); + expect(allowMethods).toContain("post"); + expect(allowMethods).toContain("options"); + + const allowHeaders = ( + response.headers.get("Access-Control-Allow-Headers") ?? "" + ).toLowerCase(); + expect(allowHeaders).toContain("content-type"); + expect(allowHeaders).toContain("x-api-key"); + expect(allowHeaders).toContain("authorization"); + + const text = await response.text(); + expect(text).toBe(""); + } + ); + + it("answers a browser-shaped preflight (Origin + Access-Control-Request-Method/Headers) the same way", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "OPTIONS", + headers: { + Origin: "https://commongrants.org", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type,x-api-key", + }, + }) + ); + + expect([200, 204]).toContain(response.status); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + + const allowMethods = ( + response.headers.get("Access-Control-Allow-Methods") ?? "" + ).toLowerCase(); + expect(allowMethods).toContain("get"); + expect(allowMethods).toContain("post"); + expect(allowMethods).toContain("options"); + + const allowHeaders = ( + response.headers.get("Access-Control-Allow-Headers") ?? "" + ).toLowerCase(); + expect(allowHeaders).toContain("content-type"); + expect(allowHeaders).toContain("x-api-key"); + expect(allowHeaders).toContain("authorization"); + + const text = await response.text(); + expect(text).toBe(""); + }); + }); + + describe("SDK auth headers on an actual (non-preflight) request", () => { + it("a search request carrying X-API-Key and Authorization still returns 200 with the CORS header", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({}), + headers: { + "Content-Type": "application/json", + "X-API-Key": "test-api-key", + Authorization: "Bearer test-token", + }, + }) + ); + + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + it("a search request with no auth headers (Auth.none()) still returns 200 with the CORS header", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: JSON.stringify({}), + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(200); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + }); + + // A response that never gets built can't carry CORS headers, so an exception + // thrown inside routing costs the caller more than a 500: the browser reports + // an opaque CORS failure and the real cause never reaches the console. These + // pin the last-resort handler that keeps a thrown error on the CORS path. + describe("unexpected failures stay on the CORS path", () => { + it("answers a JSON body that is valid but not an object without throwing, and with the CORS header", async () => { + const response = await worker.fetch( + new Request(opportunitiesUrl("0.3.0", "/search"), { + method: "POST", + body: "null", + headers: { "Content-Type": "application/json" }, + }) + ); + + expect(response.status).toBe(400); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + }); + + // No request can currently make `route()` throw, so this exercises the + // composition `src/index.ts` applies — `withCors(await withErrorBoundary(…))` + // — against a thunk that does. Without the boundary the throw escapes + // `fetch()` entirely and the caller gets no response at all, CORS or not. + it("turns a throw inside routing into a 500 envelope that still carries the CORS header", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); + + try { + const response = withCors( + await withErrorBoundary(() => { + throw new Error("boom"); + }) + ); + + expect(response.status).toBe(500); + expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*"); + + const body = (await response.json()) as { + status: number; + message: string; + errors: unknown[]; + }; + + expect(body.status).toBe(500); + expect(typeof body.message).toBe("string"); + expect(Array.isArray(body.errors)).toBe(true); + expect(body.errors.length).toBeGreaterThan(0); + } finally { + consoleError.mockRestore(); + } + }); + }); +}); diff --git a/mock-api/__tests__/index.spec.ts b/mock-api/__tests__/index.spec.ts new file mode 100644 index 000000000..4f5f07473 --- /dev/null +++ b/mock-api/__tests__/index.spec.ts @@ -0,0 +1,19 @@ +import { describe, it, expect } from "vitest"; +import worker from "../src/index"; + +describe("worker fetch handler", () => { + describe("GET /", () => { + it("returns a health response with the service name and supported versions", async () => { + const response = await worker.fetch(new Request("https://mock.example/")); + + expect(response.status).toBe(200); + expect(response.headers.get("Content-Type")).toContain("application/json"); + + const body = await response.json(); + expect(body).toMatchObject({ + name: "@common-grants/mock-api", + supportedVersions: ["0.1.0", "0.2.0", "0.3.0", "0.4.0"], + }); + }); + }); +}); diff --git a/mock-api/__tests__/utils/schema-validator.ts b/mock-api/__tests__/utils/schema-validator.ts new file mode 100644 index 000000000..8d18427fe --- /dev/null +++ b/mock-api/__tests__/utils/schema-validator.ts @@ -0,0 +1,217 @@ +/** + * Ajv validator for the generated per-version protocol schemas (#1077-T4). + * + * Follows the whole-directory `addSchema` approach in + * `website/src/lib/validation.ts:createAjvWithSchemas` and + * `lib/ts-sdk/__tests__/utils/ajv-validator.ts`: load every schema into one Ajv + * instance and let ajv resolve `$ref`s by `$id` rather than pre-dereferencing. + * + * Why not `$RefParser.dereference` (the approach in + * `website/src/lib/schema/ref-resolver.ts`): the versioned output directories are + * incomplete on their own, so dereferencing dies with ENOENT. `uuid.yaml` is + * absent from all four versioned directories, and dereferencing v0.1.0's + * `OpportunityBase` fails on `OppStatus.yaml`. Overlaying the versioned directory + * on top of the unversioned `public/schemas/yaml/` set fills those gaps while + * letting the versioned copy win wherever it exists. + * + * KNOWN LIMITATION of that overlay — a `$ref` target missing from a version's + * directory falls back to the *current* schema, so it is validated against + * today's shape rather than a genuine historical one. For invariant scalars + * (`uuid.yaml`, no changelog entries) that is harmless. It is not harmless for + * models: `ApplicantType`, `OppStatus`, `CompetitionStatus`, `AppStatus`, and + * `FormResponseStatus` are emitted *only* into `versions/v0.4.0/` even though the + * changelog records them as added in 0.2.0 or earlier. Because v0.2.0's + * `OpportunityBase` does `$ref: ApplicantType.yaml`, this suite checks v0.2.0 and + * v0.3.0 `acceptedApplicantTypes` (and every version's `status`) against the + * current shape. The cause is upstream in + * `website/src/lib/schema/version-generator.ts` (`getSchemaExistence` skips its + * "stop past the target version" check when a version has no changelog entry, so + * a duplicate "Added" log at 0.4.0 overwrites the true added-version), not + * something this suite can correct. So: this catches drift in the opportunity + * models' own fields, and does NOT catch drift in the enum/status models they + * reference. #1077-T7 should record that split. + * + * The schema directories are gitignored build output, so they must be generated + * before this runs — `pnpm --filter @common-grants/mock-api run schemas`, which + * `ci` does for you. Missing schemas raise here rather than skipping: a skipped + * conformance suite reads as a green CI run that validated nothing. + */ + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import Ajv2020 from "ajv/dist/2020"; +import type { ErrorObject, ValidateFunction } from "ajv"; +import addFormats from "ajv-formats"; +import yaml from "js-yaml"; +import type { ShapeVariant, Version } from "../../src/data/fixtures"; + +const UTILS_DIR = path.dirname(fileURLToPath(import.meta.url)); + +/** Unversioned (current) protocol schemas — the fallback layer. */ +const SCHEMAS_DIR = path.resolve(UTILS_DIR, "../../../website/public/schemas/yaml"); + +/** Per-version schemas, one directory per version (`v0.3.0/`). */ +const VERSIONS_DIR = path.join(SCHEMAS_DIR, "versions"); + +/** The command that produces both directories, quoted in the error path below. */ +const GENERATE_HINT = "pnpm --filter @common-grants/mock-api run schemas"; + +/** A compiled validator for one (version, variant) pair. */ +export interface OpportunityValidator { + /** File name of the schema actually used, e.g. `"OpportunityDetails.yaml"`. */ + schemaName: string; + /** True when the version has no `OpportunityDetails` and `OpportunityBase` stood in. */ + isFallback: boolean; + /** Validates `data`, returning whether it conforms. */ + validate(data: unknown): boolean; + /** Readable errors from the most recent `validate()` call ("" when it passed). */ + errorText(): string; +} + +/** + * Whether the generated schema directories are present on disk. + * + * @returns True when both the unversioned and versioned schema sets exist. + */ +export function schemasAvailable(): boolean { + if (!existsSync(SCHEMAS_DIR) || !existsSync(VERSIONS_DIR)) { + return false; + } + return readdirSync(VERSIONS_DIR, { withFileTypes: true }).some( + entry => entry.isDirectory() && entry.name.startsWith("v") + ); +} + +/** Loads every `*.yaml` in a directory, keyed by file name. */ +function loadSchemaDir(dir: string): Map { + const schemas = new Map(); + if (!existsSync(dir)) { + return schemas; + } + + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (!entry.isFile() || !entry.name.endsWith(".yaml")) { + continue; + } + const parsed = yaml.load(readFileSync(path.join(dir, entry.name), "utf-8")); + if (parsed !== null && typeof parsed === "object") { + schemas.set(entry.name, parsed); + } + } + + return schemas; +} + +/** + * Builds an Ajv instance holding one version's view of the protocol: the + * unversioned schemas, overlaid with that version's generated schemas. + * + * `strict: false` is what lets the generated schemas' `examples` keywords through, + * matching `createAjvWithSchemas` in `website/src/lib/validation.ts`. Formats are + * validated for real via `ajv-formats`, following + * `lib/ts-sdk/__tests__/utils/ajv-validator.ts` rather than the website's + * permissive `formats` map: the website is a renderer that must not reject a + * documented example over a format technicality, whereas this suite exists to + * catch drift, and a non-UUID id or malformed `date-time` is drift worth failing on. + * + * `time` is the one format overridden back to the protocol's own definition. + * `isoTime.yaml` emits `format: time` but describes itself as "a time on a clock, + * without a timezone, in ISO 8601 format HH:mm:ss" and publishes `17:00:00` as its + * example — while JSON Schema's `time` is RFC 3339 `full-time`, which requires a + * UTC offset. Strict `ajv-formats` therefore rejects the protocol's own documented + * example (and `Fields.Event`'s, at `lib/core/lib/core/fields/event.tsp:137`), so + * every conformant implementation would fail here, not just this fixture. The + * override matches the declared intent; the mismatch itself is a protocol finding + * for #1077-T7, not something to paper over silently. + */ +function buildAjv(version: Version): Ajv2020 { + const merged = loadSchemaDir(SCHEMAS_DIR); + for (const [name, schema] of loadSchemaDir(path.join(VERSIONS_DIR, `v${version}`))) { + merged.set(name, schema); + } + + const ajv = new Ajv2020({ + allErrors: true, + verbose: true, + strict: false, + validateFormats: true, + }); + addFormats(ajv); + // Must follow addFormats, which registers the strict RFC 3339 `time` this replaces. + ajv.addFormat("time", /^\d{2}:\d{2}:\d{2}$/); + + for (const [name, schema] of merged) { + try { + ajv.addSchema(schema, name); + } catch (cause) { + throw new Error(`Could not register schema ${name} for v${version}`, { cause }); + } + } + + return ajv; +} + +/** One Ajv instance per version — building it parses ~150 YAML files. */ +const ajvByVersion = new Map(); + +function ajvFor(version: Version): Ajv2020 { + const cached = ajvByVersion.get(version); + if (cached) { + return cached; + } + + if (!schemasAvailable()) { + throw new Error( + `Generated schemas not found under ${VERSIONS_DIR}. Run \`${GENERATE_HINT}\` first.` + ); + } + + const ajv = buildAjv(version); + ajvByVersion.set(version, ajv); + return ajv; +} + +/** Formats ajv errors as one `instancePath: message` per line. */ +function formatErrors(errors: ErrorObject[] | null | undefined): string { + if (!errors?.length) { + return ""; + } + return errors.map(err => `${err.instancePath || ""}: ${err.message}`).join("; "); +} + +/** + * Compiles the schema a given endpoint variant emits for a given version. + * + * The list endpoint emits `OpportunityBase` and the single-item read emits + * `OpportunityDetails` — except for v0.1.0, which predates + * `OpportunityDetails`; there the detail variant falls back to + * `OpportunityBase`, which is what the mock actually serves for v0.1. + * + * @param version - Target protocol version. + * @param variant - `"list"` (OpportunityBase) or `"detail"` (OpportunityDetails). + * @returns A validator carrying the resolved schema name and last-error text. + */ +export function getOpportunityValidator( + version: Version, + variant: ShapeVariant +): OpportunityValidator { + const ajv = ajvFor(version); + + const preferred = variant === "list" ? "OpportunityBase.yaml" : "OpportunityDetails.yaml"; + const versionedPath = path.join(VERSIONS_DIR, `v${version}`, preferred); + const isFallback = !existsSync(versionedPath); + const schemaName = isFallback ? "OpportunityBase.yaml" : preferred; + + const validate = ajv.getSchema(schemaName) as ValidateFunction | undefined; + if (!validate) { + throw new Error(`Schema ${schemaName} is not registered for v${version}`); + } + + return { + schemaName, + isFallback, + validate: (data: unknown) => validate(data) as boolean, + errorText: () => formatErrors(validate.errors), + }; +} diff --git a/mock-api/eslint.config.js b/mock-api/eslint.config.js new file mode 100644 index 000000000..7b4ce298d --- /dev/null +++ b/mock-api/eslint.config.js @@ -0,0 +1,34 @@ +// @ts-check +import eslint from "@eslint/js"; +import tsEslint from "typescript-eslint"; +import vitest from "@vitest/eslint-plugin"; +import prettier from "eslint-plugin-prettier"; + +export default [ + { + ignores: ["dist/**/*", "node_modules/**/*", "coverage/**/*", ".wrangler/**/*"], + }, + eslint.configs.recommended, + ...tsEslint.configs.recommended, + { + files: ["**/*.test.ts", "**/*.spec.ts"], + plugins: { + vitest, + }, + rules: { + ...vitest.configs.recommended.rules, + }, + }, + { + plugins: { + prettier, + }, + rules: { + "prettier/prettier": "error", + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }], + "no-console": "off", + }, + }, +]; diff --git a/mock-api/package.json b/mock-api/package.json new file mode 100644 index 000000000..b343b43c4 --- /dev/null +++ b/mock-api/package.json @@ -0,0 +1,46 @@ +{ + "name": "@common-grants/mock-api", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Standalone Cloudflare Worker serving deterministic CommonGrants mock data", + "engines": { + "node": ">=22.0.0" + }, + "scripts": { + "dev": "wrangler dev", + "deploy": "wrangler deploy", + "build": "wrangler deploy --dry-run --outdir dist", + "test": "vitest run", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage", + "lint": "eslint . --fix", + "format": "prettier --write .", + "check:lint": "eslint", + "check:format": "prettier --check .", + "check:types": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json", + "checks": "pnpm run check:lint && pnpm run check:format && pnpm run check:types", + "schemas": "pnpm --filter website run typespec && pnpm --filter website run generate:versioned-schemas", + "ci": "pnpm run checks && pnpm run build && pnpm run schemas && pnpm run test", + "audit": "pnpm audit" + }, + "devDependencies": { + "@cloudflare/workers-types": "^5.20260810.1", + "@eslint/js": "catalog:", + "@types/js-yaml": "^4.0.9", + "@types/node": "catalog:", + "@vitest/coverage-v8": "catalog:", + "@vitest/eslint-plugin": "catalog:", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "eslint": "catalog:", + "eslint-config-prettier": "catalog:", + "eslint-plugin-prettier": "catalog:", + "js-yaml": "^4.3.1", + "prettier": "catalog:", + "typescript": "catalog:", + "typescript-eslint": "catalog:", + "vitest": "catalog:", + "wrangler": "^4.117.0" + } +} diff --git a/mock-api/src/data/fixtures.ts b/mock-api/src/data/fixtures.ts new file mode 100644 index 000000000..10529df82 --- /dev/null +++ b/mock-api/src/data/fixtures.ts @@ -0,0 +1,698 @@ +/** + * Shared opportunity fixture for the standalone Worker mock (#1077-T2). + * + * Ported unchanged from the MSW mock-playground spike (#1049, branch + * `karina/playground-spike`), which carried zero MSW imports in this file — + * only its sibling `handlers.ts` was coupled to MSW, which is why the records + * and shaping moved over as-is while the handlers get rewritten (#1077-T3). + * + * A fixed, hand-authored dataset that the deterministic opportunity handlers + * draw from, so the list, detail, and search endpoints stay mutually + * consistent and return the same body on every call. Values are + * assembled from the TypeSpec `@example` decorators under + * `lib/core/lib/core/models/opportunity/` (semantic, not faker noise). The + * first record reproduces the spec's own published example (see + * `CANONICAL_OPPORTUNITY_ID`) so the docs pane and the live response agree, and + * the next three are carried over verbatim (id + title) from + * `lib/ts-sdk/examples/mock-api-server.ts` so cross-repo examples stay + * recognizable. + * + * Records are stored in their fullest (v0.3+, detail) shape. + * `shapeOpportunityForVersion` projects them down to the version/variant a given + * endpoint should emit: + * - `acceptedApplicantTypes` was added in v0.2 → stripped for v0.1. + * - `competitions` lives only on `OpportunityDetails` (added v0.2) → stripped + * for v0.1 and from any `list`-variant projection. + */ + +/** + * Protocol versions this fixture knows how to shape, matching the versions the + * docs site publishes specs for (`website/public/openapi/openapi.{v}.yaml`). + * Shipping a spec version the docs offer without adding it here is caught by + * `isSupportedVersion`, which keeps the mock from silently 404-ing a version a + * visitor can select. + * + * v0.4.0 (#976) added awards/organizations routes but left the opportunity + * models untouched, so it shapes identically to v0.3.0 — no new branch in + * `shapeOpportunityForVersion`. #1077-T4 verifies that against the generated + * per-version schemas rather than trusting this comment. + */ +export const SUPPORTED_VERSIONS = ["0.1.0", "0.2.0", "0.3.0", "0.4.0"] as const; + +/** A protocol version the opportunity handlers can shape responses for. */ +export type Version = (typeof SUPPORTED_VERSIONS)[number]; + +/** Narrows an arbitrary version string to a `Version`. */ +export function isSupportedVersion(value: string): value is Version { + return (SUPPORTED_VERSIONS as readonly string[]).includes(value); +} + +/** Which endpoint shape to project: the list returns `OpportunityBase`, the + * single-item read returns `OpportunityDetails` (v0.2+). */ +export type ShapeVariant = "list" | "detail"; + +/** A monetary amount and its ISO 4217 currency (mirrors `Fields.Money`). */ +export interface Money { + amount: string; + currency: string; +} + +/** Opportunity status (mirrors `Models.OppStatus`). */ +export interface OppStatus { + value: "forecasted" | "open" | "closed" | "custom"; + customValue?: string; + description?: string; +} + +/** A single-date event (mirrors the `singleDate` variant of `Fields.Event`). */ +export interface SingleDateEvent { + name: string; + eventType: "singleDate"; + date: string; + time?: string; + description?: string; +} + +/** A date-range event (mirrors the `dateRange` variant of `Fields.Event`). */ +export interface DateRangeEvent { + name: string; + eventType: "dateRange"; + startDate: string; + startTime?: string; + endDate: string; + endTime?: string; + description?: string; +} + +/** A free-form event (mirrors the `other` variant of `Fields.Event`). */ +export interface OtherEvent { + name: string; + eventType: "other"; + details?: string; + description?: string; +} + +/** + * Any `Fields.Event` variant. Named `TimelineEvent` rather than `Event` so it + * doesn't shadow the DOM global in files that use both. + */ +export type TimelineEvent = SingleDateEvent | DateRangeEvent | OtherEvent; + +/** + * Key dates for an opportunity (mirrors `Models.OppTimeline`). `postDate` and + * `closeDate` are narrowed to `SingleDateEvent` — the protocol allows any + * `Event` variant, but the close-date filter and sort read `.date`, so the + * fixture only ever uses single dates for those two. + */ +export interface OppTimeline { + postDate?: SingleDateEvent; + closeDate?: SingleDateEvent; + otherDates?: Record; +} + +/** Funding details for an opportunity (mirrors `Models.OppFunding`). */ +export interface OppFunding { + details?: string; + totalAmountAvailable?: Money; + minAwardAmount?: Money; + maxAwardAmount?: Money; + minAwardCount?: number; + maxAwardCount?: number; + estimatedAwardCount?: number; +} + +/** An accepted applicant type (mirrors `Models.ApplicantType`, added v0.2). */ +export interface ApplicantType { + value: string; + customValue?: string; + description?: string; +} + +/** A custom field (mirrors `Fields.CustomField`). */ +export interface CustomField { + name: string; + fieldType: string; + value: unknown; + description?: string; +} + +/** Competition status (mirrors `Models.CompetitionStatus`, added v0.2). */ +export interface CompetitionStatus { + value: "open" | "closed" | "custom"; + customValue?: string; + description?: string; +} + +/** + * Key dates for a competition (mirrors `Models.CompetitionTimeline`, added + * v0.2). Distinct from `OppTimeline`: competitions use `openDate` (not the + * opportunity's `postDate`). + */ +export interface CompetitionTimeline { + openDate?: SingleDateEvent; + closeDate?: SingleDateEvent; + otherDates?: Record; +} + +/** + * A trimmed competition (mirrors the identifying fields of + * `Models.CompetitionBase`, added v0.2). The full model carries a required + * `forms` object; the mock omits it deliberately since these bodies are served + * as-is (not schema-validated at runtime) and the deep form nesting adds no + * demo value. + */ +export interface Competition { + id: string; + opportunityId: string; + title: string; + description?: string; + status: CompetitionStatus; + keyDates?: CompetitionTimeline; +} + +/** A funding opportunity in its fullest (v0.3+, detail) shape. */ +export interface Opportunity { + id: string; + title: string; + status: OppStatus; + description: string; + funding?: OppFunding; + keyDates?: OppTimeline; + acceptedApplicantTypes?: ApplicantType[]; + source?: string; + customFields?: Record; + competitions?: Competition[]; + createdAt: string; + lastModifiedAt: string; +} + +/** Convenience builder for a `Money` amount in USD. */ +function usd(amount: string): Money { + return { amount, currency: "USD" }; +} + +/** Convenience builder for a single-date `closeDate` event. */ +function closeOn(date: string): SingleDateEvent { + return { + name: "Opportunity close date", + eventType: "singleDate", + date, + time: "17:00:00", + description: "Opportunity closes for all applications", + }; +} + +/** Convenience builder for a single-date `postDate` event. */ +function postOn(date: string): SingleDateEvent { + return { + name: "Opportunity posted date", + eventType: "singleDate", + date, + description: "Opportunity is posted publicly", + }; +} + +const legacyId = (value: number): CustomField => ({ + name: "legacyId", + fieldType: "integer", + value, + description: "Legacy system opportunity ID", +}); + +const programCode = (value: string): CustomField => ({ + name: "programCode", + fieldType: "string", + value, + description: "Funding program code", +}); + +/** + * The id the specs publish as the `example` on `CommonGrants.Types.uuid`, which + * Swagger UI pre-fills into the `oppId` box when a visitor clicks "Try it out" + * on `GET /common-grants/opportunities/{oppId}`. A fixture record MUST carry + * this id, or the very first Execute a visitor runs — with the field untouched + * — answers 404. It is also the id used throughout the rendered "Example Value" + * panes, so the record carrying it mirrors those documented values field for + * field. + */ +export const CANONICAL_OPPORTUNITY_ID = "30a12e5e-5940-4c08-921c-17a8960fcf4b"; + +/** + * A well-formed UUID deliberately absent from the fixture, reserved so the + * detail endpoint's 404 branch has a stable id to demonstrate — it must never + * be given to a record. + */ +export const RESERVED_MISSING_OPPORTUNITY_ID = "00000000-0000-0000-0000-000000000000"; + +/** + * The fixture set: 11 opportunities spanning all four statuses, a range of + * funding amounts, and varied close dates so filtering and sorting visibly + * change results. Sorted newest-first by `lastModifiedAt` to match the list + * endpoint's default ordering. + */ +export const OPPORTUNITY_FIXTURES: readonly Opportunity[] = Object.freeze([ + // ---- The spec's own documented example (see CANONICAL_OPPORTUNITY_ID) ---- + { + // Field values here are copied verbatim from the `@example` decorators the + // spec renders in Swagger UI's "Example Value" pane for this endpoint + // (`Types.uuid`, `OpportunityBase.title`/`.description`, `OppStatus`, + // `OppFunding`, `OppTimeline`), so the documented example and the mock's + // live response agree field for field. Do not "fix" the 2024 dates against + // the `open` status — matching the published example is the point. + id: CANONICAL_OPPORTUNITY_ID, + title: "Small business grant program", + status: { + value: "open", + description: "The opportunity is currently accepting applications", + }, + description: + "This program provides funding to small businesses to help them grow and create jobs", + funding: { + totalAmountAvailable: usd("1000000.00"), + minAwardAmount: usd("10000.00"), + maxAwardAmount: usd("50000.00"), + minAwardCount: 5, + maxAwardCount: 20, + estimatedAwardCount: 10, + }, + keyDates: { + postDate: { + name: "Opportunity posted date", + eventType: "singleDate", + date: "2024-01-15", + description: "Opportunity is posted publicly", + }, + closeDate: { + name: "Opportunity close date", + eventType: "singleDate", + date: "2024-12-31", + time: "17:00:00", + description: "Opportunity closes for all applications", + }, + otherDates: { + anticipatedAward: { + name: "Anticipated award date", + eventType: "singleDate", + date: "2025-03-15", + description: "When we expect to announce awards for this opportunity.", + }, + applicationPeriod: { + name: "Application period", + eventType: "dateRange", + startDate: "2024-01-01", + endDate: "2024-01-31", + endTime: "17:00:00", + description: "Primary application period for the grant opportunity", + }, + performancePeriod: { + name: "Period of Performance", + eventType: "dateRange", + startDate: "2024-01-01", + endDate: "2024-12-31", + description: "Period of performance for the grant", + }, + infoSessions: { + name: "Info sessions", + eventType: "other", + details: "Every other Tuesday", + description: "Info sessions for the opportunity", + }, + }, + }, + acceptedApplicantTypes: [ + { + value: "for_profit_small_business", + description: "For-profit small businesses", + }, + ], + source: "https://grants.example.gov/opportunities/small-business", + customFields: { + legacyId: legacyId(12344), + programCode: programCode("SMALL-BIZ"), + }, + competitions: [ + { + id: "c0a1b2c3-d4e5-4f60-8a1b-2c3d4e5f6a60", + opportunityId: CANONICAL_OPPORTUNITY_ID, + title: "Small business grant program — 2024 Cycle", + description: "The primary application cycle for the 2024 program year.", + status: { value: "open", description: "Accepting applications" }, + keyDates: { + closeDate: closeOn("2024-12-31"), + }, + }, + ], + // No `@example` exists for the readOnly audit timestamps; these are chosen + // so this record sorts first under the list endpoint's default + // `lastModifiedAt desc` ordering, putting the documented example at the top + // of the list response. + createdAt: "2024-01-15T00:00:00Z", + lastModifiedAt: "2025-06-01T00:00:00Z", + }, + // ---- Carried over from lib/ts-sdk/examples/mock-api-server.ts (id + title) ---- + { + id: "573525f2-8e15-4405-83fb-e6523511d893", + title: "STEM Education Grant Program", + status: { value: "open", description: "Currently accepting applications" }, + description: "A grant program focused on improving STEM education in under-resourced schools.", + funding: { + totalAmountAvailable: usd("2000000.00"), + minAwardAmount: usd("25000.00"), + maxAwardAmount: usd("250000.00"), + minAwardCount: 8, + maxAwardCount: 40, + estimatedAwardCount: 20, + }, + keyDates: { + postDate: postOn("2025-01-15"), + closeDate: closeOn("2025-06-30"), + }, + acceptedApplicantTypes: [ + { + value: "school_district_independent", + description: "Independent school districts", + }, + { value: "higher_education_public", description: "Public universities" }, + ], + source: "https://grants.example.gov/opportunities/stem-education", + customFields: { + legacyId: legacyId(12345), + programCode: programCode("STEM-ED"), + }, + competitions: [ + { + id: "c1a2b3c4-d5e6-4f70-8a1b-2c3d4e5f6a70", + opportunityId: "573525f2-8e15-4405-83fb-e6523511d893", + title: "STEM Education Grant — 2025 Cohort", + description: "The primary application cycle for the 2025 STEM cohort.", + status: { value: "open", description: "Accepting applications" }, + keyDates: { closeDate: closeOn("2025-06-30") }, + }, + ], + createdAt: "2025-01-01T00:00:00Z", + lastModifiedAt: "2025-01-15T00:00:00Z", + }, + { + id: "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + title: "Community Development Grant", + status: { value: "open", description: "Currently accepting applications" }, + description: "Funding for community development projects in rural areas.", + funding: { + totalAmountAvailable: usd("500000.00"), + minAwardAmount: usd("10000.00"), + maxAwardAmount: usd("50000.00"), + minAwardCount: 5, + maxAwardCount: 20, + estimatedAwardCount: 10, + }, + keyDates: { + postDate: postOn("2025-01-16"), + closeDate: closeOn("2025-08-15"), + }, + acceptedApplicantTypes: [ + { value: "non_profit_with_501c3", description: "501(c)(3) non-profits" }, + { + value: "government_municipal", + description: "City or township governments", + }, + ], + customFields: { + legacyId: legacyId(12346), + programCode: programCode("COMM-DEV"), + }, + createdAt: "2025-01-02T00:00:00Z", + lastModifiedAt: "2025-01-16T00:00:00Z", + }, + { + id: "b2c3d4e5-f6a7-8901-bcde-f12345678901", + title: "Education Initiative", + status: { + value: "forecasted", + description: "Not yet open for applications", + }, + description: "Support for education initiatives, opening later this year.", + funding: { + totalAmountAvailable: usd("1000000.00"), + minAwardAmount: usd("20000.00"), + maxAwardAmount: usd("100000.00"), + estimatedAwardCount: 15, + }, + keyDates: { + postDate: postOn("2025-01-17"), + closeDate: closeOn("2025-11-01"), + }, + acceptedApplicantTypes: [ + { + value: "higher_education_private", + description: "Private universities", + }, + ], + customFields: { + legacyId: legacyId(12347), + programCode: programCode("EDU-INIT"), + }, + createdAt: "2025-01-03T00:00:00Z", + lastModifiedAt: "2025-01-17T00:00:00Z", + }, + // ---- Additional records for filter/sort variety ---- + { + id: "1f0a2b3c-4d5e-4f60-8a1b-2c3d4e5f6a7b", + title: "Rural Broadband Expansion", + status: { value: "forecasted", description: "Anticipated to open in Q3" }, + description: "Expanding high-speed broadband access to unserved rural communities.", + funding: { + details: "Large infrastructure awards for multi-county deployments.", + totalAmountAvailable: usd("10000000.00"), + minAwardAmount: usd("100000.00"), + maxAwardAmount: usd("2000000.00"), + minAwardCount: 3, + maxAwardCount: 12, + estimatedAwardCount: 6, + }, + keyDates: { + postDate: postOn("2025-02-01"), + closeDate: closeOn("2026-01-31"), + }, + acceptedApplicantTypes: [ + { value: "government_county", description: "County governments" }, + { + value: "for_profit_small_business", + description: "Small telecom providers", + }, + ], + createdAt: "2025-02-01T00:00:00Z", + lastModifiedAt: "2025-02-10T00:00:00Z", + }, + { + id: "2a3b4c5d-6e7f-4081-9b2c-3d4e5f6a7b8c", + title: "Small Business Recovery Fund", + status: { value: "open", description: "Currently accepting applications" }, + description: "Grants to help small businesses recover from economic disruption.", + funding: { + details: "We'll be awarding between $5,000 and $25,000 per recipient", + minAwardAmount: usd("5000.00"), + maxAwardAmount: usd("25000.00"), + minAwardCount: 20, + maxAwardCount: 100, + estimatedAwardCount: 60, + }, + keyDates: { + postDate: postOn("2025-02-15"), + closeDate: closeOn("2025-07-15"), + }, + acceptedApplicantTypes: [ + { + value: "for_profit_small_business", + description: "For-profit small businesses", + }, + ], + createdAt: "2025-02-15T00:00:00Z", + lastModifiedAt: "2025-02-20T00:00:00Z", + }, + { + id: "3b4c5d6e-7f80-4192-8c3d-4e5f6a7b8c9d", + title: "Coastal Resilience Grant", + status: { + value: "closed", + description: "No longer accepting applications", + }, + description: "Funding for coastal communities to build resilience against flooding.", + funding: { + totalAmountAvailable: usd("250000.00"), + minAwardAmount: usd("15000.00"), + maxAwardAmount: usd("75000.00"), + estimatedAwardCount: 5, + }, + keyDates: { + postDate: postOn("2024-06-01"), + closeDate: closeOn("2024-12-31"), + }, + acceptedApplicantTypes: [ + { value: "government_municipal", description: "Coastal municipalities" }, + ], + createdAt: "2024-06-01T00:00:00Z", + lastModifiedAt: "2025-01-05T00:00:00Z", + }, + { + id: "4c5d6e7f-8091-42a3-9d4e-5f6a7b8c9d0e", + title: "Clean Energy Innovation", + status: { value: "open", description: "Currently accepting applications" }, + description: "Supporting research and deployment of clean energy technologies.", + funding: { + totalAmountAvailable: usd("5000000.00"), + minAwardAmount: usd("50000.00"), + maxAwardAmount: usd("500000.00"), + minAwardCount: 5, + maxAwardCount: 25, + estimatedAwardCount: 12, + }, + keyDates: { + postDate: postOn("2025-03-01"), + closeDate: closeOn("2025-09-30"), + }, + acceptedApplicantTypes: [ + { + value: "higher_education_public", + description: "Public research universities", + }, + { + value: "for_profit_not_small_business", + description: "Energy companies", + }, + ], + competitions: [ + { + id: "c2b3c4d5-e6f7-4081-9b2c-3d4e5f6a7b81", + opportunityId: "4c5d6e7f-8091-42a3-9d4e-5f6a7b8c9d0e", + title: "Clean Energy Innovation — Research Track", + description: "Applications for early-stage research projects.", + status: { value: "open", description: "Accepting applications" }, + keyDates: { closeDate: closeOn("2025-09-30") }, + }, + ], + createdAt: "2025-03-01T00:00:00Z", + lastModifiedAt: "2025-03-12T00:00:00Z", + }, + { + id: "5d6e7f80-91a2-43b4-8e5f-6a7b8c9d0e1f", + title: "Workforce Apprenticeship Program", + status: { + value: "closed", + description: "No longer accepting applications", + }, + description: "Establishing registered apprenticeships in high-demand trades.", + funding: { + totalAmountAvailable: usd("1200000.00"), + minAwardAmount: usd("30000.00"), + maxAwardAmount: usd("120000.00"), + estimatedAwardCount: 10, + }, + keyDates: { + postDate: postOn("2024-09-01"), + closeDate: closeOn("2025-02-28"), + }, + acceptedApplicantTypes: [ + { + value: "organization", + description: "Workforce development organizations", + }, + ], + createdAt: "2024-09-01T00:00:00Z", + lastModifiedAt: "2025-02-28T00:00:00Z", + }, + { + id: "6e7f8091-a2b3-44c5-9f60-7b8c9d0e1f20", + title: "Community Health Outreach", + status: { + value: "custom", + customValue: "under_review", + description: "Applications received are under review by the committee", + }, + description: "Expanding preventive health services in underserved neighborhoods.", + funding: { + totalAmountAvailable: usd("750000.00"), + minAwardAmount: usd("10000.00"), + maxAwardAmount: usd("60000.00"), + estimatedAwardCount: 15, + }, + keyDates: { + postDate: postOn("2025-01-10"), + closeDate: closeOn("2025-05-15"), + }, + acceptedApplicantTypes: [ + { + value: "non_profit_with_501c3", + description: "Community health non-profits", + }, + ], + createdAt: "2025-01-10T00:00:00Z", + lastModifiedAt: "2025-05-16T00:00:00Z", + }, + { + id: "7f8091a2-b3c4-45d6-8071-8c9d0e1f2031", + title: "Arts & Culture Preservation", + status: { + value: "custom", + customValue: "archived", + description: "The opportunity is archived and shouldn't appear in search results", + }, + description: "Preserving local arts, cultural heritage, and historic landmarks.", + funding: { + totalAmountAvailable: usd("300000.00"), + minAwardAmount: usd("5000.00"), + maxAwardAmount: usd("30000.00"), + estimatedAwardCount: 20, + }, + keyDates: { + postDate: postOn("2024-04-01"), + closeDate: closeOn("2024-10-31"), + }, + acceptedApplicantTypes: [ + { value: "non_profit_with_501c3", description: "Arts non-profits" }, + { value: "individual", description: "Individual artists" }, + ], + createdAt: "2024-04-01T00:00:00Z", + lastModifiedAt: "2024-11-01T00:00:00Z", + }, +]); + +/** + * Projects an opportunity down to the shape a given protocol version + endpoint + * variant should emit. Strips fields that don't exist in the target version and + * removes `competitions` from list-variant projections. + * + * @param opp - A full (v0.3+, detail) fixture record. + * @param version - Target protocol version. + * @param variant - `"list"` (OpportunityBase) or `"detail"` (OpportunityDetails). + * @returns A shallow copy projected to the target shape (original is untouched). + */ +export function shapeOpportunityForVersion( + opp: Opportunity, + version: Version, + variant: ShapeVariant = "list" +): Opportunity { + const shaped: Opportunity = { ...opp }; + + // `competitions` only exists on the detail (OpportunityDetails) shape. + if (variant === "list") { + delete shaped.competitions; + } + + // v0.1 predates both `acceptedApplicantTypes` and `OpportunityDetails`. + if (version === "0.1.0") { + delete shaped.acceptedApplicantTypes; + delete shaped.competitions; + } + + return shaped; +} + +/** Looks up a fixture record by its exact id. */ +export function getById(id: string): Opportunity | undefined { + return OPPORTUNITY_FIXTURES.find(opp => opp.id === id); +} + +/** Returns every fixture projected to the list (OpportunityBase) shape for a version. */ +export function allForVersion(version: Version): Opportunity[] { + return OPPORTUNITY_FIXTURES.map(opp => shapeOpportunityForVersion(opp, version, "list")); +} diff --git a/mock-api/src/handlers/opportunities.ts b/mock-api/src/handlers/opportunities.ts new file mode 100644 index 000000000..da24ac3b4 --- /dev/null +++ b/mock-api/src/handlers/opportunities.ts @@ -0,0 +1,573 @@ +/** + * Deterministic, fixture-backed handlers for the CommonGrants opportunity list, + * detail, and search endpoints (#1077-T3). + * + * Ported from the MSW mock-playground spike (#1049, branch + * `karina/playground-spike`, `website/src/lib/mock/opportunities/handlers.ts`). + * MSW touched this module in exactly two places, both removed here: + * - `http.get/post(PATH, resolver)` registration → the three exported + * `(Request, Version) => Response` functions below, dispatched by the router + * in `src/index.ts`. + * - `HttpResponse.json` → `Response.json` (see `src/http/envelope.ts`). + * + * Every filter, sort, pagination, and validation rule is carried over + * unchanged, so the Worker's envelopes stay byte-identical to the spike's for + * the same inputs. + * + * Bodies are static projections of `OPPORTUNITY_FIXTURES`, so repeat calls + * return identical results and the list, detail, and search endpoints resolve + * to the same records. + */ + +import { + allForVersion, + getById, + shapeOpportunityForVersion, + type Money, + type Opportunity, + type Version, +} from "../data/fixtures"; +import { errorResponse, successResponse, type FieldError } from "../http/envelope"; + +/** Spec defaults for `Pagination.PaginatedQueryParams` / `PaginatedBodyParams`. */ +const DEFAULT_PAGE = 1; +const DEFAULT_PAGE_SIZE = 100; +/** Both params declare `minimum: 1` and no maximum. */ +const MIN_PAGE_VALUE = 1; + +/** Wire values of `Models.OppSortBy` (`lib/core/lib/core/models/opportunity/search.tsp`). */ +const VALID_SORT_BY = new Set([ + "lastModifiedAt", + "createdAt", + "title", + "status.value", + "keyDates.closeDate", + "funding.maxAwardAmount", + "funding.minAwardAmount", + "funding.totalAmountAvailable", + "funding.estimatedAwardCount", + "custom", +]); + +const VALID_SORT_ORDER = new Set(["asc", "desc"]); +const VALID_ARRAY_OPERATORS = new Set(["in", "notIn"]); +const VALID_RANGE_OPERATORS = new Set(["between", "outside"]); + +/** + * The filter/sort/pagination shapes below describe what a *well-formed* request + * body looks like. Bodies arrive as untrusted JSON, so the search handler + * validates every field — operator, bound presence, and bound value — and + * answers 400 before any of these types are relied on. + */ +interface StringArrayFilter { + operator: string; + value: string[]; +} + +interface DateRangeFilter { + operator: string; + value: { min?: string; max?: string }; +} + +interface MoneyRangeFilter { + operator: string; + value: { min?: Money; max?: Money }; +} + +/** The money-range filter fields of `Models.OppFilters`. */ +const MONEY_RANGE_FIELDS = [ + "totalFundingAvailableRange", + "minAwardAmountRange", + "maxAwardAmountRange", +] as const; + +interface OppFilters { + status?: StringArrayFilter; + closeDateRange?: DateRangeFilter; + totalFundingAvailableRange?: MoneyRangeFilter; + minAwardAmountRange?: MoneyRangeFilter; + maxAwardAmountRange?: MoneyRangeFilter; + customFilters?: Record; +} + +interface OppSorting { + sortBy: string; + customSortBy?: string; + sortOrder?: string; +} + +interface SearchRequestBody { + search?: string; + filters?: OppFilters; + sorting?: OppSorting; + pagination?: { page?: number; pageSize?: number }; +} + +function moneyAmount(value: unknown): number | undefined { + if (value && typeof value === "object" && "amount" in value) { + const amount = Number((value as { amount: string }).amount); + return Number.isFinite(amount) ? amount : undefined; + } + return undefined; +} + +function dateTime(value: unknown): number | undefined { + if (typeof value !== "string") return undefined; + const ms = new Date(value).getTime(); + return Number.isNaN(ms) ? undefined : ms; +} + +/** True if `value` is a `Money` object whose `amount` parses as a number. */ +function isMoney(value: unknown): value is Money { + return ( + typeof value === "object" && + value !== null && + typeof (value as Money).currency === "string" && + moneyAmount(value) !== undefined + ); +} + +/** Applies a `StringArrayFilter` (`in`/`notIn`) over the `status.value` field. */ +function applyStatusFilter(items: Opportunity[], filter: StringArrayFilter): Opportunity[] { + const allowed = new Set(filter.value); + return items.filter(opp => { + const inSet = allowed.has(opp.status.value); + return filter.operator === "notIn" ? !inSet : inSet; + }); +} + +/** + * Applies a date `RangeFilter` (`between`/`outside`) over a field extracted by + * `getValue`. Either bound may be omitted (filters on the one given). + */ +function applyDateRangeFilter( + items: Opportunity[], + filter: DateRangeFilter, + getValue: (opp: Opportunity) => number | undefined +): Opportunity[] { + const min = dateTime(filter.value.min); + const max = dateTime(filter.value.max); + + return items.filter(opp => { + const value = getValue(opp); + if (value === undefined) return false; + const inRange = (min === undefined || value >= min) && (max === undefined || value <= max); + return filter.operator === "outside" ? !inRange : inRange; + }); +} + +/** + * Applies a `MoneyRangeFilter` (`between`/`outside`) over a `Money` field + * extracted by `getMoney`. Either bound may be omitted (filters on the one + * given). Per the protocol (`totalFundingAvailableRange` et al. in + * `lib/core/lib/core/models/opportunity/search.tsp`), amounts denominated in a + * different currency than the filter bound are excluded from the match + * regardless of `operator`. + */ +function applyMoneyRangeFilter( + items: Opportunity[], + filter: MoneyRangeFilter, + getMoney: (opp: Opportunity) => Money | undefined +): Opportunity[] { + const { min: minBound, max: maxBound } = filter.value; + const currency = minBound?.currency ?? maxBound?.currency; + const min = moneyAmount(minBound); + const max = moneyAmount(maxBound); + + return items.filter(opp => { + const money = getMoney(opp); + if (!money) return false; + if (currency !== undefined && money.currency !== currency) return false; + const value = Number(money.amount); + const inRange = (min === undefined || value >= min) && (max === undefined || value <= max); + return filter.operator === "outside" ? !inRange : inRange; + }); +} + +/** Extracts the field an `OppSortBy` wire value sorts on, as a string or number. */ +function sortKey(opp: Opportunity, sortBy: string): string | number { + switch (sortBy) { + case "lastModifiedAt": + return new Date(opp.lastModifiedAt).getTime(); + case "createdAt": + return new Date(opp.createdAt).getTime(); + case "title": + return opp.title; + case "status.value": + return opp.status.value; + case "keyDates.closeDate": + return dateTime(opp.keyDates?.closeDate?.date) ?? 0; + case "funding.maxAwardAmount": + return moneyAmount(opp.funding?.maxAwardAmount) ?? 0; + case "funding.minAwardAmount": + return moneyAmount(opp.funding?.minAwardAmount) ?? 0; + case "funding.totalAmountAvailable": + return moneyAmount(opp.funding?.totalAmountAvailable) ?? 0; + case "funding.estimatedAwardCount": + return opp.funding?.estimatedAwardCount ?? 0; + default: + // "custom" (application-defined field) - no built-in ordering to apply. + return 0; + } +} + +function compare(a: string | number, b: string | number): number { + if (typeof a === "string" || typeof b === "string") { + return String(a).localeCompare(String(b)); + } + return a - b; +} + +/** + * Orders items by `sortBy`, breaking ties on `id`. The tiebreaker makes the + * ordering a total order: without it, records sharing a sort value (two + * opportunities with the same `funding.maxAwardAmount`, say) keep their + * incoming order under a stable sort, so `desc` would not be the exact reverse + * of `asc`. Negating the composed comparator — tiebreaker included — is what + * makes the two directions mirror each other exactly. + */ +function orderBy(items: Opportunity[], sortBy: string, sortOrder: string): Opportunity[] { + return [...items].sort((a, b) => { + const result = compare(sortKey(a, sortBy), sortKey(b, sortBy)) || compare(a.id, b.id); + return sortOrder === "asc" ? result : -result; + }); +} + +/** A resolved pagination pair, or the validation errors that blocked it. */ +type PaginationResult = + | { ok: true; page: number; pageSize: number } + | { ok: false; errors: FieldError[] }; + +/** + * Resolves one pagination param against the spec + * (`Pagination.PaginatedQueryParams` / `PaginatedBodyParams`): an optional + * `integer` with `minimum: 1`, defaulting to 1 (`page`) / 100 (`pageSize`), and + * **no** declared maximum. + * + * An absent value takes the default. A present value that isn't an integer, or + * that falls below the minimum, is a validation error rather than something to + * silently clamp — clamping would answer a request the caller didn't make, and + * surfacing it as a 400 gives the playground another error case to demonstrate. + * + * @param raw - The value as received: a query string, a JSON body value, or + * `undefined`/`""` when the caller omitted it. + * @param field - Dotted path used in the `{field, message}` error entry. + * @param fallback - The spec default for this param. + */ +function resolvePaginationParam( + raw: string | number | undefined, + field: string, + fallback: number, + errors: FieldError[] +): number { + if (raw === undefined || raw === "") return fallback; + + const value = typeof raw === "number" ? raw : Number(raw); + if (!Number.isInteger(value)) { + errors.push({ field, message: `Must be an integer, received: ${raw}` }); + return fallback; + } + if (value < MIN_PAGE_VALUE) { + errors.push({ field, message: `Must be at least ${MIN_PAGE_VALUE}` }); + return fallback; + } + return value; +} + +/** Resolves both pagination params, collecting every validation error at once. */ +function resolvePagination( + rawPage: string | number | undefined, + rawPageSize: string | number | undefined, + fieldPrefix = "" +): PaginationResult { + const errors: FieldError[] = []; + const page = resolvePaginationParam(rawPage, `${fieldPrefix}page`, DEFAULT_PAGE, errors); + const pageSize = resolvePaginationParam( + rawPageSize, + `${fieldPrefix}pageSize`, + DEFAULT_PAGE_SIZE, + errors + ); + + return errors.length > 0 ? { ok: false, errors } : { ok: true, page, pageSize }; +} + +/** + * UUID-shaped value (8-4-4-4-12 hex, matching the protocol's `uuid` format). + * Not a full RFC 4122 conformance check — it deliberately accepts the nil + * UUID (`00000000-…`), used as this suite's "well-formed but unknown" case. + */ +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** + * Builds `Pagination.PaginatedResultsInfo`. Shared by the list and search + * endpoints so `totalPages` is derived the same way on both — an empty result + * set reports zero pages, not one. + */ +function paginationInfo(page: number, pageSize: number, totalItems: number) { + return { + page, + pageSize, + totalItems, + totalPages: Math.ceil(totalItems / pageSize), + }; +} + +/** + * `GET /v{version}/common-grants/opportunities` — the paginated list, ordered + * newest-modified first. + * + * @param request - Carries the `page`/`pageSize` query params. + * @param version - Protocol version to shape responses for (v0.1 omits + * `acceptedApplicantTypes`; `competitions` is detail-only, so never present here). + */ +export function listOpportunities(request: Request, version: Version): Response { + const url = new URL(request.url); + const pagination = resolvePagination( + url.searchParams.get("page") ?? undefined, + url.searchParams.get("pageSize") ?? undefined + ); + if (!pagination.ok) { + return errorResponse(400, "Invalid pagination parameters", pagination.errors); + } + const { page, pageSize } = pagination; + + const sorted = orderBy(allForVersion(version), "lastModifiedAt", "desc"); + const start = (page - 1) * pageSize; + const items = sorted.slice(start, start + pageSize); + + return successResponse({ + items, + paginationInfo: paginationInfo(page, pageSize, sorted.length), + }); +} + +/** + * `GET /v{version}/common-grants/opportunities/{oppId}` — a single record. + * + * @param oppId - The path segment as received; validated as UUID-shaped here + * rather than in the router, so a malformed id answers 400 (not a route miss). + * @param version - Protocol version to shape the response for (v0.1 returns the + * `OpportunityBase` shape rather than `OpportunityDetails`). + */ +export function getOpportunity(oppId: string, version: Version): Response { + if (!UUID_PATTERN.test(oppId)) { + return errorResponse(400, "Invalid opportunity id", [ + { field: "oppId", message: "Must be a valid UUID" }, + ]); + } + + const opp = getById(oppId); + if (!opp) { + return errorResponse(404, "Opportunity not found", [ + { field: "oppId", message: `No opportunity found with id ${oppId}` }, + ]); + } + + return successResponse({ + data: shapeOpportunityForVersion(opp, version, "detail"), + }); +} + +/** + * `POST /v{version}/common-grants/opportunities/search` — filtered, sorted, + * paginated search over the same fixture set. + * + * @param request - Carries the `OppSearchRequest` JSON body. + * @param version - Protocol version to shape the returned items for. + */ +export async function searchOpportunities(request: Request, version: Version): Promise { + let parsed: unknown; + try { + parsed = await request.json(); + } catch { + return errorResponse(400, "Malformed JSON body", [ + { field: "body", message: "Request body must be valid JSON" }, + ]); + } + + // `JSON.parse` accepts any JSON *value*, so `null`, `[]`, `42`, and a bare + // quoted string all clear the parse above and then pose as an + // `OppSearchRequest`. The spike cast straight to `SearchRequestBody` and read + // `.filters`, which crashed on `null`/strings and — worse — quietly answered + // 200 with the whole unfiltered set for `[]`/`42`/`true`, since those have no + // `.filters` to find. Rejecting non-objects here is the only way the caller + // learns the body was wrong. (This is the one deliberate behavior change from + // the #1049 port; every input that produced an envelope there still produces + // the same envelope.) + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + return errorResponse(400, "Malformed JSON body", [ + { field: "body", message: "Request body must be a JSON object" }, + ]); + } + const body = parsed as SearchRequestBody; + + const errors: FieldError[] = []; + const filters = body.filters ?? {}; + const sorting = body.sorting; + + if (sorting) { + if (!VALID_SORT_BY.has(sorting.sortBy)) { + errors.push({ + field: "sorting.sortBy", + message: `Unknown sort field: ${String(sorting.sortBy)}`, + }); + } + if (sorting.sortOrder !== undefined && !VALID_SORT_ORDER.has(sorting.sortOrder)) { + errors.push({ + field: "sorting.sortOrder", + message: `Unknown sort order: ${String(sorting.sortOrder)}`, + }); + } + } + if (filters.status) { + if (!VALID_ARRAY_OPERATORS.has(filters.status.operator)) { + errors.push({ + field: "filters.status.operator", + message: `Unknown array operator: ${String(filters.status.operator)}`, + }); + } else if (!Array.isArray(filters.status.value)) { + errors.push({ + field: "filters.status.value", + message: "Must be an array of strings", + }); + } + } + for (const field of ["closeDateRange", ...MONEY_RANGE_FIELDS] as const) { + const filter = filters[field]; + if (!filter) continue; + if (!VALID_RANGE_OPERATORS.has(filter.operator)) { + errors.push({ + field: `filters.${field}.operator`, + message: `Unknown range operator: ${String(filter.operator)}`, + }); + continue; + } + if ( + !filter.value || + typeof filter.value !== "object" || + (filter.value.min === undefined && filter.value.max === undefined) + ) { + errors.push({ + field: `filters.${field}.value`, + message: "Must include at least one of min or max", + }); + continue; + } + // Validate the bounds themselves, not just their presence. An + // malformed bound used to be silently dropped, which returned a + // result set that contradicted the filter the caller asked for. + const isDateRange = field === "closeDateRange"; + for (const bound of ["min", "max"] as const) { + const value = filter.value[bound]; + if (value === undefined) continue; + if (isDateRange ? dateTime(value) === undefined : !isMoney(value)) { + errors.push({ + field: `filters.${field}.value.${bound}`, + message: isDateRange + ? `Must be a valid ISO 8601 date, received: ${JSON.stringify(value)}` + : `Must be a Money object with a numeric amount and a currency, received: ${JSON.stringify(value)}`, + }); + } + } + } + + const pagination = resolvePagination( + body.pagination?.page, + body.pagination?.pageSize, + "pagination." + ); + if (!pagination.ok) { + errors.push(...pagination.errors); + } + // The defaults here are unreachable: an invalid pagination pair pushed + // errors above, and the guard below returns before they are used. + const { page, pageSize } = pagination.ok + ? pagination + : { page: DEFAULT_PAGE, pageSize: DEFAULT_PAGE_SIZE }; + + if (errors.length > 0) { + return errorResponse(400, "Invalid search request", errors); + } + + let items = allForVersion(version); + + if (body.search) { + const q = body.search.toLowerCase(); + items = items.filter( + opp => opp.title.toLowerCase().includes(q) || opp.description.toLowerCase().includes(q) + ); + } + if (filters.status) { + items = applyStatusFilter(items, filters.status); + } + if (filters.closeDateRange) { + items = applyDateRangeFilter(items, filters.closeDateRange, opp => + dateTime(opp.keyDates?.closeDate?.date) + ); + } + if (filters.totalFundingAvailableRange) { + items = applyMoneyRangeFilter( + items, + filters.totalFundingAvailableRange, + opp => opp.funding?.totalAmountAvailable + ); + } + if (filters.minAwardAmountRange) { + items = applyMoneyRangeFilter( + items, + filters.minAwardAmountRange, + opp => opp.funding?.minAwardAmount + ); + } + if (filters.maxAwardAmountRange) { + items = applyMoneyRangeFilter( + items, + filters.maxAwardAmountRange, + opp => opp.funding?.maxAwardAmount + ); + } + + const sortBy = sorting?.sortBy ?? "lastModifiedAt"; + const sortOrder = sorting?.sortOrder ?? "desc"; + const sortErrors: string[] = []; + if (sortBy === "custom") { + sortErrors.push( + sorting?.customSortBy + ? `Custom sort field "${sorting.customSortBy}" is not supported by this mock; results are unsorted for it.` + : "Custom sort requested without customSortBy; results are unsorted." + ); + } else { + items = orderBy(items, sortBy, sortOrder); + } + + // `filterInfo.errors` is the spec's channel for "non-fatal errors that + // occurred during filtering". `customFilters` are implementation-defined, + // so this mock echoes them but can't apply them — say so rather than + // letting the echo imply they narrowed the results. + const filterErrors: string[] = []; + const customFilterNames = Object.keys(filters.customFilters ?? {}); + if (customFilterNames.length > 0) { + filterErrors.push( + `Custom filters are not supported by this mock and were not applied: ${customFilterNames.join(", ")}.` + ); + } + + const start = (page - 1) * pageSize; + const pageItems = items.slice(start, start + pageSize); + + return successResponse({ + items: pageItems, + paginationInfo: paginationInfo(page, pageSize, items.length), + sortInfo: { + sortBy, + ...(sorting?.customSortBy !== undefined ? { customSortBy: sorting.customSortBy } : {}), + sortOrder, + ...(sortErrors.length > 0 ? { errors: sortErrors } : {}), + }, + filterInfo: { + filters, + ...(filterErrors.length > 0 ? { errors: filterErrors } : {}), + }, + }); +} diff --git a/mock-api/src/http/cors.ts b/mock-api/src/http/cors.ts new file mode 100644 index 000000000..a5d2f5d0b --- /dev/null +++ b/mock-api/src/http/cors.ts @@ -0,0 +1,55 @@ +/** + * Cross-origin access for the mock Worker. + * + * The whole point of the standalone-Worker experiment is that the docs site + * ("Try it out" on `commongrants.org`), a copied `curl`, and the TS SDK all hit + * one real URL — and the first two of those are cross-origin browser requests. + * So CORS is applied once, wrapping the router, rather than per handler: a + * response that skipped these headers would be invisible to the browser + * regardless of its status code, and errors are exactly the responses a + * playground visitor most needs to see. + * + * `Access-Control-Allow-Origin: *` is correct here because the mock serves + * public, deterministic fixture data and holds no credentials or session state. + * A productionized mock with per-key rate limits would need an origin allowlist + * instead — noted in the findings write-up (#1077-T7). + */ + +/** + * `X-API-Key` and `Authorization` are listed because the TS SDK sends one or + * the other whenever auth is configured (`Auth.apiKey()` / bearer). Both are + * non-simple request headers, so a browser refuses the request unless the + * preflight names them explicitly — even though this mock ignores their values. + */ +const CORS_HEADERS: Record = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, POST, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type, X-API-Key, Authorization", + "Access-Control-Max-Age": "86400", +}; + +/** + * Answers an `OPTIONS` preflight for any path, matched or not. + * + * Deliberately blanket: a preflight is a question about the *policy* for a + * method/header pair, not about whether the resource exists, and answering 404 + * to it makes a browser report an opaque CORS failure instead of the + * protocol-shaped 404 the real request would have returned. + */ +export function preflightResponse(): Response { + return new Response(null, { status: 204, headers: CORS_HEADERS }); +} + +/** Returns `response` with the CORS headers added, leaving status and body untouched. */ +export function withCors(response: Response): Response { + const headers = new Headers(response.headers); + for (const [name, value] of Object.entries(CORS_HEADERS)) { + headers.set(name, value); + } + + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); +} diff --git a/mock-api/src/http/envelope.ts b/mock-api/src/http/envelope.ts new file mode 100644 index 000000000..21070eb63 --- /dev/null +++ b/mock-api/src/http/envelope.ts @@ -0,0 +1,49 @@ +/** + * Protocol response envelopes, shared by the router and the opportunity + * handlers so a version-prefix 404 and a handler-level 404 are the same shape + * on the wire. + * + * Ported from the #1049 spike's `handlers.ts`, with MSW's `HttpResponse.json` + * swapped for the platform `Response.json` — the only behavioral difference is + * the constructor; both emit `application/json` with the given status. + */ + +/** A single `{field, message}` validation error carried in the `errors` array. */ +export interface FieldError { + field: string; + message: string; +} + +/** Builds the protocol `Error` envelope (`status`, `message`, `errors`). */ +export function errorResponse(status: number, message: string, errors: unknown[]): Response { + return Response.json({ status, message, errors }, { status }); +} + +/** Builds the protocol success envelope (`status: 200`, `message`, plus the endpoint-specific body). */ +export function successResponse(body: Record): Response { + return Response.json({ status: 200, message: "Success", ...body }); +} + +/** + * Runs `handle`, converting an unexpected throw into a protocol-shaped 500. + * + * Under MSW the same throw surfaced as a test-time unhandled rejection. On a + * real cross-origin Worker it costs the caller much more: no response object + * means no CORS headers, so the browser reports an opaque CORS failure and the + * actual cause never reaches the console. Returning an envelope keeps every + * outcome on the path that `withCors` decorates. + * + * No reachable throw is known today — the search handler validates its body + * rather than trusting it — so this is a backstop for later changes, not a live + * code path. + */ +export async function withErrorBoundary(handle: () => Promise): Promise { + try { + return await handle(); + } catch (cause) { + console.error("Unhandled error while routing request", cause); + return errorResponse(500, "Internal error", [ + { field: "server", message: "The mock failed to handle this request" }, + ]); + } +} diff --git a/mock-api/src/index.ts b/mock-api/src/index.ts new file mode 100644 index 000000000..218373f11 --- /dev/null +++ b/mock-api/src/index.ts @@ -0,0 +1,102 @@ +/** + * Standalone Cloudflare Worker serving deterministic CommonGrants mock data. + * + * Routing replaces MSW's handler registration from the #1049 spike: instead of + * `http.get(path, resolver)` matching inside a service worker, `route()` below + * matches `url.pathname` itself and hands off to the ported handlers in + * `src/handlers/opportunities.ts` (#1077-T3). + * + * Only the opportunity endpoints are served. Every other spec path answers a + * protocol-shaped 404 — an accepted limit of the experiment, and a data point + * for how much of the spec a production mock would have to cover. + */ + +import { SUPPORTED_VERSIONS, isSupportedVersion } from "./data/fixtures"; +import { getOpportunity, listOpportunities, searchOpportunities } from "./handlers/opportunities"; +import { preflightResponse, withCors } from "./http/cors"; +import { errorResponse, withErrorBoundary } from "./http/envelope"; + +const SERVICE_NAME = "@common-grants/mock-api"; + +/** + * `/v{version}/common-grants/opportunities` with an optional trailing segment: + * an `oppId` on GET, the literal `search` on POST. + * + * The protocol version rides in the path rather than a header or query param so + * that an SDK `baseUrl` of `https://.workers.dev/v0.4.0` works unchanged + * (`Client.url()` concatenates base + path), and each rendered spec file can + * carry a version-correct `servers:` URL (#1077-T6). + * + * `version` is captured loosely (`[^/]+`) and narrowed by `isSupportedVersion`, + * so `/vabc/...` and `/v9.9.9/...` both reach the same "unsupported version" + * answer instead of falling through to a bare route miss. + */ +const OPPORTUNITIES_ROUTE = /^\/v([^/]+)\/common-grants\/opportunities(?:\/([^/]+))?$/; + +function healthResponse(): Response { + return Response.json({ + name: SERVICE_NAME, + supportedVersions: SUPPORTED_VERSIONS, + }); +} + +async function route(request: Request): Promise { + const { pathname } = new URL(request.url); + + if (pathname === "/") { + return healthResponse(); + } + + const match = OPPORTUNITIES_ROUTE.exec(pathname); + if (!match) { + return errorResponse(404, "Not found", [ + { + field: "path", + message: `This mock serves the opportunity endpoints only; no route matches ${request.method} ${pathname}`, + }, + ]); + } + + const [, version, segment] = match; + if (!isSupportedVersion(version)) { + return errorResponse(404, "Unsupported protocol version", [ + { + field: "version", + message: `Version ${version} is not served by this mock; supported versions are ${SUPPORTED_VERSIONS.join(", ")}`, + }, + ]); + } + + // `GET .../opportunities/search` deliberately falls through to the detail + // handler, which answers 400 "Must be a valid UUID" — the same answer the + // spike's `:oppId` pattern gave, since only POST registered on `/search`. + if (request.method === "GET") { + return segment === undefined + ? listOpportunities(request, version) + : getOpportunity(segment, version); + } + if (request.method === "POST" && segment === "search") { + return searchOpportunities(request, version); + } + + return errorResponse(404, "Not found", [ + { + field: "path", + message: `No route matches ${request.method} ${pathname}`, + }, + ]); +} + +export default { + async fetch(request: Request): Promise { + if (request.method === "OPTIONS") { + return preflightResponse(); + } + + // Single choke point for everything `route()` can produce — success, + // validation error, route miss — plus, via the error boundary, anything it + // throws. Preflights are the one path that skips it, and + // `preflightResponse()` sets the same headers itself. + return withCors(await withErrorBoundary(() => route(request))); + }, +} satisfies ExportedHandler; diff --git a/mock-api/tsconfig.json b/mock-api/tsconfig.json new file mode 100644 index 000000000..fd4e70502 --- /dev/null +++ b/mock-api/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022"], + // The Worker runtime, not Node — `wrangler` bundles `src/index.ts` itself, + // so nothing here is emitted (see the `build` script's `--dry-run`). + "types": ["@cloudflare/workers-types"], + "noEmit": true, + "isolatedModules": true, + "strict": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + }, + // `src/` only. The tests live in `tsconfig.test.json`, which adds Node's types. + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/mock-api/tsconfig.test.json b/mock-api/tsconfig.test.json new file mode 100644 index 000000000..06655fc35 --- /dev/null +++ b/mock-api/tsconfig.test.json @@ -0,0 +1,11 @@ +{ + // Tests run under Node (vitest), not workerd, so they get Node's types on top + // of the Worker globals. Kept separate from `tsconfig.json` so `src/` stays + // typechecked against the Worker runtime alone — a stray `process`/`fs` in the + // Worker entrypoint is a build error there, not something Node's types excuse. + "extends": "./tsconfig.json", + "compilerOptions": { + "types": ["@cloudflare/workers-types", "node"] + }, + "include": ["src/**/*", "__tests__/**/*", "vitest.config.ts"] +} diff --git a/mock-api/vitest.config.ts b/mock-api/vitest.config.ts new file mode 100644 index 000000000..42370a191 --- /dev/null +++ b/mock-api/vitest.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + // Node, not `@cloudflare/vitest-pool-workers`: the handler is a pure + // `fetch(Request) => Response` over standard Fetch API globals, so Node 22 + // reproduces it faithfully and the suite stays dependency-free. If a later + // ticket reaches for Workers-only semantics (env bindings, `ctx.waitUntil`, + // `request.cf`), Node's globals won't cover them and this needs revisiting. + environment: "node", + exclude: ["dist/**", "node_modules/**"], + isolate: false, + }, +}); diff --git a/mock-api/wrangler.jsonc b/mock-api/wrangler.jsonc new file mode 100644 index 000000000..f82c1f84a --- /dev/null +++ b/mock-api/wrangler.jsonc @@ -0,0 +1,14 @@ +{ + // Standalone from the docs-site Worker (`common-grants` in website/wrangler.jsonc, + // which is assets-only): this one has a real script entrypoint. + "name": "cg-mock-api", + "main": "src/index.ts", + "compatibility_date": "2026-08-01", + // Explicit because the `*.workers.dev` URL *is* the experiment's deliverable + // (#1077-T5): it's the one origin the docs "Try it out", a copied curl, and the + // TS SDK all hit. Default-on today, but not something to leave implicit. + "workers_dev": true, + "observability": { + "enabled": true, + }, +} diff --git a/package.json b/package.json index 4fb29e947..b21bf0a1d 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,9 @@ "ci:changelog-emitter": "pnpm --filter typespec-versioning-changelog run ci", "ci:cli": "pnpm --filter @common-grants/cli run ci", "ci:sdk": "pnpm --filter @common-grants/sdk run ci", + "ci:mock-api": "pnpm --filter @common-grants/mock-api run ci", "ci:website": "pnpm --filter website run ci", - "ci": "pnpm run ci:core && pnpm run ci:changelog-emitter && pnpm run ci:cli && pnpm run ci:sdk && pnpm run ci:website" + "ci": "pnpm run ci:core && pnpm run ci:changelog-emitter && pnpm run ci:cli && pnpm run ci:sdk && pnpm run ci:mock-api && pnpm run ci:website" }, "keywords": [], "author": "", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 770e01fcd..3a2456d37 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -391,6 +391,60 @@ importers: specifier: 'catalog:' version: 4.1.9(@types/node@22.20.0)(@vitest/coverage-v8@4.1.9)(vite@8.1.5(@types/node@22.20.0)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.8.3)) + mock-api: + devDependencies: + '@cloudflare/workers-types': + specifier: ^5.20260810.1 + version: 5.20260810.1 + '@eslint/js': + specifier: 'catalog:' + version: 10.0.1(eslint@10.5.0(supports-color@10.2.2)) + '@types/js-yaml': + specifier: ^4.0.9 + version: 4.0.9 + '@types/node': + specifier: 'catalog:' + version: 22.20.0 + '@vitest/coverage-v8': + specifier: 'catalog:' + version: 4.1.9(vitest@4.1.9) + '@vitest/eslint-plugin': + specifier: 'catalog:' + version: 1.6.20(@typescript-eslint/eslint-plugin@8.61.1(@typescript-eslint/parser@8.61.1(eslint@10.5.0(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(eslint@10.5.0(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3))(eslint@10.5.0(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3)(vitest@4.1.9) + ajv: + specifier: ^8.20.0 + version: 8.20.0 + ajv-formats: + specifier: ^3.0.1 + version: 3.0.1(ajv@8.20.0) + eslint: + specifier: 'catalog:' + version: 10.5.0(supports-color@10.2.2) + eslint-config-prettier: + specifier: 'catalog:' + version: 10.1.8(eslint@10.5.0(supports-color@10.2.2)) + eslint-plugin-prettier: + specifier: 'catalog:' + version: 5.5.6(eslint-config-prettier@10.1.8(eslint@10.5.0(supports-color@10.2.2)))(eslint@10.5.0(supports-color@10.2.2))(prettier@3.8.4) + js-yaml: + specifier: ^4.3.1 + version: 4.3.1 + prettier: + specifier: 'catalog:' + version: 3.8.4 + typescript: + specifier: 'catalog:' + version: 6.0.3 + typescript-eslint: + specifier: 'catalog:' + version: 8.61.1(eslint@10.5.0(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) + vitest: + specifier: 'catalog:' + version: 4.1.9(@types/node@22.20.0)(@vitest/coverage-v8@4.1.9)(vite@8.1.5(@types/node@22.20.0)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.8.3)) + wrangler: + specifier: ^4.117.0 + version: 4.117.0(@cloudflare/workers-types@5.20260810.1) + website: dependencies: '@apidevtools/json-schema-ref-parser': @@ -531,7 +585,7 @@ importers: version: 4.1.9(@types/node@22.20.0)(@vitest/coverage-v8@4.1.9)(vite@8.1.5(@types/node@22.20.0)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.8.3)) wrangler: specifier: ^4.117.0 - version: 4.117.0 + version: 4.117.0(@cloudflare/workers-types@5.20260810.1) packages: @@ -953,6 +1007,9 @@ packages: cpu: [x64] os: [win32] + '@cloudflare/workers-types@5.20260810.1': + resolution: {integrity: sha512-aD0hEU6HaiG4wy4hDoPoLXMH963nHD4MsIY566pGkWO2dL/yeYEiMN7SeJ24t+wBmLDnh16yQ7IPos5opGkIoA==} + '@common-grants/cg-grants-gov@0.2.0': resolution: {integrity: sha512-BOMJ1PqKJdZm6M41Nsreou3SxKJ17R4owGP7HlrUc07NIVvM3Z7ZAVqtHIph8ruFp0oeRDY6hS0WbdYgV8fDrw==} peerDependencies: @@ -2844,9 +2901,6 @@ packages: ajv@6.14.0: resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} - ajv@8.18.0: - resolution: {integrity: sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==} - ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} @@ -5958,8 +6012,8 @@ snapshots: '@apidevtools/openapi-schemas': 2.1.0 '@apidevtools/swagger-methods': 3.0.2 '@jsdevtools/ono': 7.1.3 - ajv: 8.18.0 - ajv-draft-04: 1.0.0(ajv@8.18.0) + ajv: 8.20.0 + ajv-draft-04: 1.0.0(ajv@8.20.0) call-me-maybe: 1.0.2 openapi-types: 12.1.3 @@ -6550,6 +6604,8 @@ snapshots: '@cloudflare/workerd-windows-64@1.20260730.1': optional: true + '@cloudflare/workers-types@5.20260810.1': {} + '@common-grants/cg-grants-gov@0.2.0(@common-grants/sdk@0.5.0)': dependencies: '@common-grants/sdk': 0.5.0 @@ -8234,10 +8290,6 @@ snapshots: acorn@8.16.0: {} - ajv-draft-04@1.0.0(ajv@8.18.0): - optionalDependencies: - ajv: 8.18.0 - ajv-draft-04@1.0.0(ajv@8.20.0): optionalDependencies: ajv: 8.20.0 @@ -8257,13 +8309,6 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 - ajv@8.18.0: - dependencies: - fast-deep-equal: 3.1.3 - fast-uri: 3.1.5 - json-schema-traverse: 1.0.0 - require-from-string: 2.0.2 - ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 @@ -11836,7 +11881,7 @@ snapshots: '@cloudflare/workerd-linux-arm64': 1.20260730.1 '@cloudflare/workerd-windows-64': 1.20260730.1 - wrangler@4.117.0: + wrangler@4.117.0(@cloudflare/workers-types@5.20260810.1): dependencies: '@cloudflare/kv-asset-handler': 0.5.0 '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260730.1) @@ -11847,6 +11892,7 @@ snapshots: unenv: 2.0.0-rc.24 workerd: 1.20260730.1 optionalDependencies: + '@cloudflare/workers-types': 5.20260810.1 fsevents: 2.3.3 transitivePeerDependencies: - bufferutil diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 1dbfad2ff..55c20aef5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,6 +4,7 @@ packages: - lib/python-sdk - lib/changelog-emitter - lib/ts-sdk + - mock-api - website allowBuilds: