Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/building-block-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ Add an entry to root `api-references.yml` with `id`, `page`, `contract`, and
illustrative binding. Keep those on separate pages. Do not add a requirement
just to make a contract visible.

The page opens on operations, with its role and downloads visible and technical
metadata collapsed. The full source contract remains available to download.
The page displays the contract introduction, when supplied, and its operations,
with its role and downloads visible and technical metadata collapsed. The full
source contract remains available to download.
Local `$ref` dependencies are bundled; remote and escaping references fail the
build. Do not copy bundled JSON or Scalar assets into the source repository.

Expand Down
9 changes: 8 additions & 1 deletion src/components/ReferenceContent.astro
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const isReference = publication.apiReferences?.some((reference: { route: string
{isReference ? <div class="native-reference-content"><slot /></div> : <MarkdownContent><slot /></MarkdownContent>}

<script>
import { scalarDocument } from '../lib/scalar-document.mjs';

type ReferenceInstance = { destroy: () => void };
type ScalarWindow = Window & { Scalar?: { createApiReference: (element: HTMLElement, configuration: Record<string, unknown>) => ReferenceInstance } };
let scalarReady: Promise<void> | undefined;
Expand All @@ -32,15 +34,20 @@ const isReference = publication.apiReferences?.some((reference: { route: string
await loadScalar(host.dataset.scriptUrl!);
const scalar = (window as ScalarWindow).Scalar;
if (!scalar) throw new Error('Scalar is unavailable');
const response = await fetch(host.dataset.contractUrl!);
if (!response.ok) throw new Error(`Could not load OpenAPI document: HTTP ${response.status}`);
const content = scalarDocument(await response.json());
const root = document.documentElement;
let theme = root.dataset.theme;
const mount = () => scalar.createApiReference(host, {
url: host.dataset.contractUrl,
content,
showSidebar: false,
hideSearch: true,
withDefaultFonts: false,
hideClientButton: true,
hideTestRequestButton: true,
// The toolbar downloads the unchanged bundle, rather than the display copy.
hideDownloadButton: true,
showDeveloperTools: 'never',
telemetry: false,
persistAuth: false,
Expand Down
42 changes: 42 additions & 0 deletions src/lib/scalar-document.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']);

/**
* Scalar 1.76 ignores description siblings on operation response references.
* Inline only those responses in its display copy, preserving the source download.
*/
export function scalarDocument(document) {
const display = structuredClone(document);
if (!/^3\.1(?:\.|$)/.test(display.openapi ?? '')) return display;

function responseValue(value, seen = new Set()) {
if (!value?.$ref) return value;
const reference = value.$ref;
if (typeof reference !== 'string' || !reference.startsWith('#/')) {
throw new Error('Expected a bundled local response reference');
}
if (seen.has(reference)) throw new Error(`Cyclic response reference: ${reference}`);
seen.add(reference);
let target = display;
for (const part of reference.slice(2).split('/')) {
const key = decodeURIComponent(part).replaceAll('~1', '/').replaceAll('~0', '~');
target = target && Object.hasOwn(target, key) ? target[key] : undefined;
}
if (!target || typeof target !== 'object') throw new Error(`Missing response reference: ${reference}`);
return {
...responseValue(target, seen),
...(typeof value.description === 'string' ? { description: value.description } : {}),
};
}

for (const item of Object.values(display.paths ?? {})) {
for (const [method, operation] of Object.entries(item ?? {})) {
if (!METHODS.has(method)) continue;
for (const [status, response] of Object.entries(operation.responses ?? {})) {
if (response?.$ref && typeof response.description === 'string') {
operation.responses[status] = responseValue(response);
}
}
}
}
return display;
}
8 changes: 5 additions & 3 deletions src/styles/govstack.css
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ body:has(.native-reference-content) .main-pane { min-width: 0; }
body:has(.native-reference-content) .content-panel:has(.api-reference-title) { padding-bottom: 0; }
body:has(.native-reference-content) .content-panel:has(.native-reference-content) { border-top: 0; }
.native-reference-content { min-width: 0; }
[data-scalar-reference] { --scalar-font: var(--sl-font); --scalar-font-code: var(--sl-font-mono); }
/* Scalar 1.76 uses this stable introduction-entry suffix. The source stays in the download. */
.native-reference-content .api-reference-native [data-scalar-reference] [id$='/description/introduction'] { display: none; }
[data-scalar-reference] {
--scalar-custom-header-height: var(--sl-nav-height);
--scalar-font: var(--sl-font);
--scalar-font-code: var(--sl-font-mono);
}
header.header {
background: var(--sl-color-bg);
border-bottom: 1px solid var(--sl-color-gray-5);
Expand Down
20 changes: 18 additions & 2 deletions tests/api-reference-page.test.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { apiReferenceMarkup, prepareApiReferences } from '../scripts/api-references.mjs';

test('native reference opens on the contract without a repeated introduction or response', () => {
test('native reference uses Scalar introduction without a repeated hand-built introduction or response', async () => {
const reference = {
id: 'birth', title: 'Birth registration', role: 'example',
contract: 'api/birth.yaml', contractUrl: '/registries/api-reference/birth.json',
Expand All @@ -25,6 +25,13 @@ test('native reference opens on the contract without a repeated introduction or
assert.match(html, /data-scalar-reference/);
assert.match(html, /data-script-url="\/registries\/api-reference\/scalar\.js"/);
assert.match(html, /\/registries\/api-reference\/birth\.json/);

const styles = await readFile(new URL('../src/styles/govstack.css', import.meta.url), 'utf8');
assert.doesNotMatch(
styles,
/\[id\$=['"]\/description\/introduction['"]\][^{]*\{[^}]*\bdisplay\s*:\s*none\b/i,
"Scalar's info.description introduction must remain visible",
);
});

test('native reference markup does not require an operation or response selection', () => {
Expand All @@ -50,6 +57,15 @@ test('native reference markup does not require an operation or response selectio
assert.doesNotMatch(html, /api-response-example|operation selection/i);
});

test('native Scalar sticky content clears the Starlight header', async () => {
const styles = await readFile(new URL('../src/styles/govstack.css', import.meta.url), 'utf8');
assert.match(
styles,
/\[data-scalar-reference\]\s*\{[^}]*--scalar-custom-header-height\s*:\s*var\(--sl-nav-height\)/i,
'Scalar must include the fixed Starlight header in its viewport offset',
);
});

test('absolute contract refs cannot use an in-source decoy to read outside the source', async (t) => {
const root = await mkdtemp(path.join(os.tmpdir(), 'api-reference-absolute-'));
t.after(() => rm(root, { recursive: true }));
Expand Down
60 changes: 60 additions & 0 deletions tests/scalar-document.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
import { scalarDocument } from '../src/lib/scalar-document.mjs';

const fixture = () => ({
openapi: '3.1.2',
paths: {
'/records': { get: { responses: {
'400': { $ref: '#/components/responses/BadRequest', description: 'Invalid query parameters.' },
'500': { $ref: '#/components/responses/BadRequest' },
} } },
'/search': { post: { responses: {
'400': { $ref: '#/components/responses/BadRequest', description: 'Malformed JSON or invalid search input.' },
} } },
},
components: { responses: { BadRequest: {
description: 'Shared input error taxonomy.',
headers: { 'Cache-Control': { schema: { const: 'no-store' } } },
content: { 'application/problem+json': {
schema: { $ref: '#/components/schemas/Problem' },
example: { status: 400, description: { $ref: 'payload data', description: 'Keep this data.' } },
} },
} }, schemas: { Problem: { type: 'object', required: ['status'] } } },
});

test('Scalar receives each operation response description with the exact referenced content', () => {
const source = fixture(), before = structuredClone(source);
const rendered = scalarDocument(source);
const response = getResolvedRef(rendered.paths['/records'].get.responses['400']);
assert.equal(response.description, 'Invalid query parameters.');
assert.deepEqual(response.content, source.components.responses.BadRequest.content);
assert.deepEqual(response.headers, source.components.responses.BadRequest.headers);
assert.equal(getResolvedRef(rendered.paths['/search'].post.responses['400']).description, 'Malformed JSON or invalid search input.');
assert.deepEqual(rendered.components, source.components);
assert.deepEqual(rendered.paths['/records'].get.responses['500'], source.paths['/records'].get.responses['500']);
assert.deepEqual(source, before, 'the downloadable contract must not be mutated');
});

test('only OpenAPI 3.1 Reference descriptions are adapted', () => {
const source = fixture();
source.openapi = '3.0.3';
assert.deepEqual(scalarDocument(source), source);
});

test('response aliases preserve inner descriptions and apply the outermost override', () => {
const source = fixture();
source.components.responses.Alias = { $ref: '#/components/responses/BadRequest', description: 'Alias description.' };
source.paths['/records'].get.responses['400'].$ref = '#/components/responses/Alias';
assert.equal(scalarDocument(source).paths['/records'].get.responses['400'].description, 'Invalid query parameters.');
});

test('missing or cyclic references fail visibly instead of displaying unrelated help', () => {
const missing = fixture();
missing.paths['/records'].get.responses['400'].$ref = '#/components/responses/Missing';
assert.throws(() => scalarDocument(missing), /Missing.*reference/i);
const cyclic = fixture();
cyclic.components.responses.BadRequest = { $ref: '#/components/responses/BadRequest' };
assert.throws(() => scalarDocument(cyclic), /Cyclic.*reference/i);
});
Loading