@writedocs/generator 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -147,6 +147,11 @@ interface Props {
147
147
  breadcrumbs?: { name: string; href: string }[];
148
148
  // An OpenAPI page: its structured data says APIReference.
149
149
  isApi?: boolean;
150
+ // A script run first thing, in <head> - the operation page of a Scalar
151
+ // group sends its reader on to the reference with it
152
+ // (lib/scalar-reference.js). Again after a client-side navigation to the
153
+ // page (data-astro-rerun).
154
+ headScript?: string;
150
155
  }
151
156
  const {
152
157
  config,
@@ -161,6 +166,7 @@ const {
161
166
  alternates = [],
162
167
  breadcrumbs = [],
163
168
  isApi = false,
169
+ headScript,
164
170
  } = Astro.props as Props;
165
171
  const showSidebarCol = mode === "default" || mode === "wide";
166
172
  const showTocCol = mode === "default";
@@ -515,6 +521,7 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
515
521
  <head>
516
522
  <meta charset="UTF-8" />
517
523
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
524
+ {headScript && <script is:inline data-astro-rerun set:html={headScript} />}
518
525
  {/* Marks the pages writedocs renders - the build checks each has the site's styles (cli/check-built-styles.js). */}
519
526
  <meta name="generator" content="writedocs" />
520
527
  <title>{head.title}</title>
@@ -26,7 +26,16 @@ const navGroupOpenApiSchema = z.object({
26
26
  // so two openapi groups in the same writedocs.json must use different
27
27
  // `path` values - generate-api-pages.js throws a clear error if
28
28
  // they collide.
29
- path: z.string()
29
+ path: z.string(),
30
+ // How readers see the group: "writedocs" (the default) - a page per
31
+ // operation, grouped by tag - or "scalar": one page at `path` with
32
+ // Scalar's API reference (lib/scalar-reference.js). The per-operation
33
+ // pages are still built for a "scalar" group - search, llms.txt, MCP
34
+ // and the .md copies read them - but out of the sidebar, noindex, and
35
+ // sent on to their operation in the reference. Optional rather than
36
+ // defaulted, so a writedocs.json without it validates to the same data
37
+ // as before the field existed.
38
+ renderer: z.enum(["writedocs", "scalar"]).optional()
30
39
  }).strict()
31
40
  }).strict();
32
41
  const navGroupSchema = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
@@ -580,8 +589,13 @@ const apiSchema = z.object({
580
589
  // call fails for most real APIs - see the send handler and
581
590
  // PROXY_BASE_URL in ApiReferencePanel.astro. Defaults to enabled; a
582
591
  // site can set this to `false` to never involve a third party.
583
- proxy: z.boolean().default(true)
584
- }).strict().default({ proxy: true });
592
+ proxy: z.boolean().default(true),
593
+ // Which client the "Try it" button opens: writedocs' own modal
594
+ // (ApiReferencePanel.astro, the default) or Scalar's API client
595
+ // (ScalarTryIt.astro + src/scripts/scalar-try-it.ts), loaded only when a
596
+ // reader clicks. The API pages themselves are the same either way.
597
+ playground: z.enum(["writedocs", "scalar"]).default("writedocs")
598
+ }).strict().default({ proxy: true, playground: "writedocs" });
585
599
  const CONTEXT_MENU_OPTIONS = ["copy", "view", "chatgpt", "claude", "perplexity", "mcp", "cursor", "vscode"];
586
600
  const ASSISTANT_OPTIONS = ["chatgpt", "claude", "perplexity"];
587
601
  const MCP_MENU_OPTIONS = ["mcp", "cursor", "vscode"];
