@writedocs/generator 0.16.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.
Files changed (40) hide show
  1. package/astro.config.mjs +43 -3
  2. package/package.json +4 -1
  3. package/src/cli/build.js +39 -3
  4. package/src/cli/dev.js +16 -0
  5. package/src/cli/generate-api-pages.js +94 -3
  6. package/src/cli/run-pagefind.js +67 -22
  7. package/src/cli/write-redirects-file.js +7 -1
  8. package/src/components/ApiReferencePanel.astro +16 -3
  9. package/src/components/NoScalarReference.astro +6 -0
  10. package/src/components/NoScalarTryIt.astro +5 -0
  11. package/src/components/ScalarReference.astro +80 -0
  12. package/src/components/ScalarTryIt.astro +76 -0
  13. package/src/layout/BaseLayout.astro +7 -0
  14. package/src/layout/components/LockMark.astro +28 -0
  15. package/src/layout/components/MobileMenu.astro +4 -0
  16. package/src/layout/components/Sidebar.astro +3 -2
  17. package/src/layout/components/TopBar.astro +9 -0
  18. package/src/lib/config-schema.js +58 -6
  19. package/src/lib/config-schema.ts +75 -8
  20. package/src/lib/config.ts +40 -13
  21. package/src/lib/content-check.js +18 -3
  22. package/src/lib/json-schema-descriptions.js +5 -1
  23. package/src/lib/llms-index.ts +5 -0
  24. package/src/lib/mcp-index.ts +5 -1
  25. package/src/lib/moved-api-pages.js +16 -1
  26. package/src/lib/openapi-render.ts +5 -0
  27. package/src/lib/protected-sections.js +238 -0
  28. package/src/lib/scalar-anchors.js +56 -0
  29. package/src/lib/scalar-document.js +63 -0
  30. package/src/lib/scalar-fetch.js +89 -0
  31. package/src/lib/scalar-reference-alias.js +32 -0
  32. package/src/lib/scalar-reference.js +105 -0
  33. package/src/lib/scalar-theme.js +175 -0
  34. package/src/lib/scalar-try-it-alias.js +31 -0
  35. package/src/pages/[...slug].astro +133 -23
  36. package/src/pages/llms-full.txt.ts +4 -0
  37. package/src/pages/og/[...slug].png.ts +11 -2
  38. package/src/scripts/scalar-reference.ts +151 -0
  39. package/src/scripts/scalar-try-it.ts +145 -0
  40. package/writedocs.schema.json +476 -71
package/astro.config.mjs CHANGED
@@ -44,6 +44,11 @@ import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
44
44
  import { rehypeBasePath } from './src/lib/rehype-base-path.js';
45
45
  import { gitLastModified, newestDate } from './src/lib/last-modified.js';
46
46
  import { readSpecPaths } from './src/lib/project-files.js';
