@writedocs/generator 0.13.4 → 0.14.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 (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
@@ -1,164 +1,164 @@
1
- // The Markdown an AI agent reads for a page - llms-full.txt and the per-page
2
- // .md route. It starts from the page's raw MDX, so everything the build does
3
- // to that source on the way to HTML has to be redone here, or the agent reads
4
- // something other than the page: `<Visibility>` blocks, imported .mdx
5
- // snippets (inlined, as the page shows them) and writedocs.json `variables`.
6
- //
7
- // Code is left exactly as written - fenced blocks and inline `code` - the same
8
- // way the build never substitutes inside code: a page documenting the
9
- // `[[key]]` syntax, or showing `<Snippet />` in an example, must keep it.
10
- // Plain JavaScript, so it can be tested with plain Node.
11
- import fs from 'node:fs';
12
- import path from 'node:path';
13
- import matter from 'gray-matter';
14
- import { applyVisibilityForAgents } from './visibility.js';
15
- import { componentsToMarkdown } from './components-to-markdown.js';
16
-
17
- /** `text` with `transform` applied to everything outside fenced code blocks
18
- * and inline code spans; code comes back untouched. */
19
- export function mapOutsideCode(text, transform) {
20
- const out = [];
21
- let prose = [];
22
- let fence = null; // the opening marker (``` or ~~~, maybe longer) while inside a block
23
- const flush = () => {
24
- if (prose.length) out.push(mapOutsideInlineCode(prose.join('\n'), transform));
25
- prose = [];
26
- };
27
- for (const line of text.split('\n')) {
28
- const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
29
- if (fence) {
30
- out.push(line);
31
- if (marker && marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker) fence = null;
32
- } else if (marker) {
33
- flush();
34
- fence = marker;
35
- out.push(line);
36
- } else {
37
- prose.push(line);
38
- }
39
- }
40
- flush();
41
- return out.join('\n');
42
- }
43
-
44
- function mapOutsideInlineCode(text, transform) {
45
- // Backtick runs of equal length delimit a code span (CommonMark).
46
- return text
47
- // A closing run is a whole run: in "` ```bash `" the three backticks
48
- // inside don't close the span that one backtick opened.
49
- .split(/(?<!`)(`+)(?!`)([\s\S]*?)(?<!`)(\1)(?!`)/)
50
- .reduce((acc, part, i, parts) => {
51
- const k = i % 4;
52
- if (k === 0) acc.push(transform(part));
53
- else if (k === 1) acc.push(part + parts[i + 1] + parts[i + 2]);
54
- return acc;
55
- }, [])
56
- .join('');
57
- }
58
-
59
- const PLACEHOLDER = /\[\[\s*([\w.-]+)\s*\]\]/g;
60
- // A standalone `{key}` or `{{key}}` expression (Mintlify writes the latter;
61
- // MDX reads it as `{key}` inside an expression) - not an attribute value
62
- // (`prop={key}`), which the build leaves alone too. The double form first,
63
- // or its outer braces would be left around the value.
64
- const MINTLIFY_PLACEHOLDER = /(?<!=\s*)\{\s*\{\s*([A-Za-z_$][\w$]*)\s*\}\s*\}|(?<!=\s*)\{\s*([A-Za-z_$][\w$]*)\s*\}/g;
65
-
66
- /** writedocs.json `variables` - `[[key]]`, and Mintlify's `{key}` - replaced
67
- * the way the build replaces them (lib/mdx-substitute-variables.js): outside
68
- * code, and only for keys that exist. */
69
- export function substituteVariables(text, variables) {
70
- if (!variables || Object.keys(variables).length === 0) return text;
71
- const has = (key) => Object.prototype.hasOwnProperty.call(variables, key);
72
- return mapOutsideCode(text, (prose) =>
73
- prose
74
- .replace(PLACEHOLDER, (match, key) => (has(key) ? String(variables[key]) : match))
75
- .replace(MINTLIFY_PLACEHOLDER, (match, doubled, single) => {
76
- const key = doubled ?? single;
77
- return has(key) ? String(variables[key]) : match;
78
- })
79
- );
80
- }
81
-
82
- const IMPORT_LINE = /^[ \t]*import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+\.mdx?)['"];?[ \t]*$/gm;
83
-
84
- function resolveSnippet(spec, fromFile, contentDir) {
85
- if (spec.startsWith('/snippets/')) return path.join(contentDir, 'snippets', spec.slice('/snippets/'.length));
86
- if (spec.startsWith('./') || spec.startsWith('../')) return path.resolve(path.dirname(fromFile), spec);
87
- if (spec.startsWith('/')) return path.join(contentDir, spec.slice(1));
88
- return null;
89
- }
90
-
91
- function attributesOf(source) {
92
- const props = {};
93
- for (const m of source.matchAll(/([A-Za-z_$][\w$-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*["']([^"']*)["']\s*\})/g)) {
94
- props[m[1]] = m[2] ?? m[3] ?? m[4];
95
- }
96
- return props;
97
- }
98
-
99
- function fillProps(snippet, props, children) {
100
- return snippet
101
- .replace(/\{\s*props\.children\s*\}/g, children ?? '')
102
- .replace(/\{\s*props\.([A-Za-z_$][\w$]*)\s*\}/g, (match, key) => (key in props ? props[key] : match));
103
- }
104
-
105
- /** Imported .mdx snippets inlined where the page uses them - the snippet's
106
- * own text, with `{props.x}` filled from the tag's string attributes, and
107
- * its own imports inlined in turn. The import line goes too. A snippet that
108
- * can't be read, or a .jsx/.tsx component, stays as written. */
109
- export function inlineSnippets(text, { file, contentDir, depth = 0 }) {
110
- if (depth > 5) return text;
111
- const snippets = new Map();
112
- let result = mapOutsideCode(text, (prose) =>
113
- prose.replace(IMPORT_LINE, (line, name, spec) => {
114
- const target = resolveSnippet(spec, file, contentDir);
115
- let raw;
116
- try {
117
- raw = target && fs.readFileSync(target, 'utf-8');
118
- } catch {
119
- raw = null;
120
- }
121
- if (!raw) return line;
122
- const body = inlineSnippets(matter(raw).content.trim(), { file: target, contentDir, depth: depth + 1 });
123
- snippets.set(name, body);
124
- return '';
125
- })
126
- );
127
- for (const [name, body] of snippets) {
128
- result = mapOutsideCode(result, (prose) =>
129
- prose
130
- .replace(new RegExp(`<${name}\\b([^>]*?)\\/>`, 'g'), (_, attrs) => fillProps(body, attributesOf(attrs)))
131
- .replace(new RegExp(`<${name}\\b([^>]*)>([\\s\\S]*?)<\\/${name}>`, 'g'), (_, attrs, children) =>
132
- fillProps(body, attributesOf(attrs), children.trim())
133
- )
134
- );
135
- }
136
- return result.replace(/\n{3,}/g, '\n\n');
137
- }
138
-
139
- /** Links and images written from the site's root (`/docs/setup/`) as full
140
- * URLs. A page copied out of the site - pasted into a chat, fetched by an
141
- * agent, read from llms-full.txt - has no site to resolve them against.
142
- * Markdown links and images, and the `href`/`src`/`img` of a component;
143
- * code is left as written, and so is everything without a `siteUrl`.
144
- * `siteUrl` can be just the site's base ("/docs", lib/base-path.js) when
145
- * there's no `domain`: the links then keep the base, if not the domain. */
146
- export function absolutizeLinks(text, siteUrl) {
147
- if (!siteUrl) return text;
148
- return mapOutsideCode(text, (prose) =>
149
- prose
150
- .replace(/(\]\()\/(?!\/)/g, `$1${siteUrl}/`)
151
- .replace(/(\b(?:href|src|img)=["'])\/(?!\/)/g, `$1${siteUrl}/`)
152
- );
153
- }
154
-
155
- /** A page's body as an agent should read it. `file` is the page's absolute
156
- * path (to resolve relative snippet imports). */
157
- export function markdownForAgents(body, { file, contentDir, variables }) {
158
- let text = applyVisibilityForAgents(body ?? '');
159
- if (file) text = inlineSnippets(text, { file, contentDir });
160
- text = substituteVariables(text, variables);
161
- // Components as the Markdown that says what they show
162
- // (lib/components-to-markdown.js) - in an .mdx page; a .md page has none.
163
- return file && /\.md$/i.test(file) ? text : componentsToMarkdown(text);
164
- }
1
+ // The Markdown an AI agent reads for a page - llms-full.txt and the per-page
2
+ // .md route. It starts from the page's raw MDX, so everything the build does
3
+ // to that source on the way to HTML has to be redone here, or the agent reads
4
+ // something other than the page: `<Visibility>` blocks, imported .mdx
5
+ // snippets (inlined, as the page shows them) and writedocs.json `variables`.
6
+ //
7
+ // Code is left exactly as written - fenced blocks and inline `code` - the same
8
+ // way the build never substitutes inside code: a page documenting the
9
+ // `[[key]]` syntax, or showing `<Snippet />` in an example, must keep it.
10
+ // Plain JavaScript, so it can be tested with plain Node.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import matter from 'gray-matter';
14
+ import { applyVisibilityForAgents } from './visibility.js';
15
+ import { componentsToMarkdown } from './components-to-markdown.js';
16
+
17
+ /** `text` with `transform` applied to everything outside fenced code blocks
18
+ * and inline code spans; code comes back untouched. */
19
+ export function mapOutsideCode(text, transform) {
20
+ const out = [];
21
+ let prose = [];
22
+ let fence = null; // the opening marker (``` or ~~~, maybe longer) while inside a block
23
+ const flush = () => {
24
+ if (prose.length) out.push(mapOutsideInlineCode(prose.join('\n'), transform));
25
+ prose = [];
26
+ };
27
+ for (const line of text.split('\n')) {
28
+ const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
29
+ if (fence) {
30
+ out.push(line);
31
+ if (marker && marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker) fence = null;
32
+ } else if (marker) {
33
+ flush();
34
+ fence = marker;
35
+ out.push(line);
36
+ } else {
37
+ prose.push(line);
38
+ }
39
+ }
40
+ flush();
41
+ return out.join('\n');
42
+ }
43
+
44
+ function mapOutsideInlineCode(text, transform) {
45
+ // Backtick runs of equal length delimit a code span (CommonMark).
46
+ return text
47
+ // A closing run is a whole run: in "` ```bash `" the three backticks
48
+ // inside don't close the span that one backtick opened.
49
+ .split(/(?<!`)(`+)(?!`)([\s\S]*?)(?<!`)(\1)(?!`)/)
50
+ .reduce((acc, part, i, parts) => {
51
+ const k = i % 4;
52
+ if (k === 0) acc.push(transform(part));
53
+ else if (k === 1) acc.push(part + parts[i + 1] + parts[i + 2]);
54
+ return acc;
55
+ }, [])
56
+ .join('');
57
+ }
58
+
59
+ const PLACEHOLDER = /\[\[\s*([\w.-]+)\s*\]\]/g;
60
+ // A standalone `{key}` or `{{key}}` expression (Mintlify writes the latter;
61
+ // MDX reads it as `{key}` inside an expression) - not an attribute value
62
+ // (`prop={key}`), which the build leaves alone too. The double form first,
63
+ // or its outer braces would be left around the value.
64
+ const MINTLIFY_PLACEHOLDER = /(?<!=\s*)\{\s*\{\s*([A-Za-z_$][\w$]*)\s*\}\s*\}|(?<!=\s*)\{\s*([A-Za-z_$][\w$]*)\s*\}/g;
65
+
66
+ /** writedocs.json `variables` - `[[key]]`, and Mintlify's `{key}` - replaced
67
+ * the way the build replaces them (lib/mdx-substitute-variables.js): outside
68
+ * code, and only for keys that exist. */
69
+ export function substituteVariables(text, variables) {
70
+ if (!variables || Object.keys(variables).length === 0) return text;
71
+ const has = (key) => Object.prototype.hasOwnProperty.call(variables, key);
72
+ return mapOutsideCode(text, (prose) =>
73
+ prose
74
+ .replace(PLACEHOLDER, (match, key) => (has(key) ? String(variables[key]) : match))
75
+ .replace(MINTLIFY_PLACEHOLDER, (match, doubled, single) => {
76
+ const key = doubled ?? single;
77
+ return has(key) ? String(variables[key]) : match;
78
+ })
79
+ );
80
+ }
81
+
82
+ const IMPORT_LINE = /^[ \t]*import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+\.mdx?)['"];?[ \t]*$/gm;
83
+
84
+ function resolveSnippet(spec, fromFile, contentDir) {
85
+ if (spec.startsWith('/snippets/')) return path.join(contentDir, 'snippets', spec.slice('/snippets/'.length));
86
+ if (spec.startsWith('./') || spec.startsWith('../')) return path.resolve(path.dirname(fromFile), spec);
87
+ if (spec.startsWith('/')) return path.join(contentDir, spec.slice(1));
88
+ return null;
89
+ }
90
+
91
+ function attributesOf(source) {
92
+ const props = {};
93
+ for (const m of source.matchAll(/([A-Za-z_$][\w$-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*["']([^"']*)["']\s*\})/g)) {
94
+ props[m[1]] = m[2] ?? m[3] ?? m[4];
95
+ }
96
+ return props;
97
+ }
98
+
99
+ function fillProps(snippet, props, children) {
100
+ return snippet
101
+ .replace(/\{\s*props\.children\s*\}/g, children ?? '')
102
+ .replace(/\{\s*props\.([A-Za-z_$][\w$]*)\s*\}/g, (match, key) => (key in props ? props[key] : match));
103
+ }
104
+
105
+ /** Imported .mdx snippets inlined where the page uses them - the snippet's
106
+ * own text, with `{props.x}` filled from the tag's string attributes, and
107
+ * its own imports inlined in turn. The import line goes too. A snippet that
108
+ * can't be read, or a .jsx/.tsx component, stays as written. */
109
+ export function inlineSnippets(text, { file, contentDir, depth = 0 }) {
110
+ if (depth > 5) return text;
111
+ const snippets = new Map();
112
+ let result = mapOutsideCode(text, (prose) =>
113
+ prose.replace(IMPORT_LINE, (line, name, spec) => {
114
+ const target = resolveSnippet(spec, file, contentDir);
115
+ let raw;
116
+ try {
117
+ raw = target && fs.readFileSync(target, 'utf-8');
118
+ } catch {
119
+ raw = null;
120
+ }
121
+ if (!raw) return line;
122
+ const body = inlineSnippets(matter(raw).content.trim(), { file: target, contentDir, depth: depth + 1 });
123
+ snippets.set(name, body);
124
+ return '';
125
+ })
126
+ );
127
+ for (const [name, body] of snippets) {
128
+ result = mapOutsideCode(result, (prose) =>
129
+ prose
130
+ .replace(new RegExp(`<${name}\\b([^>]*?)\\/>`, 'g'), (_, attrs) => fillProps(body, attributesOf(attrs)))
131
+ .replace(new RegExp(`<${name}\\b([^>]*)>([\\s\\S]*?)<\\/${name}>`, 'g'), (_, attrs, children) =>
132
+ fillProps(body, attributesOf(attrs), children.trim())
133
+ )
134
+ );
135
+ }
136
+ return result.replace(/\n{3,}/g, '\n\n');
137
+ }
138
+
139
+ /** Links and images written from the site's root (`/docs/setup/`) as full
140
+ * URLs. A page copied out of the site - pasted into a chat, fetched by an
141
+ * agent, read from llms-full.txt - has no site to resolve them against.
142
+ * Markdown links and images, and the `href`/`src`/`img` of a component;
143
+ * code is left as written, and so is everything without a `siteUrl`.
144
+ * `siteUrl` can be just the site's base ("/docs", lib/base-path.js) when
145
+ * there's no `domain`: the links then keep the base, if not the domain. */
146
+ export function absolutizeLinks(text, siteUrl) {
147
+ if (!siteUrl) return text;
148
+ return mapOutsideCode(text, (prose) =>
149
+ prose
150
+ .replace(/(\]\()\/(?!\/)/g, `$1${siteUrl}/`)
151
+ .replace(/(\b(?:href|src|img)=["'])\/(?!\/)/g, `$1${siteUrl}/`)
152
+ );
153
+ }
154
+
155
+ /** A page's body as an agent should read it. `file` is the page's absolute
156
+ * path (to resolve relative snippet imports). */
157
+ export function markdownForAgents(body, { file, contentDir, variables }) {
158
+ let text = applyVisibilityForAgents(body ?? '');
159
+ if (file) text = inlineSnippets(text, { file, contentDir });
160
+ text = substituteVariables(text, variables);
161
+ // Components as the Markdown that says what they show
162
+ // (lib/components-to-markdown.js) - in an .mdx page; a .md page has none.
163
+ return file && /\.md$/i.test(file) ? text : componentsToMarkdown(text);
164
+ }
@@ -1,89 +1,89 @@
1
- // Image sizes handed to the build in a file, so it doesn't open the images.
2
- //
3
- // The WriteDocs platform builds a project with its images swapped for small
4
- // placeholder files (it puts the real ones back after the build), so the
5
- // build can't read a width and a height from them. It writes this file
6
- // instead:
7
- //
8
- // <project>/.writedocs/asset-dimensions.json
9
- // {
10
- // "images/hero.png": { "width": 1200, "height": 630 },
11
- // "public/images/logo.svg": { "width": 120, "height": 32 }
12
- // }
13
- //
14
- // THIS FORMAT IS A CONTRACT with the platform:
15
- // - one JSON object; each key is a file's path from the project root -
16
- // where the file really is, so a file in public/ starts with "public/" -
17
- // with forward slashes, no leading slash, spelled exactly as on disk;
18
- // - each value is an object with `width` and `height`, both whole numbers
19
- // greater than zero (pixels). Other fields in it are ignored.
20
- // - A path that's listed is never opened to be measured. A path that isn't
21
- // listed is read from its file, as when there's no such file at all.
22
- // - An entry that isn't valid is skipped and the image is read; a file
23
- // that isn't valid JSON, or isn't an object, counts as absent. Nothing
24
- // here can fail a build.
25
- //
26
- // `.writedocs/` is never published (EXCLUDED_TOP_LEVEL_DIRS, lib/pages.js).
27
- import fs from 'node:fs';
28
- import path from 'node:path';
29
-
30
- /** Where the file is, from the project root. */
31
- export const ASSET_DIMENSIONS_FILE = '.writedocs/asset-dimensions.json';
32
-
33
- const isSize = (n) => Number.isSafeInteger(n) && n > 0;
34
-
35
- /** The valid entries of the file's text, as a Map of path -> `{ width,
36
- * height }`. Empty for text that isn't a JSON object. */
37
- export function parseAssetDimensions(text) {
38
- const sizes = new Map();
39
- let data;
40
- try {
41
- data = JSON.parse(String(text).replace(/^\uFEFF/, ''));
42
- } catch {
43
- return sizes;
44
- }
45
- if (!data || typeof data !== 'object' || Array.isArray(data)) return sizes;
46
- for (const [key, value] of Object.entries(data)) {
47
- if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
48
- if (!isSize(value.width) || !isSize(value.height)) continue;
49
- sizes.set(key, { width: value.width, height: value.height });
50
- }
51
- return sizes;
52
- }
53
-
54
- // Per project, parsed again only when the file changes - `writedocs dev`
55
- // keeps running while it's edited.
56
- const loaded = new Map();
57
-
58
- function dimensionsFor(contentDir) {
59
- const file = path.join(contentDir, ...ASSET_DIMENSIONS_FILE.split('/'));
60
- let stamp;
61
- try {
62
- const stat = fs.statSync(file);
63
- stamp = `${stat.mtimeMs}:${stat.size}`;
64
- } catch {
65
- loaded.delete(contentDir);
66
- return null;
67
- }
68
- const known = loaded.get(contentDir);
69
- if (known?.stamp === stamp) return known.sizes;
70
- let sizes;
71
- try {
72
- sizes = parseAssetDimensions(fs.readFileSync(file, 'utf8'));
73
- } catch {
74
- sizes = new Map();
75
- }
76
- loaded.set(contentDir, { stamp, sizes });
77
- return sizes;
78
- }
79
-
80
- /** `{ width, height }` for the image file at `file` (an absolute path) when
81
- * the project's asset-dimensions.json lists it, else null. */
82
- export function providedImageSize(file, contentDir) {
83
- if (!file || !contentDir) return null;
84
- const sizes = dimensionsFor(contentDir);
85
- if (!sizes || sizes.size === 0) return null;
86
- const relative = path.relative(contentDir, file);
87
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
88
- return sizes.get(relative.split(path.sep).join('/')) ?? null;
89
- }
1
+ // Image sizes handed to the build in a file, so it doesn't open the images.
2
+ //
3
+ // The WriteDocs platform builds a project with its images swapped for small
4
+ // placeholder files (it puts the real ones back after the build), so the
5
+ // build can't read a width and a height from them. It writes this file
6
+ // instead:
7
+ //
8
+ // <project>/.writedocs/asset-dimensions.json
9
+ // {
10
+ // "images/hero.png": { "width": 1200, "height": 630 },
11
+ // "public/images/logo.svg": { "width": 120, "height": 32 }
12
+ // }
13
+ //
14
+ // THIS FORMAT IS A CONTRACT with the platform:
15
+ // - one JSON object; each key is a file's path from the project root -
16
+ // where the file really is, so a file in public/ starts with "public/" -
17
+ // with forward slashes, no leading slash, spelled exactly as on disk;
18
+ // - each value is an object with `width` and `height`, both whole numbers
19
+ // greater than zero (pixels). Other fields in it are ignored.
20
+ // - A path that's listed is never opened to be measured. A path that isn't
21
+ // listed is read from its file, as when there's no such file at all.
22
+ // - An entry that isn't valid is skipped and the image is read; a file
23
+ // that isn't valid JSON, or isn't an object, counts as absent. Nothing
24
+ // here can fail a build.
25
+ //
26
+ // `.writedocs/` is never published (EXCLUDED_TOP_LEVEL_DIRS, lib/pages.js).
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+
30
+ /** Where the file is, from the project root. */
31
+ export const ASSET_DIMENSIONS_FILE = '.writedocs/asset-dimensions.json';
32
+
33
+ const isSize = (n) => Number.isSafeInteger(n) && n > 0;
34
+
35
+ /** The valid entries of the file's text, as a Map of path -> `{ width,
36
+ * height }`. Empty for text that isn't a JSON object. */
37
+ export function parseAssetDimensions(text) {
38
+ const sizes = new Map();
39
+ let data;
40
+ try {
41
+ data = JSON.parse(String(text).replace(/^\uFEFF/, ''));
42
+ } catch {
43
+ return sizes;
44
+ }
45
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return sizes;
46
+ for (const [key, value] of Object.entries(data)) {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
48
+ if (!isSize(value.width) || !isSize(value.height)) continue;
49
+ sizes.set(key, { width: value.width, height: value.height });
50
+ }
51
+ return sizes;
52
+ }
53
+
54
+ // Per project, parsed again only when the file changes - `writedocs dev`
55
+ // keeps running while it's edited.
56
+ const loaded = new Map();
57
+
58
+ function dimensionsFor(contentDir) {
59
+ const file = path.join(contentDir, ...ASSET_DIMENSIONS_FILE.split('/'));
60
+ let stamp;
61
+ try {
62
+ const stat = fs.statSync(file);
63
+ stamp = `${stat.mtimeMs}:${stat.size}`;
64
+ } catch {
65
+ loaded.delete(contentDir);
66
+ return null;
67
+ }
68
+ const known = loaded.get(contentDir);
69
+ if (known?.stamp === stamp) return known.sizes;
70
+ let sizes;
71
+ try {
72
+ sizes = parseAssetDimensions(fs.readFileSync(file, 'utf8'));
73
+ } catch {
74
+ sizes = new Map();
75
+ }
76
+ loaded.set(contentDir, { stamp, sizes });
77
+ return sizes;
78
+ }
79
+
80
+ /** `{ width, height }` for the image file at `file` (an absolute path) when
81
+ * the project's asset-dimensions.json lists it, else null. */
82
+ export function providedImageSize(file, contentDir) {
83
+ if (!file || !contentDir) return null;
84
+ const sizes = dimensionsFor(contentDir);
85
+ if (!sizes || sizes.size === 0) return null;
86
+ const relative = path.relative(contentDir, file);
87
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
88
+ return sizes.get(relative.split(path.sep).join('/')) ?? null;
89
+ }