@@ -88,13 +88,22 @@ const navGroupOpenApiSchema = z.object({
88
88
  // `path` values - generate-api-pages.js throws a clear error if
89
89
  // they collide.
90
90
  path: z.string(),
91
+ // How readers see the group: "writedocs" (the default) - a page per
92
+ // operation, grouped by tag - or "scalar": one page at `path` with
93
+ // Scalar's API reference (lib/scalar-reference.js). The per-operation
94
+ // pages are still built for a "scalar" group - search, llms.txt, MCP
95
+ // and the .md copies read them - but out of the sidebar, noindex, and
96
+ // sent on to their operation in the reference. Optional rather than
97
+ // defaulted, so a writedocs.json without it validates to the same data
98
+ // as before the field existed.
99
+ renderer: z.enum(['writedocs', 'scalar']).optional(),
91
100
  })
92
101
  .strict(),
93
102
  }).strict();
94
103
 
95
104
  export type GroupNavItem =
96
105
  | { group: string; page?: string; pages: NavItem[] }
97
- | { group: string; openapi: { src: string; path: string } };
106
+ | { group: string; openapi: { src: string; path: string; renderer?: 'writedocs' | 'scalar' } };
98
107
 
99
108
  const navGroupSchema: z.ZodType<GroupNavItem> = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
100
109
 
@@ -987,9 +996,14 @@ const apiSchema = z
987
996
  // PROXY_BASE_URL in ApiReferencePanel.astro. Defaults to enabled; a
988
997
  // site can set this to `false` to never involve a third party.
989
998
  proxy: z.boolean().default(true),
999
+ // Which client the "Try it" button opens: writedocs' own modal
1000
+ // (ApiReferencePanel.astro, the default) or Scalar's API client
1001
+ // (ScalarTryIt.astro + src/scripts/scalar-try-it.ts), loaded only when a
1002
+ // reader clicks. The API pages themselves are the same either way.
1003
+ playground: z.enum(['writedocs', 'scalar']).default('writedocs'),
990
1004
  })
991
1005
  .strict()
992
- .default({ proxy: true });
1006
+ .default({ proxy: true, playground: 'writedocs' });
993
1007
 
994
1008
  // The "Copy page" menu shown next to a page's title - copy the page's
995
1009
  // Markdown, view it, or open it in an AI assistant - and the .md copy of
package/src/lib/config.ts CHANGED
@@ -7,6 +7,7 @@ import { accessOf, isLocked } from './protected-sections.js';
7
7
  import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLandingsJs } from './item-pages.js';
8
8
  import matter from 'gray-matter';
9
9
  import { writedocsTempDir } from './writedocs-temp-dir.js';
10
+ import { readScalarReferences } from './scalar-reference.js';
10
11
  import { readableTextOn } from './color.js';
11
12
  import { oncePerBuild } from './build-memo.js';
12
13
  import { normalizeBasePath, siteUrlFor, siteOriginFor } from './base-path.js';
@@ -343,10 +344,24 @@ function loadOpenApiManifest(contentDir: string, specPath: string): OpenApiManif
343
344
  * manifest is missing - generate-api-pages.js always runs before this
344
345
  * does (see src/cli/dev.js/build.js), so a missing manifest here means
345
346
  * generation hasn't happened yet rather than a user error worth
