Files
sim/scripts/openapi/docs-redirects.test.ts
T
Waleed 47f143016e fix(docs): restore api-reference URL continuity and fix translated SDK bodies (#6617)
Two docs-only defects introduced by #5273 (`263e3ca67e`), which re-founded the
public API reference on the v2 surface.

1. Ten translated SDK snippets produce a deterministic 400.

The streaming example in the five translated `api-reference/typescript.mdx` and
`python.mdx` pages was repointed from `/api/workflows/{id}/execute` to
`/api/v2/workflows/{id}/execute` and nothing else was changed — fr/ja/zh
typescript.mdx are literally one-line diffs. `message` stayed at the body root.
That was correct against v1, whose route treats the whole non-control body as
workflow input, but `v2ExecuteWorkflowBodySchema` ends in `.strict()` and the
route parses before executing, so every copied snippet returns
`400 Unrecognized key: "message"`. The same commit fixed the English bodies to
`input: { … }`, so this is an oversight, not a decision. The ten fences now
match `en/api-reference/typescript.mdx:959` and `python.mdx:681`.

Not relaxing `.strict()`: it is deliberate house style across the v2 contract
and is what makes a typo'd option fail loudly instead of silently.

2. Thirty-two published operation pages 404 with no redirect.

Replacing the single v1 `openapi.json` with seven v2-only specs changes page
identity, because fumadocs derives every generated page as
`slugify(tag)/operationId` from the specs at build time. Re-deriving both sets
gives 52 old slugs and 128 new ones: 32 disappear and 20 keep their URL while
silently retargeting v1 -> v2 (`knowledge-bases/updateKnowledgeBase` also flips
PUT -> PATCH). All 52 are in the live sitemap — parsing `<loc>` from
docs.sim.ai/sitemap.xml gives 458 URLs of which 56 are `/api-reference/`: the
four static pages plus all 52 generated ones by name, including every one of
the 32 that die. They are 200 today under an allow-all robots.txt.

The spec swap itself is deliberate and CI-enforced (`check-openapi-specs.ts`
requires every published operation under `/api/v2/`), so restoring the v1
operations is not an option. The missing piece is the redirect map, in a file
that already carried 56 such rules from earlier doc moves.

`permanent: true` (308) is used only for a true 1:1 successor — same operation,
renamed. A 308 is cached indefinitely and effectively unrecallable, so anything
that collapses two pages onto one, changes the identifier model, or lands on a
merely adjacent operation is `permanent: false` (307). That splits 21/11.

Four destinations differ from the mapping proposed in review, each on evidence
from the specs rather than from the operation names:

- `workflows/getJobStatus` is not destination-less. The v2 queued-execution
  receipt (`QueuedWorkflowRun`) returns `statusUrl`
  `/api/v2/workflows/{id}/runs/{runId}`, so `workflow-runs/getWorkflowRunV2` is
  the successor poll target — far better than a generic landing page.
- The three HITL read operations go to `getWorkflowRunV2`, not to the resume
  page: `WorkflowRunStatus` carries a `paused` object with `contextId`,
  `pausedAt`, and `pauseKind`. Pointing a GET doc at a POST doc would be wrong.
- `human-in-the-loop/listPausedExecutions` goes to `listWorkflowRunsV2`, whose
  `status` filter includes `paused`.
- `tables/batchUpdateRows` is 307, not 308. v2 `updateTableRows` is "Update Rows
  by Filter" — the successor of v1 `updateRows` (PUT, predicate-based), which
  keeps its 308. v2 has no by-id batch update at all, so batchUpdateRows lands
  on a genuinely different operation.

3. A guard, so the map cannot rot silently.

`scripts/openapi/docs-redirects.test.ts` recomputes the generated slug set the
way fumadocs does and asserts no `/api-reference/` source shadows a live page
and every destination resolves. Nothing else in the repo reads docs URLs, so a
future spec regeneration would otherwise break the map with no signal. It needs
no wiring: `check-openapi.ts` already runs this vitest config.

The redirect array moves to `apps/docs/lib/redirects.ts` because the guard
cannot import `next.config.ts` — `createMDX()` runs the fumadocs-mdx generator
at import time, which made vitest emit an unhandled build error and warn about
false positives. The 56 pre-existing rules are byte-identical to before,
verified programmatically; `next.config.ts` keeps the same public shape and
Next's own `checkCustomRoutes` accepts all 88 rules.

Open question for the owner, larger than the redirects: all 82 `/api/v1`
route files survive on staging, so a live public API now ships with zero
reference docs, while the documented `/api/v2` surface returns 404 for any
caller outside the off-by-default `v2-api` flag cohort. Is that the intended
end state or transitional?
2026-08-12 01:49:59 -07:00

109 lines
4.2 KiB
TypeScript

/**
* Pins the `/api-reference/` rules in `apps/docs/lib/redirects.ts` against the
* generated operation pages.
*
* Page identity is derived from the specs at build time, so a spec regeneration
* can silently invalidate the map in two directions: a redirect `source` can
* start shadowing a page that now exists (the redirect wins and hides it), and a
* `destination` can stop resolving (the redirect lands on a 404). Neither shows
* up in a build, a type-check, or any other check — nothing else in the repo
* reads docs URLs.
*
* Both directions use the same slug set, so a rule cannot shadow a hand-authored
* page (`/api-reference/getting-started`) any more than a generated one.
*
* The slug derivation mirrors `fumadocs-openapi`'s auto preset: pages are
* emitted at `<baseDir>/<slugify(tag)>/<operationId>.mdx`, `(generated)` is a
* folder group stripped from the URL, and `hideLocale: 'default-locale'` drops
* the `en` prefix — so the public URL is `/api-reference/<tag>/<operationId>`.
*/
import { readdirSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { OPENAPI_SPEC_FILES } from '../../apps/docs/lib/openapi-specs'
import { DOCS_REDIRECTS } from '../../apps/docs/lib/redirects'
const ROOT = path.resolve(import.meta.dirname, '../..')
const DOCS_DIR = path.join(ROOT, 'apps/docs')
const STATIC_PAGES_DIR = path.join(DOCS_DIR, 'content/docs/en/api-reference')
const PREFIX = '/api-reference/'
/**
* `fumadocs-openapi`'s `methodKeys`, which is what decides whether an operation
* becomes a page. It is deliberately narrower than the OpenAPI method set —
* `options` and `trace` are not enumerated, so an operation declared under
* either produces no page and must not count as a resolvable destination here.
*/
const HTTP_METHODS = ['get', 'post', 'patch', 'delete', 'head', 'put'] as const
interface OperationObject {
operationId?: string
tags?: string[]
}
/** `fumadocs-openapi`'s default `slugify` for tag folder names. */
function slugify(value: string): string {
return value.replace(/\s+/g, '-').toLowerCase()
}
function generatedSlugs(): Set<string> {
const slugs = new Set<string>()
for (const file of OPENAPI_SPEC_FILES) {
const spec = JSON.parse(readFileSync(path.join(DOCS_DIR, file), 'utf8')) as {
paths?: Record<string, Record<string, OperationObject | undefined>>
}
for (const pathItem of Object.values(spec.paths ?? {})) {
for (const method of HTTP_METHODS) {
const operation = pathItem[method]
if (!operation?.operationId) continue
const tags = operation.tags?.length ? operation.tags : ['unknown']
for (const tag of tags) {
slugs.add(`${slugify(tag)}/${operation.operationId}`)
}
}
}
}
return slugs
}
/** Every slug a `/api-reference/` URL can resolve to: generated plus hand-authored. */
function resolvableSlugs(): Set<string> {
const slugs = generatedSlugs()
for (const entry of readdirSync(STATIC_PAGES_DIR)) {
if (entry.endsWith('.mdx')) slugs.add(path.basename(entry, '.mdx'))
}
return slugs
}
const API_REFERENCE_RULES = DOCS_REDIRECTS.filter(
(rule) => rule.source.startsWith(PREFIX) || rule.destination.startsWith(PREFIX)
)
describe('api-reference redirects', () => {
it('is a non-empty set of literal paths', () => {
expect(API_REFERENCE_RULES.length).toBeGreaterThan(0)
for (const rule of API_REFERENCE_RULES) {
expect(
`${rule.source} -> ${rule.destination}`,
'path params would make the slug checks below vacuous'
).not.toMatch(/[:*]/)
}
})
it('never shadows a page that exists', () => {
const resolvable = resolvableSlugs()
const shadowed = API_REFERENCE_RULES.map((rule) => rule.source)
.filter((source) => source.startsWith(PREFIX))
.filter((source) => resolvable.has(source.slice(PREFIX.length)))
expect(shadowed).toEqual([])
})
it('only points at pages that exist', () => {
const resolvable = resolvableSlugs()
const broken = API_REFERENCE_RULES.map((rule) => rule.destination)
.filter((destination) => destination.startsWith(PREFIX))
.filter((destination) => !resolvable.has(destination.slice(PREFIX.length)))
expect(broken).toEqual([])
})
})