# RapiDoc Utilities

## Overview

Framework-free helpers behind the `<rapi-doc>` component (`src/rapidoc.ts`), its templates and
the static renderer (`@rapidoc/prerender`, `packages/rapidoc-prerender`). `utils/` owns the spec pipeline (load,
dereference, group, anchor), schema rendering and example generation, request/response/mock
helpers, and UI helpers (highlighting, Markdown, sanitizing, navbar binding, color, OAuth). It
does not own rendering (`templates/`, `components/`) or styles. The MCP manifest, runtime and
project writer are documented in [`./mcp/README.md`](./mcp/README.md); Arazzo parsing and workflow diagrams in
[`./arazzo/README.md`](./arazzo/README.md).

Everything except `arazzo/` is bundled into `dist/rapidoc-min.js`; `arazzo/` goes into
`dist/rapidoc-flow-min.js` and `@rapidoc/prerender`. `@rapidoc/portal` depends on this folder
indirectly through `@rapidoc/prerender` (`methodPathSlug`, `operationAnchorSource`, `toKebabCase`)
and the anchors `<rapi-doc>` emits, so anchor generation is public behavior.
Several modules run in Node (static renderer, unit tests) and must guard `window`/`document`.

## Interface

Spec pipeline:

- `spec-parser.js`: default `ProcessSpec` (spec URL, text or object to the render model of
  tags, tag groups, components, security schemes, servers); `isTagExpanded`, `groupByTagGroups`,
  `groupByParentTags`, `normalizeExampleObjects`.