47
+ import { protectedPages } from './src/lib/protected-sections.js';
48
+ import { SCALAR_TRY_IT_ALIAS, SCALAR_OPTIMIZED_DEPS, scalarTryItComponent } from './src/lib/scalar-try-it-alias.js';
49
+ import { SCALAR_REFERENCE_ALIAS, SCALAR_REFERENCE_OPTIMIZED_DEPS, scalarReferenceComponent } from './src/lib/scalar-reference-alias.js';
50
+ import { readScalarReferences, scalarOperationTargets } from './src/lib/scalar-reference.js';
51
+ import { fileIdForPath } from './src/lib/pages.js';
47
52
  import {
48
53
  loadDocsConfig,
49
54
  resolveCodeblockTheme,
@@ -81,6 +86,9 @@ const dependencyRoot = nodeModulesAt === -1 ? packageRoot : packageRoot.slice(0,
81
86
  // with how every other consumer of it in this codebase behaves - no
82
87
  // special-casing needed.
83
88
  const docsConfig = loadDocsConfig(contentDir);
89
+ // Whether an OpenAPI group shows Scalar's reference: generate-api-pages.js
90
+ // has listed it by now (it runs before Astro).
91
+ const usesScalarReference = readScalarReferences(contentDir).length > 0;
84
92
  // resolveCodeblockTheme() is the single source of truth for the
85
93
  // github-light/github-dark fallback - also used by ApiReferencePanel.astro
86
94
  // for its own separate <Code/> usages (which don't inherit
@@ -166,6 +174,12 @@ function collectNoindexIds(rootContentDir) {
166
174
  const pageIds = [];
167
175
  // When each page last changed, for <lastmod> - see lib/last-modified.js.
168
176
  const fileDates = gitLastModified(rootContentDir);
177
+ // A protected page (lib/protected-sections.js) is noindex, whatever its
178
+ // frontmatter says - and never listed in a public file.
179
+ const protectedRules = protectedPages(docsConfig.navigation);
180
+ // The operation pages of a Scalar group are noindex too - the reference is
181
+ // the page to index (lib/scalar-reference.js).
182
+ const scalarOperations = scalarOperationTargets(readScalarReferences(rootContentDir));
169
183
 
170
184
  for (const relativeId of findAllPages(rootContentDir)) {
171
185
  const file = path.join(rootContentDir, relativeId);
@@ -183,7 +197,8 @@ function collectNoindexIds(rootContentDir) {
183
197
  // canonical URL is another address (the sitemap lists canonical ones).
184
198
  const canonical = data?.seo?.canonical ?? data?.canonical;
185
199
  const pagePath = pageId === 'index' ? '/' : `/${pageId}/`;
186
- if (!frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
200
+ const alwaysNoindex = protectedRules.has(fileIdForPath(relativeId)) || scalarOperations.has(fileIdForPath(relativeId));
201
+ if (!alwaysNoindex && !frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
187
202
  ids.add(pageId);
188
203
  }
189
204
  // Generated OpenAPI stub pages always set an explicit `slug` (see
@@ -197,7 +212,8 @@ function collectNoindexIds(rootContentDir) {
197
212
  // A generated API page changes when a spec does. Which spec it came
198
213
  // from isn't recorded on the page, so it gets the newest of them.
199
214
  if (data?.slug && specsChanged) lastModifiedById.set(normalizeEntryId(data.slug), specsChanged);
200
- if (frontmatterNoindex(data) && data.slug) ids.add(normalizeEntryId(data.slug));
215
+ const generatedId = normalizeEntryId(data?.slug ?? '');
216
+ if ((frontmatterNoindex(data) || protectedRules.has(generatedId) || scalarOperations.has(generatedId)) && data.slug) ids.add(generatedId);
201
217
  }
202
218
  if (!rootIsPage) ids.add('index');
203
219
  // Folder addresses with no page of their own redirect to one under them
@@ -569,8 +585,17 @@ export default defineConfig({
569
585
  // as it is, and its CommonJS dependencies failed in the browser ("dayjs
570
586
  // ... does not provide an export named 'default'"): diagrams stayed as
571
587
  // text in dev, while builds were fine. Naming it here prepares it always.
588
+ // Scalar's "Try it" (api.playground "scalar") too: found only on the first
589
+ // click's import(), it made Vite optimize it then and reload the page,
590
+ // which lost the click. Only for a site that uses it - the others don't
591
+ // pay for preparing it. Scalar's API reference (an OpenAPI group's
592
+ // `renderer: "scalar"`) the same way, on its page's first load.
572
593
  optimizeDeps: {
573
- include: ['mermaid'],
594
+ include: [
595
+ 'mermaid',
596
+ ...(docsConfig.api.playground === 'scalar' ? SCALAR_OPTIMIZED_DEPS : []),
597
+ ...(usesScalarReference ? SCALAR_REFERENCE_OPTIMIZED_DEPS : []),
598
+ ],
574
599
  },
575
600
  resolve: {
576
601
  alias: [
@@ -601,6 +626,21 @@ export default defineConfig({
601
626
  find: 'writedocs/components',
602
627
  replacement: path.join(packageRoot, 'packages/components/src/index.ts'),
603
628
  },
629
+ // Scalar's "Try it" (ApiReferencePanel.astro): the real component
630
+ // only when writedocs.json asks for it (or in dev) - otherwise an
631
+ // empty one, so Scalar isn't bundled into a site that doesn't use it
632
+ // (lib/scalar-try-it-alias.js).
633
+ {
634
+ find: SCALAR_TRY_IT_ALIAS,
635
+ replacement: scalarTryItComponent({ playground: docsConfig.api.playground, command: process.env.WRITEDOCS_COMMAND, packageRoot }),
636
+ },
637
+ // Scalar's API reference ([...slug].astro), the page of an OpenAPI
638
+ // group with `renderer: "scalar"`: the real component only when a
639
+ // group asks for it (or in dev) - lib/scalar-reference-alias.js.
640
+ {
641
+ find: SCALAR_REFERENCE_ALIAS,
642
+ replacement: scalarReferenceComponent({ scalar: usesScalarReference, command: process.env.WRITEDOCS_COMMAND, packageRoot }),
643
+ },
604
644
  ],
605
645
  },
606
646
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -69,6 +69,9 @@
69
69
  "@iconify-json/tabler": "1.2.38",
70
70
  "@mdx-js/mdx": "3.1.1",
71
71
  "@resvg/resvg-wasm": "2.6.2",
72
+ "@scalar/api-client": "3.25.0",
73
+ "@scalar/api-reference": "1.78.0",
74
+ "@scalar/workspace-store": "0.71.0",
72
75
  "@shikijs/transformers": "4.4.3",
73
76
  "@tailwindcss/vite": "4.3.3",
74
77
  "astro": "7.2.9",
package/src/cli/build.js CHANGED
@@ -20,6 +20,7 @@ import { reportApiPages } from './api-pages-output.js';
20
20
  import { findDraftPages } from '../lib/pages.js';
21
21
  import { draftWarnings } from '../lib/drafts.js';
22
22
  import { createJsonLocator } from '../lib/config-schema.js';
23
+ import { usesAccess, accessRules, accessMap, ACCESS_MAP_FILE, ACCESS_NEEDS_PLATFORM } from '../lib/protected-sections.js';
23
24
 
24
25
  /** `drafts` (`writedocs build --drafts`): draft pages are part of the site -
25
26
  * marked, noindex, out of the sitemap, llms.txt and the MCP index, the way
@@ -72,12 +73,17 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
72
73
  const ogCardsFile = path.join(writedocsTempDir(contentDir), 'og-cards.json');
73
74
  fs.mkdirSync(path.dirname(ogCardsFile), { recursive: true });
74
75
  fs.rmSync(ogCardsFile, { force: true });
76
+ // The protected addresses ([...slug].astro lists them here, as
77
+ // `{ slug, rule }` - lib/protected-sections.js). Removed first for the same
78
+ // reason.
79
+ const accessFile = path.join(writedocsTempDir(contentDir), 'access-routes.json');
80
+ fs.rmSync(accessFile, { force: true });
75
81
  const { exited } = runAstro('build', {
76
82
  packageRoot,
77
83
  contentDir,
78
84
  // WRITEDOCS_DRAFTS: draftsIncluded() in lib/pages.js - set either way, so
79
85
  // one left in the shell's environment can't decide it.
80
- env: { WRITEDOCS_OG_CARDS_FILE: ogCardsFile, WRITEDOCS_DRAFTS: drafts ? '1' : '' },
86
+ env: { WRITEDOCS_OG_CARDS_FILE: ogCardsFile, WRITEDOCS_ACCESS_FILE: accessFile, WRITEDOCS_DRAFTS: drafts ? '1' : '' },
81
87
  onEvent(event) {
82
88
  if (verbose) {
83
89
  const line = verboseLine(event);
@@ -136,6 +142,10 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
136
142
  // Without one, siteDir is distDir, and every step below is what it was.
137
143
  const basePath = normalizeBasePath(siteConfig.basePath);
138
144
  const siteDir = siteDirFor(distDir, basePath);
145
+ // Protected sections are protected by the WriteDocs platform only
146
+ // (lib/protected-sections.js) - said every time, so nobody hosting the
147
+ // build elsewhere takes them for private.
148
+ if (usesAccess(siteConfig.navigation)) addWarning(null, ACCESS_NEEDS_PLATFORM);
139
149
  // Astro just wrote its actual output to writedocsBuildStagingDir()
140
150
  // (astro.config.mjs's own `outDir`), not distDir directly - see that
141
151
  // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
@@ -185,7 +195,12 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
185
195
  // ever produce client-side meta-refresh pages (see write-redirects-file.js)
186
196
  // - this turns those into real instant edge redirects on hosts that read
187
197
  // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
188
- writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
198
+ // A folder redirect, or a generated API page's old address
199
+ // (lib/moved-api-pages.js), that leads to a protected page stays a page,
200
+ // behind its rule - not an edge redirect anyone can follow.
201
+ const protectedRoutes = fs.existsSync(accessFile) ? JSON.parse(fs.readFileSync(accessFile, 'utf8')) : [];
202
+ const protectedFolders = new Set(protectedRoutes.map((route) => `/${route.slug}/`));
203
+ writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath, protectedFolders });
189
204
  // Every other host follows Astro's redirect pages - rewritten so the
190
205
  // reader never sees one (rewrite-redirect-pages.js).
191
206
  rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors, appearance: siteConfig.styles?.appearance });
@@ -198,8 +213,9 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
198
213
  if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
199
214
 
200
215
  const indexing = step('Indexing search');
216
+ let searchSpaces = [];
201
217
  try {
202
- await runPagefind(siteDir, { packageRoot });
218
+ ({ spaces: searchSpaces } = await runPagefind(siteDir, { packageRoot }));
203
219
  } catch (err) {
204
220
  indexing.fail('Search indexing failed');
205
221
  log.line();
@@ -208,6 +224,26 @@ export async function runBuild({ contentDir, packageRoot, verbose = false, draft
208
224
  }
209
225
  indexing.succeed('Indexed search');
210
226
 
227
+ // The map the WriteDocs platform protects the site by: each access rule
228
+ // and every path it serves only to the rule's readers
229
+ // (lib/protected-sections.js, docs/dev/docs/protected-sections.mdx). At
230
+ // the root of dist/, outside a basePath's folder - the platform never
231
+ // serves /.writedocs/. Without `access` in writedocs.json, no file, and
232
+ // dist/ is what it was.
233
+ if (usesAccess(siteConfig.navigation)) {
234
+ const map = accessMap({
235
+ rules: accessRules(siteConfig.navigation),
236
+ routes: protectedRoutes,
237
+ spaces: searchSpaces,
238
+ basePath,
239
+ exists: (rel) => fs.existsSync(path.join(siteDir, ...rel.split('/'))),
240
+ });
241
+ const mapFile = path.join(distDir, ...ACCESS_MAP_FILE.split('/'));
242
+ fs.mkdirSync(path.dirname(mapFile), { recursive: true });
243
+ fs.writeFileSync(mapFile, `${JSON.stringify(map, null, 2)}
244
+ `);
245
+ }
246
+
211
247
  if (warnings.length) {
212
248
  log.line();
213
249
  log.warn(plural(warnings.length, 'warning'));
package/src/cli/dev.js CHANGED
@@ -10,6 +10,7 @@ import { showUpdateNotice } from './update-check.js';
10
10
  import { shouldOpenBrowser, openBrowser } from './open-browser.js';
11
11
  import { watchPageList } from './page-list-watch.js';
12
12
  import { readConfigText } from '../lib/config-file.js';
13
+ import { usesAccess, ACCESS_IN_DEV } from '../lib/protected-sections.js';
13
14
  import { normalizeBasePath } from '../lib/base-path.js';
14
15
  import { writeDevOpenApiState } from '../lib/openapi-dev-status.js';
15
16
 
@@ -143,6 +144,12 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
143
144
  log.line();
144
145
  log.line(color.dim(' Edit any page and the preview updates. Press Ctrl+C to stop.'));
145
146
  log.line();
147
+ // Protected sections (lib/protected-sections.js) are the
148
+ // platform's to protect - here every page opens.
149
+ if (configUsesAccess(contentDir)) {
150
+ log.info(ACCESS_IN_DEV);
151
+ log.line();
152
+ }
146
153
  // `dev` runs until Ctrl+C - the notice goes under the ready screen,
147
154
  // not after the command like everywhere else.
148
155
  showUpdateNotice();
@@ -267,3 +274,12 @@ export async function runDev({ contentDir, packageRoot, port, verbose = false, o
267
274
  }
268
275
  throw new CliExit(code || 1);
269
276
  }
277
+
278
+ /** Whether writedocs.json names an access rule - false when it can't be read. */
279
+ function configUsesAccess(contentDir) {
280
+ try {
281
+ return usesAccess(JSON.parse(readConfigText(contentDir)).navigation);
282
+ } catch {
283
+ return false;
284
+ }
285
+ }
@@ -8,8 +8,10 @@ import { findAllPages } from '../lib/pages.js';
8
8
  import { projectIgnore } from '../lib/project-ignore.js';
9
9
  import { readConfigText } from '../lib/config-file.js';
10
10
  import { HTTP_METHODS, collectOpenApiGroups } from '../lib/openapi-spec.js';
11
- import { operationMetaDescription } from '../lib/meta-description.js';
11
+ import { operationMetaDescription, plainLine, truncateAtWord } from '../lib/meta-description.js';
12
12
  import { movedApiPagesFile, untaggedRedirects } from '../lib/moved-api-pages.js';
13
+ import { scalarReferencesFile, scalarDocumentFile } from '../lib/scalar-reference.js';
14
+ import { scalarOperationAnchor } from '../lib/scalar-anchors.js';
13
15
  import { canonicalPath } from '../lib/canonical-path.js';
14
16
 
15
17
 
@@ -158,6 +160,21 @@ function resolveSecurity(operation, spec) {
158
160
  .filter((s) => s.type);
159
161
  }
160
162
 
163
+ /** The operation's security requirements as the spec wrote them (each entry
164
+ * an alternative, its keys required together, with their scopes) and the
165
+ * schemes they name, under their own names - what an OpenAPI document needs
166
+ * to say the same thing again (lib/scalar-document.js). `security` above
167
+ * flattens both into one list for writedocs' own playground. */
168
+ function securityAsWritten(operation, spec) {
169
+ const requirements = operation.security ?? spec.security ?? [];
170
+ const schemes = spec.components?.securitySchemes ?? {};
171
+ const named = {};
172
+ for (const req of requirements) {
173
+ for (const name of Object.keys(req)) if (schemes[name]?.type) named[name] = schemes[name];
174
+ }
175
+ return { securityRequirements: requirements, securitySchemes: named };
176
+ }
177
+
161
178
  function buildOperations(spec) {
162
179
  const operations = [];
163
180
  for (const [urlPath, pathItem] of Object.entries(spec.paths ?? {})) {
@@ -177,6 +194,7 @@ function buildOperations(spec) {
177
194
  responses: operation.responses ?? {},
178
195
  servers: operation.servers ?? spec.servers ?? [],
179
196
  security: resolveSecurity(operation, spec),
197
+ ...securityAsWritten(operation, spec),
180
198
  });
181
199
  }
182
200
  }
@@ -224,7 +242,7 @@ async function dereferenceSpec(specPath, sources) {
224
242
  * in the same writedocs.json never collide with each other on disk, exactly
225
243
  * as they won't collide in the URL space either (both keyed off the
226
244
  * same `path` value). Nothing is written here - see writeGeneratedFiles(). */
227
- async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources }) {
245
+ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources, references, pageIds }) {
228
246
  const pathPrefix = normalizePathPrefix(group.openapi.path);
229
247
  const specPath = path.resolve(contentDir, group.openapi.src);
230
248
  if (!fs.existsSync(specPath)) {
@@ -233,6 +251,21 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
233
251
  `(resolved to ${specPath}), which doesn't exist`
234
252
  );
235
253
  }
254
+ // Scalar's reference (lib/scalar-reference.js) is a page of its own, at the
255
+ // group's path - which then can't be the site's root, nor a page's.
256
+ const scalar = group.openapi.renderer === 'scalar';
257
+ if (scalar && !pathPrefix) {
258
+ throw new Error(
259
+ `[writedocs] writedocs.json's "${group.group}" group has openapi.renderer "scalar" and openapi.path "${group.openapi.path}" - ` +
260
+ 'the reference is a page at that path, so give it one of its own, like "/api".'
261
+ );
262
+ }
263
+ if (scalar && pageIds.has(pathPrefix)) {
264
+ throw new Error(
265
+ `[writedocs] writedocs.json's "${group.group}" group has openapi.renderer "scalar" - its reference is the page at /${pathPrefix}/, ` +
266
+ 'and a page of the project is already there. Move that page or give the group another openapi.path.'
267
+ );
268
+ }
236
269
 
237
270
  const spec = await dereferenceSpec(specPath, sources);
238
271
  const operations = buildOperations(spec);
@@ -241,6 +274,7 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
241
274
 
242
275
  const manifest = [];
243
276
  const untagged = [];
277
+ const referenceOperations = [];
244
278
  for (const operation of operations) {
245
279
  const key = operationKey(operation.method, operation.path);
246
280
  const overrideSlug = overrides.get(key);
@@ -282,6 +316,7 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
282
316
  moves.slugs.add(slug);
283
317
 
284
318
  manifest.push({ slug, method: operation.method, path: operation.path, tags: operation.tags, title, generated });
319
+ if (scalar) referenceOperations.push({ slug, method: operation.method, path: operation.path, title, anchor: scalarOperationAnchor(operation) });
285
320
 
286
321
  const opFile = path.join(openapiOutDir, 'operations', operationFileName(operation.method, operation.path));
287
322
  files.set(opFile, operationJson(operation));
@@ -289,6 +324,17 @@ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, o
289
324
 
290
325
  files.set(path.join(openapiOutDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
291
326
  if (untagged.length) moves.untagged.push({ pathPrefix, moved: untagged });
327
+ if (scalar) {
328
+ const title = spec.info?.title?.trim() || group.group;
329
+ // The spec as its author wrote it, in one document: $refs inside it stay
330
+ // (Scalar resolves them, and the page stays the spec's size), $refs to
331
+ // other files are brought in - the reader's browser can't fetch those.
332
+ const document = await new SwaggerParser().bundle(specPath);
333
+ files.set(scalarDocumentFile(contentDir, pathPrefix), JSON.stringify(document));
334
+ files.set(path.join(generatedDocsDir, `${pathPrefix}.mdx`), referencePage({ title, spec, slug: pathPrefix, operations: referenceOperations }));
335
+ moves.slugs.add(pathPrefix);
336
+ references.push({ group: group.group, slug: pathPrefix, title, operations: referenceOperations });
337
+ }
292
338
  summary.groups.push({ group: group.group, src: group.openapi.src, operations: operations.length });
293
339
  }
294
340
 
@@ -389,9 +435,14 @@ export async function planApiPages({ contentDir, drafts }) {
389
435
  // Absolute path -> content: everything the two folders will hold.
390
436
  const files = new Map();
391
437
  const sources = new Set();
438
+ // Groups shown as Scalar's reference (lib/scalar-reference.js), and the
439
+ // addresses of the project's own pages - a reference can't take one.
440
+ const references = [];
441
+ const pageIds = groups.some((g) => g.openapi.renderer === 'scalar') ? projectPageIds(contentDir, drafts) : new Set();
392
442
  for (const group of groups) {
393
- await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources });
443
+ await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves, files, sources, references, pageIds });
394
444
  }
445
+ if (references.length) files.set(scalarReferencesFile(contentDir), JSON.stringify(references, null, 2));
395
446
  const moved = moves.untagged.flatMap(({ pathPrefix, moved: list }) => untaggedRedirects(pathPrefix, list, moves.slugs));
396
447
  if (moved.length) files.set(movedApiPagesFile(contentDir), JSON.stringify(moved, null, 2));
397
448
 
@@ -408,6 +459,46 @@ export async function planApiPages({ contentDir, drafts }) {
408
459
  return { summary, files, roots };
409
460
  }
410
461
 
462
+ /** The addresses (file ids) of the project's own pages: its path without the
463
+ * extension or a trailing /index, or its frontmatter `slug`. */
464
+ function projectPageIds(contentDir, drafts) {
465
+ const ids = new Set();
466
+ for (const rel of findAllPages(contentDir, { drafts })) {
467
+ ids.add(rel.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
468
+ try {
469
+ const { data } = matter(fs.readFileSync(path.join(contentDir, rel), 'utf-8'));
470
+ if (typeof data?.slug === 'string') ids.add(data.slug.replace(/^\/+|\/+$/g, ''));
471
+ } catch {}
472
+ }
473
+ return ids;
474
+ }
475
+
476
+ /** Text for a Markdown link's label inside MDX: what MDX or Markdown would
477
+ * read as syntax is escaped. */
478
+ function markdownText(text) {
479
+ return String(text).replace(/[\\`*_[\]{}<>|#]/g, (c) => `\\${c}`);
480
+ }
481
+
482
+ /** The reference page of a Scalar group: its title, the spec's description
483
+ * as the search-engine one, and a list of the operations linking to their
484
+ * own pages - not shown (the page shows Scalar's reference), but what its
485
+ * .md copy and llms-full.txt carry. */
486
+ function referencePage({ title, spec, slug, operations }) {
487
+ const description = truncateAtWord(plainLine(spec.info?.description)) || `The ${title} reference.`;
488
+ const lines = operations.map((op) => `- [${markdownText(op.title)}](/${op.slug}/) - \`${op.method} ${op.path.replace(/`/g, '')}\``);
489
+ return [
490
+ '---',
491
+ `title: ${JSON.stringify(title)}`,
492
+ `slug: ${JSON.stringify(slug)}`,
493
+ 'seo:',
494
+ ` description: ${JSON.stringify(description)}`,
495
+ '---',
496
+ '',
497
+ ...lines,
498
+ '',
499
+ ].join('\n');
500
+ }
501
+
411
502
  function listFiles(dir) {
412
503
  let entries;
413
504
  try {
@@ -60,25 +60,45 @@ function resolvePagefindBin(packageRoot) {
60
60
  * result (/docs/pagefind/ -> "/docs/a/"). Adding the base here too gave
61
61
  * results with it twice.
62
62
  */
63
+ /**
64
+ * Returns the ids of the search spaces it wrote, each in
65
+ * pagefind-spaces/<id>/ - the build lists a protected one's folder in
66
+ * dist/.writedocs/access.json (lib/protected-sections.js).
67
+ */
63
68
  export async function runPagefind(siteDir, { packageRoot }) {
69
+ // With a hidden or protected space, or a page whose result leads elsewhere
70
+ // - the operation page of a Scalar group, whose result is its operation in
71
+ // the reference (lib/scalar-reference.js) - the indexes are written by
72
+ // Pagefind's Node API, which takes a result's address; the CLI only knows
73
+ // files. Without either, the CLI indexes the site, as ever.
64
74
  const groups = searchSpaces(siteDir);
65
- if (groups) return indexBySpace(siteDir, packageRoot, groups);
66
- return indexWholeSite(siteDir, packageRoot);
75
+ if (groups) {
76
+ await indexBySpace(siteDir, packageRoot, groups);
77
+ return { spaces: [...groups.spaces.keys()] };
78
+ }
79
+ await indexWholeSite(siteDir, packageRoot);
80
+ return { spaces: [] };
67
81
  }
68
82
 
69
- // Pages under a hidden navigation item name their search space in their
70
- // markup ([...slug].astro, lib/hidden-sections.js).
83
+ // Pages under a hidden or a protected navigation item name their search
84
+ // space in their markup ([...slug].astro, lib/hidden-sections.js,
85
+ // lib/protected-sections.js).
71
86
  const SPACE = /data-wd-search-space="([^"]+)"/;
72
87
  const SEARCH_PUBLIC = /data-wd-search-public="true"/;
88
+ const SEARCH_URL = /data-wd-search-url="([^"]+)"/;
73
89
 
74
90
  /** The site's pages by search space - `{ public, spaces }` - or null when
75
- * no page is in a hidden space (the whole site is one index, as ever).
91
+ * no page is in a hidden or protected space and none has a result address
92
+ * of its own (the whole site is one index, as ever).
76
93
  * Only pages Pagefind would index: those with a data-pagefind-body. A
77
- * page is `{ rel }`, its path in the site with forward slashes.
94
+ * page is `{ rel }`, its path in the site with forward slashes, and `url`
95
+ * when its result is to lead elsewhere (data-wd-search-url, an address in
96
+ * the site: [...slug].astro writes it on a Scalar group's operation pages).
78
97
  * Exported for scripts/search-spaces.test.js. */
79
98
  export function searchSpaces(siteDir) {
80
99
  const publicPages = [];
81
100
  const spaces = new Map();
101
+ let ownUrls = false;
82
102
  const walk = (dir) => {
83
103
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
84
104
  const full = path.join(dir, entry.name);
@@ -94,6 +114,11 @@ export function searchSpaces(siteDir) {
94
114
  // content here ran the CLI out of memory on a site with 1.7 GiB of
95
115
  // HTML - and most sites have no hidden space, so none of it was used.
96
116
  const page = { rel: path.relative(siteDir, full).split(path.sep).join('/') };
117
+ const url = SEARCH_URL.exec(content)?.[1];
118
+ if (url) {
119
+ page.url = decodeAttribute(url);
120
+ ownUrls = true;
121
+ }
97
122
  const space = SPACE.exec(content)?.[1];
98
123
  if (!space) {
99
124
  publicPages.push(page);
@@ -106,15 +131,40 @@ export function searchSpaces(siteDir) {
106
131
  }
107
132
  };
108
133
  walk(siteDir);
109
- return spaces.size ? { public: publicPages, spaces } : null;
134
+ return spaces.size || ownUrls ? { public: publicPages, spaces } : null;
110
135
  }
111
136
 
112
- /** One index for the public pages (dist/pagefind/) and one per hidden
113
- * space (dist/pagefind-spaces/<id>/) - so the public search never finds a
114
- * hidden page, and a hidden space's search finds only its own pages, plus
115
- * the public ones when it sets `searchPublic`. src/scripts/search.ts loads
116
- * the index of the page's space. */
137
+ /** An attribute's value as written by Astro, unescaped. */
138
+ function decodeAttribute(value) {
139
+ return value.replace(/&(quot|#34|#39|lt|gt|amp);/g, (_, name) => ({ quot: '"', '#34': '"', '#39': "'", lt: '<', gt: '>', amp: '&' })[name]);
140
+ }
141
+
142
+ /** One index for the public pages (dist/pagefind/) and one per hidden or
143
+ * protected space (dist/pagefind-spaces/<id>/) - so the public search never
144
+ * finds a hidden or protected page, and a space's search finds only its own
145
+ * pages, plus the public ones when it sets `searchPublic`. A protected
146
+ * space holds one access rule's pages only (searchSpaceOf() in
147
+ * lib/protected-sections.js), so its folder is behind that rule.
148
+ * src/scripts/search.ts loads the index of the page's space. A site with no
149
+ * space but pages with their own result address gets the public index
150
+ * alone, written the same way. */
117
151
  async function indexBySpace(siteDir, packageRoot, groups) {
152
+ const { pagefind, write } = await nodeIndexer(siteDir, packageRoot);
153
+ try {
154
+ await write(groups.public, path.join(siteDir, 'pagefind'), 'public pages');
155
+ for (const [id, space] of groups.spaces) {
156
+ const pages = space.searchPublic ? [...space.pages, ...groups.public] : space.pages;
157
+ await write(pages, path.join(siteDir, 'pagefind-spaces', id), `search space ${id}`);
158
+ }
159
+ } finally {
160
+ await pagefind.close();
161
+ }
162
+ }
163
+
164
+ /** Pagefind's Node API, and a function writing one index of `pages`: each
165
+ * added by its file (Pagefind makes its address from the path, as the CLI
166
+ * does) or, with a `url`, at that address. */
167
+ async function nodeIndexer(siteDir, packageRoot) {
118
168
  const pagefind = await import(pathToFileURL(path.join(findPagefindDir(packageRoot), 'lib', 'index.js')).href);
119
169
  const check = (result, what) => {
120
170
  if (result.errors?.length) throw new Error(`pagefind (${what}): ${result.errors.join('; ')}`);
@@ -122,18 +172,13 @@ async function indexBySpace(siteDir, packageRoot, groups) {
122
172
  };
123
173
  const write = async (pages, outputPath, what) => {
124
174
  const { index } = check(await pagefind.createIndex({}), what);
125
- for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8') }), `${what}: ${page.rel}`);
175
+ for (const page of pages) {
176
+ const content = fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8');
177
+ check(await index.addHTMLFile(page.url ? { url: page.url, content } : { sourcePath: page.rel, content }), `${what}: ${page.rel}`);
178
+ }
126
179
  check(await index.writeFiles({ outputPath }), what);
127
180
  };
128
- try {
129
- await write(groups.public, path.join(siteDir, 'pagefind'), 'public pages');
130
- for (const [id, space] of groups.spaces) {
131
- const pages = space.searchPublic ? [...space.pages, ...groups.public] : space.pages;
132
- await write(pages, path.join(siteDir, 'pagefind-spaces', id), `hidden space ${id}`);
133
- }
134
- } finally {
135
- await pagefind.close();
136
- }
181
+ return { pagefind, write };
137
182
  }
138
183
 
139
184
  function indexWholeSite(siteDir, packageRoot) {
@@ -41,7 +41,11 @@ import { withBase } from '../lib/base-path.js';
41
41
  // the rules name, source and destination - the host matches the full path
42
42
  // it was asked for - and adds `/ -> /docs/` for whoever opens the root of
43
43
  // the address directly.
44
- export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, basePath = '' } = {}) {
44
+ /** `protectedFolders` - the protected addresses ("/partners/"), among them
45
+ * every folder redirect and moved API page (lib/moved-api-pages.js) that
46
+ * leads to a protected page (lib/protected-sections.js): their redirects
47
+ * are left out here, so each stays a page behind the page's access rule. */
48
+ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, basePath = '', protectedFolders = new Set() } = {}) {
45
49
  const writedocsJson = JSON.parse(readConfigText(contentDir));
46
50
  const redirects = writedocsJson.redirects ?? [];
47
51
  const lines = [];
@@ -68,6 +72,7 @@ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, base
68
72
  // as requested.
69
73
  for (const { source, destination } of readMovedApiPages(contentDir)) {
70
74
  if (redirects.some((r) => r.source.replace(/\/+$/, '') === source)) continue;
75
+ if (protectedFolders.has(`${source}/`)) continue;
71
76
  lines.push(`${at(source)} ${at(destination)} 301`, `${at(source)}/ ${at(destination)} 301`);
72
77
  }
73
78
 
@@ -100,6 +105,7 @@ export function writeRedirectsFile(distDir, contentDir, { outDir = distDir, base
100
105
  // automatic folder redirects. (Read before rewrite-redirect-pages.js makes
101
106
  // every redirect page go at once.)
102
107
  for (const { url, target } of temporaryRedirectPages(distDir)) {
108
+ if (protectedFolders.has(url)) continue;
103
109
  lines.push(`${at(url)} ${target} 302`, `${at(url).replace(/\/$/, '')} ${target} 302`);
104
110
  }
105
111
 
@@ -18,6 +18,10 @@ import {
18
18
  import { parseOpenApiRef } from '../lib/openapi-ref.js';
19
19
  import { loadDocsConfig, resolveCodeblockTheme } from '../lib/config';
20
20
  import ApiLangSelect from './ApiLangSelect.astro';
21
+ // ScalarTryIt.astro when writedocs.json asks for Scalar, an empty component
22
+ // otherwise - an alias, so Scalar isn't bundled into other sites
23
+ // (lib/scalar-try-it-alias.js).
24
+ import ScalarTryIt from 'writedocs/scalar-try-it';
21
25
 
22
26
  interface Props {
23
27
  operation: string;
@@ -64,6 +68,11 @@ const SNIPPET_THEMES = resolveCodeblockTheme(docsConfig);
64
68
  // Whether the Send button in the Try-it modal routes its request through
65
69
  // writedocs' CORS proxy - see PROXY_BASE_URL in the <script> below.
66
70
  const proxyEnabled = docsConfig.api.proxy;
71
+ // writedocs.json's `api.playground`: "scalar" makes the Try button open
72
+ // Scalar's API client (ScalarTryIt.astro) instead of the modal below, which
73
+ // isn't rendered then. The button gets another data-role, so this file's own
74
+ // script (unchanged) never binds it.
75
+ const scalarPlayground = docsConfig.api.playground === 'scalar';
67
76
 
68
77
  // "METHOD /path", or Mintlify's "spec.json METHOD /path" - see lib/openapi-ref.js.
69
78
  const ref = parseOpenApiRef(operation);
@@ -162,14 +171,14 @@ const paramsJson = JSON.stringify(op?.parameters ?? []);
162
171
  const securityJson = JSON.stringify(op?.security ?? []);
163
172
  ---
164
173
 
165
- {op && (
174
+ {op && (<Fragment>
166
175
  <div class="wd-api-panel" data-api-panel data-method={op.method} data-path={op.path}>
167
176
  <div class="wd-api-card">
168
177
  <div class="wd-api-card-head">
169
178
  <span class="wd-api-card-label">Request</span>
170
179
  <div class="wd-api-card-actions">
171
180
  <ApiLangSelect options={langOptions} rolePrefix="lang" ariaLabel="Language" />
172
- <button type="button" class="wd-api-try-inline" data-role="open-modal">
181
+ <button type="button" class="wd-api-try-inline" data-role={scalarPlayground ? 'open-scalar' : 'open-modal'}>
173
182
  Try <span class="wd-api-try-icon" aria-hidden="true">&#9656;</span>
174
183
  </button>
175
184
  </div>
@@ -219,6 +228,9 @@ const securityJson = JSON.stringify(op?.security ?? []);
219
228
  )}
220
229
  </div>
221
230
 
231
+ {scalarPlayground && <ScalarTryIt op={op} proxy={proxyEnabled} title={docsConfig.name} />}
232
+
233
+ {!scalarPlayground && (
222
234
  <div class="wd-api-modal-overlay" data-role="modal-overlay" hidden>
223
235
  <div class="wd-api-modal" role="dialog" aria-modal="true" aria-label="Try it">
224
236
  <div class="wd-api-modal-head">
@@ -410,7 +422,8 @@ const securityJson = JSON.stringify(op?.security ?? []);
410
422
  </div>
411
423
  </div>
412
424
  </div>
413
- )}
425
+ )}
426
+ </Fragment>)}
414
427
 
415
428
  <style is:global>
416
429
  /* Widens the shared .wd-toc-col (defined in BaseLayout.astro) only on
@@ -0,0 +1,6 @@
1
+ ---
2
+ // What `writedocs/scalar-reference` resolves to in a build with no OpenAPI
3
+ // group set to `renderer: "scalar"` (lib/scalar-reference-alias.js):
4
+ // nothing - no markup, no script, no style - so Scalar stays out of that
5
+ // build.
6
+ ---
@@ -0,0 +1,5 @@
1
+ ---
2
+ // What `writedocs/scalar-try-it` resolves to in a build without
3
+ // `api.playground: "scalar"` (lib/scalar-try-it-alias.js): nothing - no
4
+ // markup, no script, no style - so Scalar stays out of that build.
5
+ ---