@writedocs/generator 0.10.18 → 0.10.19

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.10.18",
3
+ "version": "0.10.19",
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": {
@@ -54,6 +54,8 @@ export function runAstro(command, { packageRoot, contentDir, port, onEvent }) {
54
54
  // fileIdForEntry() can resolve it back into a docs/-relative file id
55
55
  // - see that function for why.
56
56
  WRITEDOCS_PACKAGE_ROOT: packageRoot,
57
+ // 'dev' or 'build' - lib/build-memo.js keeps per-build results only in a build.
58
+ WRITEDOCS_COMMAND: command,
57
59
  ...(port ? { WRITEDOCS_PORT: String(port) } : {}),
58
60
  },
59
61
  });
@@ -67,8 +67,10 @@ const SEARCH_PUBLIC = /data-wd-search-public="true"/;
67
67
 
68
68
  /** The site's pages by search space - `{ public, spaces }` - or null when
69
69
  * no page is in a hidden space (the whole site is one index, as ever).
70
- * Only pages Pagefind would index: those with a data-pagefind-body. */
71
- function searchSpaces(siteDir) {
70
+ * Only pages Pagefind would index: those with a data-pagefind-body. A
71
+ * page is `{ rel }`, its path in the site with forward slashes.
72
+ * Exported for scripts/search-spaces.test.js. */
73
+ export function searchSpaces(siteDir) {
72
74
  const publicPages = [];
73
75
  const spaces = new Map();
74
76
  const walk = (dir) => {
@@ -81,7 +83,11 @@ function searchSpaces(siteDir) {
81
83
  if (!entry.name.endsWith('.html')) continue;
82
84
  const content = fs.readFileSync(full, 'utf8');
83
85
  if (!content.includes('data-pagefind-body')) continue;
84
- const page = { rel: path.relative(siteDir, full).split(path.sep).join('/'), content };
86
+ // The page's address only, not its HTML: a page is read again when
87
+ // it's added to an index (indexBySpace()). Keeping every page's
88
+ // content here ran the CLI out of memory on a site with 1.7 GiB of
89
+ // HTML - and most sites have no hidden space, so none of it was used.
90
+ const page = { rel: path.relative(siteDir, full).split(path.sep).join('/') };
85
91
  const space = SPACE.exec(content)?.[1];
86
92
  if (!space) {
87
93
  publicPages.push(page);
@@ -110,7 +116,7 @@ async function indexBySpace(siteDir, packageRoot, groups) {
110
116
  };
111
117
  const write = async (pages, outputPath, what) => {
112
118
  const { index } = check(await pagefind.createIndex({}), what);
113
- for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: page.content }), `${what}: ${page.rel}`);
119
+ 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}`);
114
120
  check(await index.writeFiles({ outputPath }), what);
115
121
  };
116
122
  try {
@@ -82,6 +82,7 @@ import { htmlDirective } from "../lib/agent-directive.js";
82
82
  import { contextMenuOptions } from "../lib/config";
83
83
  import { jsonLd, serializeJsonLd } from "../lib/json-ld.js";
84
84
  import { consentOptions } from "../lib/consent.js";
85
+ import { oncePerBuild } from "../lib/build-memo.js";
85
86
 
86
87
  interface Props {
87
88
  config: DocsConfig;
@@ -381,10 +382,12 @@ const footerLogoDark = footerLogoConfig
381
382
  // project (root, `docs/`, `snippets/`, `public/`, any subfolder -
382
383
  // `dist/`/`node_modules/`/etc. excluded, see findRootAssets() in
383
384
  // lib/pages.js) is auto-loaded on every page, no writedocs.json entry
384
- // needed. Read fresh on every render (not cached at module scope) so an
385
- // edit to one of these files shows up on the next `writedocs dev` page
386
- // load without a server restart - same freshness `loadDocsConfig(contentDir)`
387
- // itself already gives writedocs.json edits in [...slug].astro/404.astro.
385
+ // needed. In `writedocs dev` they're read fresh on every render, so an
386
+ // edit to one of these files shows up on the next page load without a
387
+ // server restart - same freshness `loadDocsConfig(contentDir)` itself
388
+ // already gives writedocs.json edits in [...slug].astro/404.astro. In a
389
+ // build, where they can't change, the list and the files are read once
390
+ // for all pages (oncePerBuild(), lib/build-memo.js).
388
391
  // Rendered in addition to, not instead of, writedocs.json's own explicit
389
392
  // `scripts` field - that still exists for external/CDN script URLs
390
393
  // (`src`) and inline content that should only load under deliberate
@@ -397,12 +400,12 @@ const rootAssets = findRootAssets(contentDir);
397
400
  // "docs/theme.css") - split and rejoin with nodePath.join rather than
398
401
  // handing the raw string straight to it, so a nested asset resolves
399
402
  // correctly on every OS this might run on, not just POSIX ones.
400
- const rootCssContents = rootAssets.css.map((name) =>
403
+ const rootCssContents = oncePerBuild("root-css-contents", () => rootAssets.css.map((name) =>
401
404
  fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
402
- );
403
- const rootJsContents = rootAssets.js.map((name) =>
405
+ ));
406
+ const rootJsContents = oncePerBuild("root-js-contents", () => rootAssets.js.map((name) =>
404
407
  fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
405
- );
408
+ ));
406
409
  // public/*.css and public/*.js auto-load too, but as <link>/<script src>
407
410
  // pointing at their already-public URL (see findRootAssets()'s own
408
411
  // comment for why - no point inlining a file that's also independently
@@ -0,0 +1,22 @@
1
+ // What is the same for every page of a build, worked out once per build.
2
+ //
3
+ // `writedocs build` renders every page in one process, from files that don't
4
+ // change while it runs. The list of page files, writedocs.json, the lookup
5
+ // tables built from the collections - each page asked for them again, and
6
+ // each of those reads the whole project: with N pages, N x N file reads. A
7
+ // 4,000-page site spent 13 of its 19 minutes there.
8
+ //
9
+ // Only in a build: src/cli/run-astro.js tells the Astro process which command
10
+ // it runs (WRITEDOCS_COMMAND). In `writedocs dev` - and wherever else this is
11
+ // loaded: `writedocs validate`, the tests - compute() runs on every call, as
12
+ // it always did, because there the files do change between two calls.
13
+ //
14
+ // What compute() returns is handed to every caller, so callers must not
15
+ // change it. Plain JavaScript, for scripts/build-memo.test.js.
16
+ const values = new Map();
17
+
18
+ export function oncePerBuild(key, compute) {
19
+ if (process.env.WRITEDOCS_COMMAND !== 'build') return compute();
20
+ if (!values.has(key)) values.set(key, compute());
21
+ return values.get(key);
22
+ }
@@ -337,6 +337,11 @@ const pageSeoFieldsSchema = seoFieldsSchema.extend({
337
337
  jsonLd: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).optional()
338
338
  }).strict();
339
339
  const siteSeoFieldsSchema = seoFieldsSchema.extend({
340
+ // The link preview picture generated for every page that has no
341
+ // `ogImage` (lib/og-image.js). On unless this is `false`: drawing one
342
+ // takes ~25 ms a page, which a site with thousands of pages may prefer
343
+ // to save. Site-wide only - a page opts out by setting its own `ogImage`.
344
+ generatedOgImage: z.boolean().optional(),
340
345
  // Who publishes the site - an Organization block in the home page's
341
346
  // structured data, and the `publisher` of every page (lib/json-ld.js).
342
347
  // Not derived from `name`: a site is called "Acme Docs", the
@@ -679,6 +679,11 @@ export const pageSeoFieldsSchema = seoFieldsSchema
679
679
  // as a whole.
680
680
  export const siteSeoFieldsSchema = seoFieldsSchema
681
681
  .extend({
682
+ // The link preview picture generated for every page that has no
683
+ // `ogImage` (lib/og-image.js). On unless this is `false`: drawing one
684
+ // takes ~25 ms a page, which a site with thousands of pages may prefer
685
+ // to save. Site-wide only - a page opts out by setting its own `ogImage`.
686
+ generatedOgImage: z.boolean().optional(),
682
687
  // Who publishes the site - an Organization block in the home page's
683
688
  // structured data, and the `publisher` of every page (lib/json-ld.js).
684
689
  // Not derived from `name`: a site is called "Acme Docs", the
package/src/lib/config.ts CHANGED
@@ -6,6 +6,7 @@ import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLanding
6
6
  import matter from 'gray-matter';
7
7
  import { writedocsTempDir } from './writedocs-temp-dir.js';
8
8
  import { readableTextOn } from './color.js';
9
+ import { oncePerBuild } from './build-memo.js';
9
10
  import {
10
11
  formatValidationIssues,
11
12
  validateDocsConfig,
@@ -396,6 +397,13 @@ function expandOpenApiInNavigation(navigation: NavigationConfig, contentDir: str
396
397
  }
397
398
 
398
399
  export function loadDocsConfig(contentDir: string): DocsConfig {
400
+ // Read and validated once per build, not once per page (lib/build-memo.js):
401
+ // every caller there gets the same object, so none of them may change it.
402
+ // In `writedocs dev` it's read again on every call, and an edit shows up.
403
+ return oncePerBuild(`config:${contentDir}`, () => readDocsConfig(contentDir));
404
+ }
405
+
406
+ function readDocsConfig(contentDir: string): DocsConfig {
399
407
  const configPath = path.join(contentDir, 'writedocs.json');
400
408
  if (!fs.existsSync(configPath)) {
401
409
  throw new Error(
@@ -168,6 +168,7 @@ export const DESCRIPTIONS = {
168
168
 
169
169
  seo: 'Default metadata for every page. A page\'s own `seo` frontmatter overrides it field by field.',
170
170
  'seo.ogImage': 'Image shown in link previews - a path or a full URL.',
171
+ 'seo.generatedOgImage': 'Whether a page without an `ogImage` gets a link preview image generated at build time. Default true; set false to skip them, which shortens the build of a large site.',
171
172
  'seo.ogType': 'The og:type of pages. Default "website".',
172
173
  'seo.twitterCard': 'X/Twitter card style. Default "summary_large_image" with an `ogImage`, "summary" without.',
173
174
  'seo.keywords': 'Keywords for the <meta name="keywords"> tag.',
@@ -27,8 +27,13 @@ export const OG_HEIGHT = 630;
27
27
 
28
28
  /** Whether a page gets a generated picture: it has none of its own (`seo`
29
29
  * is the site's with the page's merged over it), search engines index it,
30
- * and it's a page - not a link to somewhere else (`url`). */
31
- export function wantsGeneratedCard(seo, data = {}) {
30
+ * and it's a page - not a link to somewhere else (`url`) - on a site that
31
+ * hasn't turned generated pictures off. */
32
+ export function wantsGeneratedCard(seo, data = {}, siteSeo = {}) {
33
+ // writedocs.json `"seo": { "generatedOgImage": false }` turns them off
34
+ // for the whole site - `siteSeo` is the site's own `seo`, since the merged
35
+ // one (mergeSeo()) only carries the fields a page can set.
36
+ if (siteSeo?.generatedOgImage === false) return false;
32
37
  return !seo?.ogImage && !seo?.noindex && !data.url;
33
38
  }
34
39
 
@@ -151,8 +156,13 @@ export async function ogImageSvg(options) {
151
156
  export async function ogImagePng(options) {
152
157
  const svg = await ogImageSvg(options);
153
158
  const { Resvg } = await loadRenderer();
154
- const rendered = new Resvg(svg, { fitTo: { mode: 'width', value: OG_WIDTH } }).render();
159
+ const resvg = new Resvg(svg, { fitTo: { mode: 'width', value: OG_WIDTH } });
160
+ const rendered = resvg.render();
155
161
  const png = Buffer.from(rendered.asPng());
162
+ // Both live in the WebAssembly memory, which nothing collects: freeing
163
+ // only the image left the parsed SVG of every card there until the build
164
+ // ended, and past ~800 cards each one took three times as long.
156
165
  rendered.free?.();
166
+ resvg.free?.();
157
167
  return png;
158
168
  }
package/src/lib/pages.js CHANGED
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import matter from 'gray-matter';
8
8
  import { readConfigText } from './config-file.js';
9
+ import { oncePerBuild } from './build-memo.js';
9
10
 
10
11
  // Top-level folders of a content directory that are never scanned for
11
12
  // pages - build output, dependencies, and static assets. Any folder whose
@@ -114,10 +115,17 @@ function navigationPageIds(contentDir) {
114
115
  * and [...slug].astro, which needs the identical list to decide whether
115
116
  * calling `getCollection('pages')` is worth doing at all. Also reused by
116
117
  * astro.config.mjs's noindex/sitemap scan and by `writedocs validate`, so
117
- * all of them see exactly the same file set. Synchronous and re-run from
118
- * scratch wherever it's called - cheap enough for a docs site's file
119
- * count. */
118
+ * all of them see exactly the same file set. Synchronous. In a build the
119
+ * project is scanned once and every later call gets that list
120
+ * (lib/build-memo.js) - a page that scanned it again made the build N x N;
121
+ * everywhere else (`writedocs dev`, `validate`) every call scans afresh,
122
+ * so a page added or removed is seen. */
120
123
  export function findAllPages(contentDir) {
124
+ // A copy, so a caller that changes its list doesn't change everyone's.
125
+ return oncePerBuild(`pages:${contentDir}`, () => scanAllPages(contentDir)).slice();
126
+ }
127
+
128
+ function scanAllPages(contentDir) {
121
129
  const results = [];
122
130
  const ignored = readIgnoreFile(contentDir);
123
131
  const listed = navigationPageIds(contentDir);
@@ -232,6 +240,11 @@ export function fileIdForPath(relativePath) {
232
240
  * above - nothing to read, Astro's own static-file serving/copy already
233
241
  * handles those. */
234
242
  export function findRootAssets(contentDir) {
243
+ // Once per build (lib/build-memo.js); on every call in `writedocs dev`.
244
+ return oncePerBuild(`root-assets:${contentDir}`, () => scanRootAssets(contentDir));
245
+ }
246
+
247
+ function scanRootAssets(contentDir) {
235
248
  const css = [];
236
249
  const js = [];
237
250
  function walk(dir, relBase) {
@@ -78,6 +78,7 @@ import { selectorPlacements } from "../lib/selector-placement.js";
78
78
  import { spaceOf } from "../lib/hidden-sections.js";
79
79
  import { navigationPageOrder } from "../lib/pages.js";
80
80
  import { folderRedirects } from "../lib/folder-redirects.js";
81
+ import { oncePerBuild } from "../lib/build-memo.js";
81
82
 
82
83
  // A page is hand-written (the `pages` collection, sourced from anywhere
83
84
  // in the project - docs/ has no special status, see findAllPages() in
@@ -371,7 +372,8 @@ const {
371
372
  const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
372
373
  const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
373
374
  const config = loadDocsConfig(contentDir);
374
- const sections = resolveSections(config.navigation);
375
+ // Once per build, like the lookup tables further down.
376
+ const sections = oncePerBuild("slug:sections", () => resolveSections(config.navigation));
375
377
  // Falls back to an empty stand-in section rather than crashing on
376
378
  // `.pages` below - only reachable for a hidden page (see hiddenRoutes in
377
379
  // getStaticPaths above) on a site whose writedocs.json has no navigation
@@ -379,12 +381,17 @@ const sections = resolveSections(config.navigation);
379
381
  // render in the first place.
380
382
  // An item's own page shown inside its item (landingRoutes above): the item's
381
383
  // path, and its own sidebar if it has one.
382
- const landing = landingIndex === undefined ? undefined : resolveLandings(config.navigation)[landingIndex];
384
+ const landing = landingIndex === undefined ? undefined : oncePerBuild("slug:landings", () => resolveLandings(config.navigation))[landingIndex];
383
385
  const activeSection = landing ? { pages: landing.pages, path: landing.path } : sections[sectionIndex] ?? { pages: [], path: [] };
384
386
 
385
387
  const { Content, headings } = await render(entry);
386
388
  const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
387
389
 
390
+ // The lookup tables below are the same for every page, so a build makes
391
+ // them once (oncePerBuild(), lib/build-memo.js) - findAllPages() alone reads
392
+ // every page file of the project, and ran here once per page. In
393
+ // `writedocs dev` they're made again on every request, as before.
394
+ const { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId } = await oncePerBuild("slug:lookups", async () => {
388
395
  const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
389
396
  const hasPages = findAllPages(contentDir).length > 0;
390
397
  const [pagesEntries, generatedDocsEntries] = await Promise.all([
@@ -419,6 +426,8 @@ for (const e of entries) {
419
426
  methodByFileId.set(fileId, apiRef.method);
420
427
  }
421
428
  }
429
+ return { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId };
430
+ });
422
431
  const titleForSlug = (slug: string) => titleByFileId.get(slug) ?? slug;
423
432
  const navTitleForSlug = (slug: string) => navTitleByFileId.get(slug) ?? slug;
424
433
  const methodForSlug = (slug: string) => methodByFileId.get(slug) ?? null;
@@ -435,7 +444,9 @@ const hrefForSlug = (slug: string) => {
435
444
  // and what every "is this the active page" comparison below needs, since
436
445
  // navTree/globalDropdowns are built from writedocs.json's file-id space.
437
446
  const currentFileId = fileIdForEntry(contentDir, packageRoot, entry);
438
- const navTree = buildNavTree(activeSection.pages, navTitleForSlug, methodForSlug, navMetaForSlug);
447
+ // A section's tree doesn't depend on which of its pages is open (NavTree.astro
448
+ // marks the current one), so it's built once per section in a build.
449
+ const navTree = oncePerBuild(`slug:nav:${landingIndex === undefined ? `s${sectionIndex}` : `l${landingIndex}`}`, () => buildNavTree(activeSection.pages, navTitleForSlug, methodForSlug, navMetaForSlug));
439
450
  // The ancestor sidebar-group trail above the auto <h1> (Breadcrumbs.astro)
440
451
  // - empty for a page sitting at the top level of its Section with no
441
452
  // enclosing group, in which case [...slug].astro below skips rendering
@@ -486,7 +497,7 @@ const globalDropdowns = buildGlobalDropdowns(
486
497
  const pageSeo = mergeSeo(config.seo, entry.data.seo);
487
498
  // A page with no picture of its own for link previews gets the generated
488
499
  // card (lib/og-image.js, served by src/pages/og/[...slug].png.ts).
489
- if (wantsGeneratedCard(pageSeo, entry.data)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
500
+ if (wantsGeneratedCard(pageSeo, entry.data, config.seo)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
490
501
  const currentPath = hrefForSlug(currentFileId);
491
502
  // This page in each language, for hreflang (languageAlternates() in
492
503
  // lib/item-pages.js) - a hidden page belongs to no language level.
@@ -12,7 +12,8 @@ import { imageFileFor } from '../../lib/image-size.js';
12
12
  // title and description, the site's primary color (lib/og-image.js).
13
13
  // [...slug].astro points the page's og:image here under the same condition
14
14
  // (wantsGeneratedCard()), so a card is only built for a page that uses it -
15
- // a site with `seo.ogImage` in writedocs.json builds none at all.
15
+ // a site with `seo.ogImage` in writedocs.json builds none at all, and neither
16
+ // does one with `"seo": { "generatedOgImage": false }`.
16
17
  //
17
18
  // A static route like [...slug].md.ts next to it: one file per page at build
18
19
  // time, and built on request in `writedocs dev`.
@@ -36,7 +37,7 @@ export async function getStaticPaths() {
36
37
  const logo = logoForCard(logoPath ? imageFileFor(logoPath, contentDir) : null);
37
38
 
38
39
  return entries
39
- .filter((entry) => wantsGeneratedCard(mergeSeo(config.seo, entry.data.seo), entry.data))
40
+ .filter((entry) => wantsGeneratedCard(mergeSeo(config.seo, entry.data.seo), entry.data, config.seo))
40
41
  .map((entry) => ({
41
42
  params: { slug: normalizeEntryId(entry.id) },
42
43
  props: {
@@ -757,6 +757,11 @@
757
757
  "description": "Other <meta> tags, name to content - like { \"google-site-verification\": \"...\" }. One with the name of a tag writedocs writes (\"og:image\", \"twitter:image\") replaces it.",
758
758
  "markdownDescription": "Other <meta> tags, name to content - like { \"google-site-verification\": \"...\" }. One with the name of a tag writedocs writes (\"og:image\", \"twitter:image\") replaces it."
759
759
  },
760
+ "generatedOgImage": {
761
+ "type": "boolean",
762
+ "description": "Whether a page without an `ogImage` gets a link preview image generated at build time. Default true; set false to skip them, which shortens the build of a large site.",
763
+ "markdownDescription": "Whether a page without an `ogImage` gets a link preview image generated at build time. Default true; set false to skip them, which shortens the build of a large site."
764
+ },
760
765
  "organization": {
761
766
  "type": "object",
762
767
  "properties": {