- `spec-loader.js`: `createBrowserFetchPlugin` (the fetch plugin for the parser's `load()`),
  `breakCircularRefs`, `isUrlLike`, `pageUrl`. No imports but `yaml`; `spec-parser.js` uses it, and
  `rapipdf` (`packages/rapipdf`) bundles it by relative path, with `schema-utils.js`.
- `slugger.js`: `OperationSlugger` (`slug`, `slugOp`, `slugTag`, `slugTagGroup`, `reset`),
  `operationAnchorSource`, `methodPathSlug`, `toKebabCase`, `clampWordBoundary`, `createSlugger`.
- `common-utils.js`: search (`advancedSearch`, `getMatchedPaths`), `debounce`, `sleep`,
  clipboard and download helpers, `rapidocApiKey`.

Schema rendering:

- `schema-utils.js`: `getTypeInfo`, `typeLabel` (the type label every parameter and schema row
  shows), `schemaToAST` (schema tree for renderers),
  `schemaInObjectNotation` (older tree format), `schemaToSampleObj` and `generateExample`
  (examples), `json2xml`, `flattenAllOf` (one merged schema for an `allOf`),
  `getMergedProperties`/`getMergedRequired`.

Request, response, mock:

- `url-utils.js`: path/query serialization, `constructFetchURL`, `oauthReceiverUrl`.
- `request-utils.js`: headers, url-encoded and multipart bodies.
- `request-status.js`: the Try console's status wording, headless: `SLOW_AFTER_MS` (10 s, after
  which the status line says the server is slow; the request goes on), `formatElapsed`,
  `countStreamItems`, `itemsLabel`, `requestStatusText` (waiting, streaming, stopped),
  `networkErrorText` (a failed fetch: unreachable or CORS, which the browser can't tell apart).
- `stream-utils.js`: OpenAPI 3.2 sequential media types (`itemSchema`): `streamKind`,
  `streamItemLabel`, `serializeStreamItems` (items as SSE events, JSON Lines or JSON Text
  Sequences), `isStreamingResponse`, `readStreamText` (a fetch body as text as it arrives).
  Headless.
- `response-utils.js`: `processFetchResponse` (decode a `Response`),
  `prepareResponseDefinitions`.
- `curl-utils.js`: `generateCurlCommand`.
- `mock-interceptor.js`: `enableMockServer`, `disableMockServer`, `updateMockConfig`,
  `isMockServerActive`, `compileRoutes` (from a `ProcessSpec` result).

UI helpers:

- `highlighter.js`: `highlightAllCode`, `scheduleHighlight` (CSS Custom Highlight API).
- `markdown-utils.js`: `configureMarkdown` and token helpers for the global `marked`.
- `sanitize.js`: `sanitizeHTML`.
- `bind-navbar.js`: `bindNavBar` ties a static `getNavBarHtml` sidebar to `<rapi-doc>`. The active
  item follows `nav-active-change`'s `detail.elementId`, so a tag's section highlights the tag.
- `auto-color-scheme.js`: `AutoColorSchemeController`, `resolvePageColorScheme`.
- `oauth-utils.js`: PKCE (`randomUrlSafe`, `pkceChallenge`), `readOAuthReply`,
  `isExpectedOAuthReply`.
- `color-utils.js`, `xml-utils.js` (`formatXml`): pure helpers.
- `mcp-generator.js`: `generateMcpServer(spec, options) -> { manifest, files, budget, hostConfig }`,
  re-exporting `./mcp` (`buildMcpManifest`, `createMcpRuntime`, `writeMcpProject`, `createZip`,
  `parseMcpEnabled`, ...).

## Invariants

- **`ProcessSpec` never rejects** (`[spec-parser.js:ProcessSpec]`). Loading and post-load
  processing are each wrapped in `try/catch`. Every failure resolves to
  `{ specLoadError: true, isSpecLoading: false, info: { title, description, version }, tags: [],
  tagGroups: [] }`, where `description` is `"<url> ┃ Not Found (404)"`,
  `"Unable to load <url> ┃ <status|message>"`, `"Invalid Spec Definition"`, or
  `"Unable to process the spec ┃ <message>"` for failures after loading. Callers check
  `specLoadError`, not exceptions. It uses an optional `this` (`requestUpdate`,
  `before-render` event), so the component calls it with `.call(element, ...)`.
- **Webhooks** (`[spec-parser.js:groupByTags]`) are grouped after paths and flagged
  `isWebhook`; they are never written into the spec's `paths`, so a webhook named like a path
  does not replace it.
- **OpenAPI 3.2 tags** (`[spec-parser.js:groupByTags]`, `[spec-parser.js:groupByParentTags]`):
  a tag's name in the navigation is `x-displayName`, else `summary`, else `name`. Without
  `x-tagGroups`, tags with a `parent` become tag groups: each root of a `parent` chain that has
  children is a group (its `summary` the heading, itself first when it has operations), and
  deeper descendants sit in the root's group. A parent with no operations is not a tag section.
  An operation goes under its tags of kind `nav` (or no kind); other kinds place it only when it
  has no navigation tag, and `badge` tags are added to its `xBadges`. Anchors are unchanged:
  `parent` groups add no tag prefix.
- **Streams** (`[response-utils.js:prepareResponseDefinitions]`, `[response-utils.js:streamExamples]`):
  a media type with `itemSchema` and no `schema` shows the item schema, with `streamItemLabel`
  set, and its examples as the stream's text: an Example Object whose value is an array is a list
  of items, a string is used as sent, and without examples one item is generated. Request bodies
  (`request-body-template.js`) use the same examples. The mock
  (`[mock-interceptor.js:mockStreamChunks]`) sends a stream through `fetch` one item at a time,
  `mock-server-delay` apart (300 ms when 0): the first example's items, or 5 generated items with
  `id` numbered; through XHR it sends the whole text. The
  Try console reads `text/event-stream`, JSON Lines and `application/json-seq` responses with
  `readStreamText`, showing the text as it arrives, until the stream ends or STOP aborts it.
- **XML arrays** (`[schema-utils.js:xmlArrayValue]`, `[schema-utils.js:json2xml]`): each item is
  an element named by the items' `xml.name`, else the property's name, whether the sample comes
  from an example or the schema. `wrapped: true` or OpenAPI 3.2 `nodeType: element`
  (`[schema-utils.js:isXmlWrapped]`) puts them in an element named by the array's `xml.name`, else
  the property's name; unwrapped, they sit directly in the parent.
- **Example Objects** (`[spec-parser.js:normalizeExampleObjects]`): before grouping, a 3.2
  `dataValue` (else `serializedValue`) is copied to `value` in the spec's paths, webhooks and
  components (mutating the parsed spec), skipping schemas.
- **Stable anchors** (`[slugger.js:operationAnchorSource]`, `[slugger.js:OperationSlugger.slug]`):
  - Source priority: `operationId` (trimmed, 1-45 chars, not a placeholder like `operation12`),
    then `summary` (the parser passes `summary || description`; clamped to 40 chars at a word
    boundary), then `methodPathSlug(method, path)`.
  - Memoized per method + path (and tag slug), so one operation keeps one `elementId` per run.
  - Tag prefix `<tagSlug>--` is applied only when the spec has non-empty `x-tagGroups` or
    `x-tag-groups` (`[spec-parser.js:ProcessSpec]`), and never for the tag `general`.
  - Collisions try `<prefix><method>-<slug>` first, then `github-slugger`'s `-1`, `-2` suffixes,
    which depend on encounter order (paths, then webhooks; methods in `supportedMethods` order).
  - Tag and tag-group ids (`tag--<kebab>`, `tag-group--<kebab>`) are not deduplicated.
  - The portal links to these ids and checks them with `operationAnchorSource`/`methodPathSlug`;
    changing any rule above is a breaking change for published portals.
- **Circular references** (`[spec-loader.js:breakCircularRefs]`): after dereferencing, the tree
  is cloned without `x-ref` keys and each cycle becomes `{ $ref }` (fallback
  `#/components/schemas/Circular`); shared non-cyclic nodes stay shared. The `{ $ref }` takes the
  place of the schema that contains itself, also when the dereferenced copy is a different object
  with the same children (never `properties: { $ref }`). Schema code treats a
  remaining `$ref` as the cycle marker, so renderers must not recurse into it.
- **allOf** (`[schema-utils.js:flattenAllOf]`): the schema table/tree, object notation and
  `getMergedProperties`/`getMergedRequired` read one merged schema: members in order, the
  schema's own keywords last; a property defined in several places is one property, `required`
  is the union. oneOf/anyOf members stay options. Examples of an object still merge each
  member's sample, so a member's own `example` is kept. Results are cached per schema object,
  so schemas must not be changed after they were rendered.
- **Type labels** (`[schema-utils.js:typeLabel]`): parameters, form fields, the schema tree and
  table label a type the same way. A format that implies its type replaces it (`int64`,
  `date-time`); any other format (`string` + `decimal`, custom formats) keeps the type and is
  returned as `formatNote`, shown as a Format chip or constraint. The color comes from the
  declared type, never the format. `getTypeInfo().type` still puts any format in place of
  `string`; example generation reads it, so labels must use `baseType` and `typeLabel`.
- **Schema depth limits** (`[schema-utils.js]`): `schemaToSampleObj` returns `undefined` and
  `schemaInObjectNotation` returns a `::type` stub when `level > 8`. `schemaToAST` expands to
  `MAX_SCHEMA_DEPTH` (8); below `MIN_SCHEMA_DEPTH` (4) an object or array stops expanding once it
  and its direct children would take its tree past `SCHEMA_NODE_BUDGET` (8000 nodes). Cut
  containers become nodes with `truncated: true`. A node's children (`properties`,
  `patternProperties`, `additionalProperties`, `items`, a union's `properties`) are getters built on
  first read with the path and tree the node was built in, then replaced by the value: a tree is
  built only as far as it is read, and a reader that walks it whole (JSON, the PDF) builds all of it.
  Its module state makes it synchronous and non-reentrant.
- **Sanitization** (`[sanitize.js:sanitizeHTML]`): non-strings return `""`. The native
  `Sanitizer` path allows all attributes; the fallback removes only `<script>`, `on*` attributes
  and `javascript:` / `data:text/html` in `href`/`src`. Without `DOMParser` (Node) the input is
  returned unchanged, so server-side output is not sanitized.
- **Mock server** (`[mock-interceptor.js:enableMockServer]`): one mock per `options.owner` (the
  element; omitted, a page-wide default), so several `<rapi-doc>` / `<rapi-doc-mini>` on a page
  mock their own APIs with their own status codes, delay and cycle positions. Repeated calls for an
  owner refresh its routes and config but never stack wrappers; `disableMockServer(owner)` drops
  that mock and restores the originals once none is left. A request is answered by the most
  specific match across the mocks (server origin and base path, then base path, then bare path;
  ties to the mock enabled first); unmatched requests fall through to the real `fetch`/XHR. Mock
  responses carry `X-Mock-Server: RapiDoc`.
- **Highlighter** (`[highlighter.js]`): `highlightAllCode` and `scheduleHighlight` are no-ops
  without `window` and `CSS.highlights`; highlighting never mutates the DOM.
- **Operation filter** (`[filter-operations.js]`): `parseOperationFilter(text)` reads
  `filter-operations` (operationIds, `METHOD /path`, paths, `*` / `**` globs, `tag:`, `badge:`,
  `deprecated`, `!` to exclude; null when it filters nothing), `operationFacts(method, path, op)`
  what the terms look at, `operationRank(filter, facts)` the first include term matched (-1: left
  out). `ProcessSpec` drops left-out operations, and orders each tag's operations, and the tags,
  by that rank unless `sort-endpoints-by` / `sort-tags` is set. Covered by
  `tests/unit/filter-operations.test.js`.
- **Try by operation** (`[try-filter.js:tryStateFor]`): `allow-try` takes the same terms; an
  operation they leave out gets `allow-try="disabled"` on its `<api-request>` (documented, a
  disabled TRY DISABLED button) and `try-disabled-reason` from `tryReasonFor` (the ! term that matched,
  as `test.term`, or the include terms), and `tryAnywhere` keeps the Authentication section on unless
  `allow-try` is `false`. `badge:` also matches OpenAPI 3.2 `kind: badge` tags, by label or name.
  Covered by `allow-try-filter`.
- **Headless boundary**: `spec-parser.js`, `spec-loader.js`, `schema-utils.js`, `slugger.js`, `mcp-generator.js`,
  `mcp/`, `arazzo/` and everything they import are shared with the Node builds (`@rapidoc/prerender`,
  `@rapidoc/mcp`) and, for `spec-loader.js` and `schema-utils.js`, with `rapipdf`. They never import Lit, elements, `components/`, `templates/`, `styles/` or
  `static/`, and use only the third-party packages allowed in `tests/unit/headless-boundary.test.js`.
  DOM calls inside functions are allowed (Node never calls them); DOM access at import time is not.

## Side Effects

- `ProcessSpec` fetches the spec and external `$ref`s, logs load errors with `console.info`, and
  mutates the spec it processes: `x-ref` during dereference, `paths` replaced by `filterPaths` (the operations `filter-operations` shows, `[filter-operations.js]`),
  `callbacks` filtered, relative `servers[*].url` made absolute against the spec's address, or the page's for a spec
  without one (`[spec-parser.js:resolveServerUrl]`; unchanged outside a browser),
  `computedUrl` added.
- `mock-interceptor.js` replaces `window.fetch` and `XMLHttpRequest.prototype` methods while
  active and keeps routes and config in module state.
- `markdown-utils.js` configures the global `marked` at import time.
- `highlighter.js` writes the global `CSS.highlights` registry and schedules
  `requestAnimationFrame`.
- `bind-navbar.js` adds DOM and `window` listeners, writes `history` (`replaceState`, keeping
  `history.state` for routers); some timers and the
  `spec-loaded` listener outlive `unbind()`.
- `auto-color-scheme.js` observes `<html>`/`<body>` attributes and `prefers-color-scheme`.
- `response-utils.js` creates object URLs it does not revoke; `common-utils.js` clipboard and
  download helpers create temporary elements.

## Verification

Run `npm run test:unit` from the repo root before and after changing `spec-parser.js` or
`schema-utils.js`, then `npm run lint` and `npm run format-fix`. Files in `tests/unit/`:

- `spec-parser.js`: `spec-parser-relative-url`, `spec-parser-security`,
  `spec-parser-tag-groups`, `spec-parser-webhooks`, `unused-tags`, `openapi-3-2-petstore`,
  `openapi-3-2-tags`.
- `stream-utils.js`, `response-utils.js` (streams): `openapi-3-2-streaming`.
- `request-status.js` and the Try panel by request phase: `try-request-status`.
- `spec-loader.js`: `spec-loader`.
- `slugger.js`: `slugger`.
- `schema-utils.js`: `schema-utils`, `schema-ast`, `schema-in-object-notation`,
  `schema-nullable`, `schema-modernization`, `multipart-form-curl`, `type-format-label`.
- `url-utils.js`: `query-param-serialization`, `oauth-receiver-url`.
- `request-utils.js`, `curl-utils.js`: `request-utils`, `multipart-part-types`, `curl-command`.
- `response-utils.js`: `api-request-response`.
- `mock-interceptor.js`, `oauth-utils.js`, `markdown-utils.js`, `mcp-generator.js`: the
  test file of the same name.
- Headless boundary (imports of the modules above, transitively): `headless-boundary`.