346
- * crashing the dev server over. */
347
- function expandOpenApiGroupPages(openapiRef: { src: string; path: string }, contentDir: string): NavItem[] {
347
+ * crashing the dev server over.
348
+ *
349
+ * A group with `renderer: "scalar"` is its reference page first - the page
350
+ * its sidebar shows, and the one a tab with it opens on - then every
351
+ * operation page, which [...slug].astro leaves out of the sidebar and the
352
+ * page-by-page links (lib/scalar-reference.js). They stay here so each
353
+ * keeps its section: its access rule, search space and language. */
354
+ function expandOpenApiGroupPages(
355
+ openapiRef: { src: string; path: string; renderer?: string },
356
+ contentDir: string
357
+ ): NavItem[] {
348
358
  const manifest = loadOpenApiManifest(contentDir, openapiRef.path);
349
359
  if (!manifest) return [];
360
+ if (openapiRef.renderer === 'scalar') {
361
+ const slug = openapiRef.path.replace(/^\/+|\/+$/g, '');
362
+ const reference = readScalarReferences(contentDir).find((r: { slug: string }) => r.slug === slug);
363
+ if (reference) return [reference.slug, ...manifest.map((op) => op.slug)];
364
+ }
350
365
 
351
366
  const seenTags: string[] = [];
352
367
  const byTag = new Map<string, string[]>();
@@ -152,6 +152,7 @@ export const DESCRIPTIONS = {
152
152
  'NavigationItem.openapi': 'Generate this group\'s pages from an OpenAPI spec - a page per operation, grouped by tag.',
153
153
  'NavigationItem.openapi.src': 'Path of the OpenAPI spec file, relative to writedocs.json.',
154
154
  'NavigationItem.openapi.path': 'URL path the generated pages go under, like "/api". Each OpenAPI group needs its own.',
155
+ 'NavigationItem.openapi.renderer': 'How readers see the group: "writedocs" (the default), a page per operation grouped by tag; or "scalar", one page at `path` with Scalar\'s API reference and its own Try it. Search, llms.txt, MCP and the .md copies still cover every operation.',
155
156
  'NavigationItem.label': 'Link text in the sidebar.',
156
157
  'NavigationItem.href': 'Where the link goes.',
157
158
  ...Object.fromEntries(containerEntries),
@@ -169,6 +170,7 @@ export const DESCRIPTIONS = {
169
170
 
170
171
  api: 'The API playground.',
171
172
  'api.proxy': 'When the browser blocks a "Try it" request (the API doesn\'t allow calls from other sites - CORS), retry it through writedocs\' proxy. Requests always go to the API directly first. Default true.',
173
+ 'api.playground': 'Which client the "Try it" button of the API pages opens: "writedocs" (the default) or "scalar" (Scalar\'s API client, loaded only when a reader clicks Try it). The API pages are the same either way; api.proxy applies to both.',
172
174
  domain: 'The site\'s address, like "docs.example.com". Turns on sitemap.xml and absolute URLs in link previews.',
173
175
  basePath: 'The path the site is served under, like "/docs" for example.com/docs - usually behind your own proxy. Every address the site makes starts with it, and the build writes the site to dist/docs/. Starts with "/", no "/" at the end; lowercase letters, digits, "-" and "_". Default: none, the site at the root.',
174
176
 
@@ -8,7 +8,8 @@
8
8
  // from the specs and writes it; astro.config.mjs adds it to the site's
9
9
  // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
10
  // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
- // counts the old addresses as existing.
11
+ // counts the old addresses as existing. One that leads to a protected page
12
+ // stays out of `_redirects` (protectedMovedApiPages() below).
12
13
  //
13
14
  // Plain JavaScript: read by code that runs under plain Node.
14
15
  import fs from 'node:fs';
@@ -47,3 +48,17 @@ export function untaggedRedirects(pathPrefix, moved, taken) {
47
48
  }
48
49
  return redirects;
49
50
  }
51
+
52
+ /** The moved addresses that lead to a protected page, as `{ slug, rule }`
53
+ * (the old address without its slashes, and the page's access rule):
54
+ * [...slug].astro adds them to the protected addresses - the access map,
55
+ * dist/.writedocs/access.json - and write-redirects-file.js leaves them
56
+ * out of `_redirects`, so the redirect stays a page behind the page's rule
57
+ * instead of an edge redirect that names the protected address to anyone.
58
+ * `ruleOf(slug)`: the rule of the page at `slug`, or null. */
59
+ export function protectedMovedApiPages(moved, ruleOf) {
60
+ return moved.flatMap(({ source, destination }) => {
61
+ const rule = ruleOf(destination.replace(/^\/+|\/+$/g, ''));
62
+ return rule ? [{ slug: source.replace(/^\/+|\/+$/g, ''), rule }] : [];
63
+ });
64
+ }
@@ -117,6 +117,11 @@ export interface OpenApiOperation {
117
117
  responses: Record<string, { description?: string; content?: Record<string, { schema?: OpenApiSchema }> }>;
118
118
  servers: { url: string }[];
119
119
  security: { name: string; type: string; in?: string; scheme?: string }[];
120
+ // The same security as the spec wrote it - requirements and the schemes
121
+ // they name (generate-api-pages.js's securityAsWritten()). Read by
122
+ // lib/scalar-document.js, for Scalar's "Try it".
123
+ securityRequirements?: Record<string, string[]>[];
124
+ securitySchemes?: Record<string, Record<string, unknown>>;
120
125
  }
121
126
 
122
127
  /** Merges `allOf` members into one flat {type, properties, required}
@@ -0,0 +1,56 @@
1
+ // Where an operation is in Scalar's API reference (an OpenAPI group with
2
+ // `openapi.renderer: "scalar"`): the address fragment of its section,
3
+ // "tag/pets/GET/pets/{petId}" - "/api/#tag/pets/GET/pets/{petId}" on the page.
4
+ //
5
+ // Scalar makes these ids itself (getNavigationOptions() in
6
+ // @scalar/workspace-store): `tag/<tag slug>/<operation slug>` for an operation
7
+ // with a tag - under its first tag - and `<operation slug>` for one without,
8
+ // each behind the document's own slug, which the address leaves out for a
9
+ // page with one document. Both slugs come from functions its configuration
10
+ // can replace (`generateTagSlug`, `generateOperationSlug`), and
11
+ // src/scripts/scalar-reference.ts gives it the two below - so the anchor the
12
+ // build works out for an operation (the redirect from its page, its search
13
+ // result) is the one the reader's browser makes, by construction, and stays
14
+ // the same from build to build and Scalar version to version: it depends on
15
+ // the operation's first tag, method and path only.
16
+ //
17
+ // Plain JavaScript with no Node import: imported by the build and by the
18
+ // browser script.
19
+
20
+ const NON_WORD = /[^\p{L}\p{M}\p{N}\s_-]/gu;
21
+ const SPACES = /[\s_-]+/g;
22
+ const EDGE_HYPHENS = /^-+|-+$/g;
23
+
24
+ /** A tag name as a slug: Scalar's own slugify() (@scalar/helpers), with its
25
+ * defaults - lower case, letters, marks, digits and hyphens only, spaces
26
+ * and underscores as one hyphen, at most 255 characters read. */
27
+ export function scalarSlug(value) {
28
+ return String(value ?? '')
29
+ .slice(0, 255)
30
+ .trim()
31
+ .normalize('NFC')
32
+ .toLowerCase()
33
+ .replace(NON_WORD, '')
34
+ .replace(SPACES, '-')
35
+ .replace(EDGE_HYPHENS, '');
36
+ }
37
+
38
+ /** Scalar's `generateTagSlug` - it gets the tag object. */
39
+ export function scalarTagSlug(tag) {
40
+ return scalarSlug(tag?.name ?? '');
41
+ }
42
+
43
+ /** Scalar's `generateOperationSlug` - it gets `{ path, method, ... }`, the
44
+ * method upper case for a standard one. "GET/pets/{petId}", as Scalar's
45
+ * default writes it. */
46
+ export function scalarOperationSlug({ method, path }) {
47
+ return `${String(method).toUpperCase()}${path}`;
48
+ }
49
+
50
+ /** The operation's fragment in the reference (no "#"). `tags` as the spec
51
+ * lists them - Scalar shows the operation under each, and this is the
52
+ * first. */
53
+ export function scalarOperationAnchor({ method, path, tags = [] }) {
54
+ const operation = scalarOperationSlug({ method, path });
55
+ return tags.length ? `tag/${scalarTagSlug({ name: tags[0] })}/${operation}` : operation;
56
+ }
@@ -0,0 +1,63 @@
1
+ // What Scalar's "Try it" gets (writedocs.json `api.playground: "scalar"`):
2
+ // the OpenAPI document of one operation, built from the operation JSON the
3
+ // build already writes for the page (generate-api-pages.js) - never the
4
+ // project's spec file, and never fetched. It goes into the page itself
5
+ // (ScalarTryIt.astro), so it's exactly as public as the page: on a page of a
6
+ // protected section (`access`), behind the same rule.
7
+ //
8
+ // Plain JavaScript so the tests can import it.
9
+
10
+ const METHODS_WITHOUT_BODY = new Set(['GET', 'HEAD']);
11
+
12
+ /** One operation (the build's operation JSON) as an OpenAPI 3.1 document
13
+ * with only that operation. `title` names the document (Scalar shows it in
14
+ * its sidebar, which starts closed). Null fields are left out; schemas stay
15
+ * as the build dereferenced them - a recursive one as its `x-circular`
16
+ * stand-in. */
17
+ export function scalarDocument(op, { title } = {}) {
18
+ const operation = {};
19
+ if (op.operationId) operation.operationId = op.operationId;
20
+ if (op.summary) operation.summary = op.summary;
21
+ if (op.description) operation.description = op.description;
22
+ if (op.tags?.length) operation.tags = op.tags;
23
+ if (op.parameters?.length) operation.parameters = op.parameters;
24
+ if (op.requestBody && !METHODS_WITHOUT_BODY.has(op.method.toUpperCase())) operation.requestBody = op.requestBody;
25
+ operation.responses = op.responses && Object.keys(op.responses).length ? op.responses : { default: { description: '' } };
26
+
27
+ const { requirements, schemes } = securityOf(op);
28
+ if (requirements) operation.security = requirements;
29
+
30
+ const doc = {
31
+ openapi: '3.1.0',
32
+ info: { title: title || op.summary || `${op.method} ${op.path}`, version: '' },
33
+ paths: { [op.path]: { [op.method.toLowerCase()]: operation } },
34
+ };
35
+ if (op.servers?.length) doc.servers = op.servers;
36
+ if (Object.keys(schemes).length) doc.components = { securitySchemes: schemes };
37
+ return doc;
38
+ }
39
+
40
+ /** The operation's security requirements and schemes. Builds before this
41
+ * module existed (or a hand-made operation file) only have the flattened
42
+ * `security` list - then each scheme in it is offered on its own. */
43
+ function securityOf(op) {
44
+ if (op.securityRequirements) {
45
+ return { requirements: op.securityRequirements, schemes: op.securitySchemes ?? {} };
46
+ }
47
+ if (!op.security?.length) return { requirements: null, schemes: {} };
48
+ const schemes = {};
49
+ for (const { name, ...scheme } of op.security) {
50
+ // generate-api-pages.js's resolveSecurity() lets an apiKey scheme's own
51
+ // `name` (the header or parameter) stand for the scheme's key.
52
+ schemes[name] = scheme.type === 'apiKey' ? { ...scheme, name } : scheme;
53
+ }
54
+ return { requirements: Object.keys(schemes).map((name) => ({ [name]: [] })), schemes };
55
+ }
56
+
57
+ /** JSON for a `<script type="application/json">`: every `<` escaped, so no
58
+ * text in the spec can close the tag (`</script>`) or open a comment. The
59
+ * block is only ever read with JSON.parse(), never run. */
60
+ export function jsonForScript(value) {
61
+ const backslash = String.fromCharCode(92);
62
+ return JSON.stringify(value).replace(/</g, `${backslash}u003c`);
63
+ }
@@ -0,0 +1,89 @@
1
+ // How a request from Scalar's "Try it" leaves the browser - the `customFetch`
2
+ // writedocs gives Scalar's API client (src/scripts/scalar-try-it.ts).
3
+ //
4
+ // Scalar's own way to reach an API that refuses browser calls is a proxy URL
5
+ // it rewrites every request to, `<proxy>?scalar_url=<url>` - by default its
6
+ // own hosted proxy.scalar.com. writedocs never uses that: Scalar gets no
7
+ // proxy URL (its modal then sends straight to the API), and this function
8
+ // applies writedocs' own rules, the ones writedocs' playground follows
9
+ // (ApiReferencePanel.astro's send handler):
10
+ //
11
+ // - the request goes straight to the API first, so a reader's key reaches
12
+ // only the API;
13
+ // - only when the browser blocks it (fetch() rejects - CORS, or the host
14
+ // can't be reached) and writedocs.json's `api.proxy` is on, the same
15
+ // request goes again through writedocs' proxy, which is cors-anywhere
16
+ // style: the target URL right after the base. The response then carries
17
+ // an `x-writedocs-proxy` header, which Scalar lists with the others;
18
+ // - not a request the browser sends without asking first (a CORS "simple"
19
+ // request) that is a POST: it may already have reached the API, and
20
+ // sending it again could run it twice;
21
+ // - a request the reader cancelled isn't sent again.
22
+ //
23
+ // Plain JavaScript (Request/Response, nothing else) so the tests can import it.
24
+
25
+ /** writedocs' CORS proxy - the same one as PROXY_BASE_URL in
26
+ * ApiReferencePanel.astro (kept there as a literal, in that page script). */
27
+ export const WRITEDOCS_PROXY_URL = 'https://proxy.writechoice.io/';
28
+
29
+ /** The header a response sent through the proxy carries, and what it says. */
30
+ export const PROXY_HEADER = 'x-writedocs-proxy';
31
+ export const PROXY_HEADER_VALUE = 'sent through the writedocs proxy - the API blocks direct browser requests (CORS)';
32
+
33
+ const METHODS_WITHOUT_BODY = new Set(['GET', 'HEAD']);
34
+ const SAFELISTED_HEADERS = new Set(['accept', 'accept-language', 'content-language', 'content-type']);
35
+ const SIMPLE_CONTENT_TYPES = ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain'];
36
+
37
+ /** Whether the browser sends this request without a preflight (the CORS
38
+ * spec's "simple" request): GET, HEAD or POST, and only safelisted headers,
39
+ * a Content-Type among the three a form can send. */
40
+ export function isSimpleRequest(method, headers) {
41
+ if (!['GET', 'HEAD', 'POST'].includes(method.toUpperCase())) return false;
42
+ for (const [name, value] of new Headers(headers)) {
43
+ if (!SAFELISTED_HEADERS.has(name.toLowerCase())) return false;
44
+ if (name.toLowerCase() === 'content-type' && !SIMPLE_CONTENT_TYPES.includes(value.split(';')[0].trim().toLowerCase())) return false;
45
+ }
46
+ return true;
47
+ }
48
+
49
+ /** A blocked request that mustn't be sent again: a simple POST may already
50
+ * have run on the API, the browser only kept its response from the page. */
51
+ export function mayHaveRun(method, headers) {
52
+ return method.toUpperCase() === 'POST' && isSimpleRequest(method, headers);
53
+ }
54
+
55
+ /** The fetch for Scalar's API client. `proxy`: writedocs.json's `api.proxy`.
56
+ * `fetchImpl`: the fetch to call (the browser's). */
57
+ export function tryItFetch({ proxy, fetchImpl = (...args) => globalThis.fetch(...args) }) {
58
+ return async function writedocsTryItFetch(input, init) {
59
+ const request = new Request(input, init);
60
+ // Read before the first try: sending it consumes the body.
61
+ const body = METHODS_WITHOUT_BODY.has(request.method) ? undefined : await request.clone().arrayBuffer();
62
+ try {
63
+ return await fetchImpl(request);
64
+ } catch (err) {
65
+ if (!proxy || request.signal?.aborted || err?.name === 'AbortError') throw err;
66
+ if (mayHaveRun(request.method, request.headers)) {
67
+ throw new Error('Blocked by the browser (CORS). Not retried through the writedocs proxy: this POST may already have reached the API.', { cause: err });
68
+ }
69
+ let res;
70
+ try {
71
+ res = await fetchImpl(WRITEDOCS_PROXY_URL + request.url, {
72
+ method: request.method,
73
+ headers: request.headers,
74
+ body,
75
+ signal: request.signal,
76
+ });
77
+ } catch (proxyErr) {
78
+ throw new Error('Request failed through the writedocs proxy too - the base URL may be unreachable from the internet.', { cause: proxyErr });
79
+ }
80
+ return markedAsProxied(res);
81
+ }
82
+ };
83
+ }
84
+
85
+ function markedAsProxied(res) {
86
+ const headers = new Headers(res.headers);
87
+ headers.set(PROXY_HEADER, PROXY_HEADER_VALUE);
88
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
89
+ }
@@ -0,0 +1,32 @@
1
+ // Which component the alias `writedocs/scalar-reference` (astro.config.mjs)
2
+ // resolves to - [...slug].astro imports the page of Scalar's API reference
3
+ // (an OpenAPI group with `openapi.renderer: "scalar"`) through it.
4
+ //
5
+ // Why an alias, as for the API pages' Scalar Try it
6
+ // (lib/scalar-try-it-alias.js): Astro bundles the <script> of every
7
+ // component a page imports, rendered or not, and ScalarReference.astro's
8
+ // script import()s Scalar - a plain import would put Scalar's chunks in the
9
+ // _astro/ folder of every site. Through the alias a build imports
10
+ // ScalarReference.astro only when writedocs.json has a group asking for it;
11
+ // otherwise an empty component, and the build is the same as before the
12
+ // option existed.
13
+ //
14
+ // `writedocs dev` always gets the real one: it reads writedocs.json again on
15
+ // every request, so a switch to "scalar" mid-session works without a restart.
16
+ //
17
+ // Plain JavaScript so the tests can import it.
18
+ import path from 'node:path';
19
+
20
+ export const SCALAR_REFERENCE_ALIAS = 'writedocs/scalar-reference';
21
+
22
+ /** What src/scripts/scalar-reference.ts imports from Scalar - for Vite's
23
+ * optimizeDeps in `writedocs dev` (astro.config.mjs), so its first load
24
+ * doesn't reload the page. Keep in step with its imports (the tests check). */
25
+ export const SCALAR_REFERENCE_OPTIMIZED_DEPS = ['@scalar/api-reference'];
26
+
27
+ /** The component file the alias points at. `scalar`: whether a group of
28
+ * the site shows Scalar's reference (lib/scalar-reference.js). */
29
+ export function scalarReferenceComponent({ scalar, command, packageRoot }) {
30
+ const file = scalar || command === 'dev' ? 'ScalarReference.astro' : 'NoScalarReference.astro';
31
+ return path.join(packageRoot, 'src/components', file);
32
+ }
@@ -0,0 +1,105 @@
1
+ // OpenAPI groups with `openapi.renderer: "scalar"`: Scalar's API reference on
2
+ // one page, at the group's `path`, in the site's layout.
3
+ //
4
+ // generate-api-pages.js works each one out before Astro starts and writes,
5
+ // under writedocsTempDir()/openapi/ (never published):
6
+ // - scalar.json - every such group: `{ group, slug, title, operations }`,
7
+ // `slug` the reference page's address ("api" for "/api"), and per
8
+ // operation the page writedocs still builds for it (`slug`) and its
9
+ // fragment in the reference (`anchor`, lib/scalar-anchors.js);
10
+ // - <path>/reference-document.json - the group's spec, bundled into one
11
+ // document (its own $refs kept, other files' brought in), which the
12
+ // reference page carries inside its HTML (ScalarReference.astro) - never a
13
+ // file of its own, so a group in a protected section stays behind the
14
+ // section's rule;
15
+ // - the reference page itself, generated-docs/<path>.mdx: the title, and a
16
+ // list of the operations - what its .md copy and llms-full.txt say.
17
+ //
18
+ // The per-operation pages are generated as for any OpenAPI group (search,
19
+ // llms.txt, llms-full.txt, MCP and the .md copies are made from them) and
20
+ // stay in the navigation data - so their section, access rule and search
21
+ // space don't change - but [...slug].astro keeps them out of the sidebar
22
+ // and pagination, marks them noindex, sends a reader on to their operation
23
+ // in the reference, and gives search their anchor (scalarOperationTargets()
24
+ // below).
25
+ //
26
+ // Plain JavaScript: read by the CLI, astro.config.mjs and the pages.
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
30
+
31
+ /** The list of the site's Scalar references (JSON). */
32
+ export const scalarReferencesFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'scalar.json');
33
+
34
+ /** A group's bundled spec (JSON), for its reference page. `pathPrefix`: the
35
+ * group's `openapi.path` without its slashes ("api", "v2/api"). */
36
+ export const scalarDocumentFile = (contentDir, pathPrefix) =>
37
+ path.join(writedocsTempDir(contentDir), 'openapi', ...pathPrefix.split('/'), 'reference-document.json');
38
+
39
+ /** `[{ group, slug, title, operations: [{ slug, method, path, anchor }] }]` -
40
+ * empty without any, or before generate-api-pages.js has run. */
41
+ export function readScalarReferences(contentDir) {
42
+ try {
43
+ const list = JSON.parse(fs.readFileSync(scalarReferencesFile(contentDir), 'utf-8'));
44
+ return Array.isArray(list) ? list.filter((r) => typeof r?.slug === 'string' && Array.isArray(r.operations)) : [];
45
+ } catch {
46
+ return [];
47
+ }
48
+ }
49
+
50
+ /** The reference whose page is `slug` (a page's file id), or null. */
51
+ export function scalarReferenceAt(references, slug) {
52
+ return references.find((r) => r.slug === slug) ?? null;
53
+ }
54
+
55
+ /** The address of an operation in its reference, in the site (no basePath):
56
+ * "/api/#tag/pets/GET/pets". */
57
+ export function scalarOperationHref(reference, operation) {
58
+ return `/${reference.slug}/#${operation.anchor}`;
59
+ }
60
+
61
+ /** Whether a sidebar (buildNavTree()'s nodes) would list nothing but the
62
+ * page `slug` - the reference of an API tab, say. Its page then leaves the
63
+ * site's sidebar out, and Scalar's own (its operations) takes its place;
64
+ * otherwise the two stand side by side. */
65
+ export function sidebarListsOnly(nodes, slug) {
66
+ const entries = [];
67
+ const walk = (list) => {
68
+ for (const node of list) {
69
+ if (node.kind === 'group') {
70
+ if (node.pageSlug) entries.push(node.pageSlug);
71
+ walk(node.children ?? []);
72
+ } else {
73
+ entries.push(node.kind === 'page' ? node.slug : node.href);
74
+ }
75
+ }
76
+ };
77
+ walk(nodes);
78
+ return entries.length === 1 && entries[0] === slug;
79
+ }
80
+
81
+ /** Page (file id) -> where its reader goes instead, for every operation page
82
+ * of a Scalar group: `{ href, reference }` - `href` the address in the site
83
+ * ("/api/#tag/pets/GET/pets", no basePath), `reference` the reference's
84
+ * slug. A hand-written page that claims one of the group's operations
85
+ * (frontmatter `openapi`) is in it too: the reference shows that
86
+ * operation. */
87
+ export function scalarOperationTargets(references) {
88
+ const targets = new Map();
89
+ for (const reference of references) {
90
+ for (const operation of reference.operations) {
91
+ targets.set(operation.slug, { href: scalarOperationHref(reference, operation), reference: reference.slug });
92
+ }
93
+ }
94
+ return targets;
95
+ }
96
+
97
+ /** The script that sends a reader from an operation page to `href` (the
98
+ * address with the site's basePath): replace(), so Back skips the page.
99
+ * Only with JavaScript - Scalar's reference needs it too, so a reader
100
+ * without it stays on the operation's own page, which shows everything.
101
+ * Safe inside a <script> (no `<` left). */
102
+ export function scalarRedirectScript(href) {
103
+ const backslash = String.fromCharCode(92);
104
+ return `location.replace(${JSON.stringify(href).replace(/</g, `${backslash}u003c`)});`;
105
+ }