@writedocs/generator 0.13.3 → 0.13.5

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 (87) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +43 -12
  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 +203 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +1 -1
  10. package/src/cli/dev.js +268 -268
  11. package/src/cli/exit-when-flushed.js +4 -0
  12. package/src/cli/generate-api-pages.js +507 -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 +69 -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 +203 -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 +408 -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 +414 -75
  48. package/src/lib/config-schema.ts +2509 -1905
  49. package/src/lib/config.ts +1316 -1314
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-store-reload-integration.js +101 -101
  52. package/src/lib/icon-data-dev.js +53 -53
  53. package/src/lib/image-size.js +152 -152
  54. package/src/lib/json-schema-descriptions.js +228 -228
  55. package/src/lib/link-check.js +544 -544
  56. package/src/lib/llms-index.ts +90 -90
  57. package/src/lib/mcp-dev-integration.js +65 -65
  58. package/src/lib/mcp-index.ts +102 -102
  59. package/src/lib/mintlify-convert.js +605 -605
  60. package/src/lib/moved-api-pages.js +49 -49
  61. package/src/lib/og-cards.js +33 -33
  62. package/src/lib/og-image.js +235 -235
  63. package/src/lib/openapi-dev-status.js +80 -80
  64. package/src/lib/openapi-reload-integration.js +193 -193
  65. package/src/lib/pages.js +312 -312
  66. package/src/lib/project-files-integration.js +116 -116
  67. package/src/lib/project-files.js +137 -137
  68. package/src/lib/rehype-base-path.js +62 -62
  69. package/src/lib/rehype-image-loading.js +71 -71
  70. package/src/lib/robots-txt.js +21 -21
  71. package/src/lib/search-scope.js +44 -44
  72. package/src/lib/selector-placement.js +50 -50
  73. package/src/lib/seo-tags.js +155 -155
  74. package/src/lib/shiki-code-block.js +7 -1
  75. package/src/lib/site-base.ts +27 -27
  76. package/src/lib/styles-asset-integration.js +291 -291
  77. package/src/lib/wdignore-cases.json +195 -195
  78. package/src/lib/wdignore.js +177 -177
  79. package/src/pages/404.astro +63 -63
  80. package/src/pages/[...slug].astro +1762 -1608
  81. package/src/pages/[...slug].md.ts +93 -93
  82. package/src/pages/llms-full.txt.ts +88 -88
  83. package/src/pages/og/[...slug].png.ts +63 -63
  84. package/src/scripts/mobile-menu.ts +80 -80
  85. package/src/scripts/search.ts +245 -245
  86. package/src/scripts/sidebar-scroll.ts +61 -61
  87. package/src/styles/global.css +40 -40
@@ -1,544 +1,544 @@
1
- // `writedocs broken-links`: every internal link in the content - page
2
- // bodies, the snippets they import, and writedocs.json - checked against the
3
- // site the build would produce, without building it. Plain JavaScript,
4
- // loaded by plain Node from an installed package (see lib/icons.js's
5
- // comment on why not TypeScript).
6
- //
7
- // A link is broken when, on the built site:
8
- // - no page, redirect or file is at its address;
9
- // - its #anchor isn't on the target page (headings, titled components -
10
- // Callout/Accordion/Update and friends - and elements with an `id`).
11
- // #cookie-settings is on every page when writedocs.json turns on
12
- // `integrations.consent`: it opens the consent banner (lib/consent.js);
13
- // - it names a file the build doesn't publish (lib/project-files.js says
14
- // which files of a project are published as they are).
15
- //
16
- // Addresses are worked out the way the build works them out:
17
- // - a page's URL is its frontmatter `slug`, or else its file path with
18
- // every segment put through github-slugger - Astro's own glob-loader
19
- // id (getContentEntryIdAndSlug in astro/dist/content/utils.js), which
20
- // is why `docs/API Guide/v1.2.mdx` is served at /docs/api-guide/v12/;
21
- // - heading ids come from github-slugger too, deduped per page the way
22
- // Astro's rehypeHeadingIds does; titled components' ids from
23
- // lib/mdx-title-anchor-ids.js's own rule;
24
- // - a relative link resolves the way a browser resolves it, from the
25
- // page's URL - which ends in a slash (/docs/guides/setup/), so
26
- // `install` on that page means /docs/guides/setup/install/, not a
27
- // sibling page. Mintlify's URLs have no trailing slash, so migrated
28
- // relative links are the usual casualty; the message says so.
29
- //
30
- // External links (http:, mailto:, ...) aren't checked.
31
- import fs from 'node:fs';
32
- import { estreeText } from './plain-text.js';
33
- import path from 'node:path';
34
- import { createRequire } from 'node:module';
35
- import { pathToFileURL } from 'node:url';
36
- import matter from 'gray-matter';
37
- import { visit } from 'unist-util-visit';
38
- import { findAllPages } from './pages.js';
39
- import { createJsonLocator, contextMenuOptions } from './config-schema.js';
40
- import { writedocsTempDir } from './writedocs-temp-dir.js';
41
- import { folderAddresses } from './folder-redirects.js';
42
- import { isPublishedFile, readSpecPaths } from './project-files.js';
43
- import { projectIgnore } from './project-ignore.js';
44
- import { readMovedApiPages } from './moved-api-pages.js';
45
- import { consentOptions, CONSENT_SETTINGS_ANCHOR } from './consent.js';
46
-
47
- // The same github-slugger Astro builds page URLs and heading ids with -
48
- // resolved through Astro itself, so the two can't drift apart.
49
- let sluggerModule = null;
50
- async function loadSlugger() {
51
- if (!sluggerModule) {
52
- const require = createRequire(import.meta.url);
53
- const fromAstro = createRequire(require.resolve('astro/package.json'));
54
- sluggerModule = await import(pathToFileURL(fromAstro.resolve('github-slugger')).href);
55
- }
56
- return sluggerModule;
57
- }
58
-
59
- const processors = {};
60
- async function parse(text, format) {
61
- if (!processors[format]) {
62
- const { createProcessor } = await import('@mdx-js/mdx');
63
- processors[format] = createProcessor({ format });
64
- }
65
- return processors[format].parse(text);
66
- }
67
-
68
- // Images and fonts are published from anywhere in the project; every other
69
- // file only from public/ (lib/styles-asset-integration.js).
70
- const ASSET_EXTENSIONS = new Set(['.svg', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.ico', '.woff', '.woff2', '.ttf', '.otf']);
71
- // lib/mdx-title-anchor-ids.js
72
- const TITLED_COMPONENTS = ['Callout', 'Note', 'Info', 'Tip', 'Warning', 'Danger', 'Check', 'Accordion', 'Update'];
73
- const titleSlug = (value) =>
74
- value
75
- .toLowerCase()
76
- .replace(/[^a-z0-9]+/g, '-')
77
- .replace(/^-+|-+$/g, '');
78
-
79
- const BASE = 'http://writedocs.invalid';
80
-
81
- function normalizeEntryId(id) {
82
- const trimmed = String(id).replace(/^\/+/, '').replace(/\/+$/, '');
83
- return trimmed === '' ? 'index' : trimmed;
84
- }
85
- const urlForId = (id) => (id === 'index' ? '/' : `/${id}/`);
86
-
87
- /** (rel, frontmatterSlug) => the URL the build serves that page at: its
88
- * frontmatter `slug`, or its file path with each segment through
89
- * github-slugger (see this file's header). Also used by
90
- * lib/writedocs-legacy-convert.js, for redirects from old addresses. */
91
- export async function pageUrlResolver() {
92
- const { slug } = await loadSlugger();
93
- return (rel, frontmatterSlug) =>
94
- urlForId(
95
- frontmatterSlug
96
- ? normalizeEntryId(frontmatterSlug)
97
- : normalizeEntryId(
98
- rel
99
- .replace(/\.mdx?$/i, '')
100
- .split('/')
101
- .map((segment) => slug(segment))
102
- .join('/')
103
- .replace(/\/index$/, '')
104
- )
105
- );
106
- }
107
-
108
- function textOf(node) {
109
- if (typeof node.value === 'string' && (node.type === 'text' || node.type === 'inlineCode')) return node.value;
110
- return (node.children ?? []).map(textOf).join('');
111
- }
112
-
113
- function attribute(node, name) {
114
- const attr = node.attributes?.find((a) => a.type === 'mdxJsxAttribute' && a.name === name);
115
- return attr && typeof attr.value === 'string' ? attr.value : null;
116
- }
117
-
118
- /** A component's title as text - a JSX title (`title={<><code>X</code> y</>}`)
119
- * included, the way lib/mdx-title-anchor-ids.js reads it. */
120
- function titleText(node, name) {
121
- const attr = node.attributes?.find((a) => a.type === 'mdxJsxAttribute' && a.name === name);
122
- if (!attr) return null;
123
- return typeof attr.value === 'string' ? attr.value : estreeText(attr.value?.data?.estree) || null;
124
- }
125
-
126
- /** Everything a page or snippet file links to and can be linked to. */
127
- async function scanFile(absPath, { slug, Slugger }) {
128
- let raw;
129
- try {
130
- raw = fs.readFileSync(absPath, 'utf-8').replace(/\r\n/g, '\n');
131
- } catch {
132
- return null;
133
- }
134
- let parsed;
135
- try {
136
- parsed = matter(raw, {});
137
- } catch {
138
- return null; // invalid frontmatter - `writedocs validate` reports it
139
- }
140
- const bodyStart = raw.lastIndexOf(parsed.content);
141
- const lineOffset = bodyStart > 0 ? raw.slice(0, bodyStart).split('\n').length - 1 : 0;
142
- let tree;
143
- try {
144
- tree = await parse(parsed.content, /\.mdx$/i.test(absPath) ? 'mdx' : 'md');
145
- } catch {
146
- return null; // doesn't parse - `writedocs validate` reports it
147
- }
148
-
149
- const links = []; // { href, line, kind: 'link' | 'image' | 'src' }
150
- const anchors = new Set();
151
- const imports = [];
152
- const lineOf = (node) => (node.position?.start?.line ? node.position.start.line + lineOffset : undefined);
153
- const headingSlugger = new Slugger();
154
- const titleSeen = new Map();
155
-
156
- visit(tree, (node) => {
157
- switch (node.type) {
158
- case 'link':
159
- case 'definition':
160
- links.push({ href: node.url, line: lineOf(node), kind: 'link' });
161
- break;
162
- case 'image':
163
- links.push({ href: node.url, line: lineOf(node), kind: 'image' });
164
- break;
165
- case 'heading': {
166
- const text = textOf(node);
167
- if (text.trim()) anchors.add(headingSlugger.slug(text));
168
- break;
169
- }
170
- case 'html': {
171
- // Raw HTML in a .md page.
172
- for (const m of node.value.matchAll(/\bhref\s*=\s*["']([^"']*)["']/gi)) links.push({ href: m[1], line: lineOf(node), kind: 'link' });
173
- for (const m of node.value.matchAll(/\bsrc\s*=\s*["']([^"']*)["']/gi)) links.push({ href: m[1], line: lineOf(node), kind: 'src' });
174
- for (const m of node.value.matchAll(/\b(?:id|name)\s*=\s*["']([^"']+)["']/gi)) anchors.add(m[1]);
175
- break;
176
- }
177
- case 'mdxjsEsm':
178
- for (const m of node.value.matchAll(/\bfrom\s*['"]([^'"]+\.mdx?)['"]/g)) imports.push(m[1]);
179
- break;
180
- case 'mdxJsxFlowElement':
181
- case 'mdxJsxTextElement': {
182
- const href = attribute(node, 'href');
183
- if (href !== null) links.push({ href, line: lineOf(node), kind: 'link' });
184
- if (!/^(iframe|script|embed)$/i.test(node.name ?? '')) {
185
- for (const name of ['src', 'img']) {
186
- const value = attribute(node, name);
187
- if (value !== null) links.push({ href: value, line: lineOf(node), kind: 'src' });
188
- }
189
- }
190
- const id = attribute(node, 'id');
191
- if (id) anchors.add(id);
192
- if (TITLED_COMPONENTS.includes(node.name)) {
193
- const title = titleText(node, node.name === 'Update' ? 'label' : 'title');
194
- const base = title ? titleSlug(title) : '';
195
- if (base) {
196
- const prior = titleSeen.get(base) ?? 0;
197
- titleSeen.set(base, prior + 1);
198
- anchors.add(prior === 0 ? base : `${base}-${prior + 1}`);
199
- }
200
- }
201
- break;
202
- }
203
- }
204
- });
205
- return { data: parsed.data ?? {}, links, anchors, imports };
206
- }
207
-
208
- function editDistance(a, b) {
209
- const row = Array.from({ length: b.length + 1 }, (_, i) => i);
210
- for (let i = 1; i <= a.length; i++) {
211
- let prev = row[0];
212
- row[0] = i;
213
- for (let j = 1; j <= b.length; j++) {
214
- const tmp = row[j];
215
- row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
216
- prev = tmp;
217
- }
218
- }
219
- return row[b.length];
220
- }
221
-
222
- function closest(value, candidates) {
223
- let best = null;
224
- let bestDistance = Infinity;
225
- for (const c of candidates) {
226
- const d = editDistance(value.toLowerCase(), c.toLowerCase());
227
- if (d < bestDistance) {
228
- best = c;
229
- bestDistance = d;
230
- }
231
- }
232
- return best !== null && bestDistance <= Math.max(2, Math.floor(value.length * 0.3)) ? best : null;
233
- }
234
-
235
- /** Generated OpenAPI pages' URLs, from the manifests generateApiPages()
236
- * (src/cli/generate-api-pages.js) wrote - it runs first. */
237
- function generatedPageUrls(contentDir) {
238
- const urls = new Set();
239
- const root = path.join(writedocsTempDir(contentDir), 'openapi');
240
- (function walk(dir) {
241
- let entries;
242
- try {
243
- entries = fs.readdirSync(dir, { withFileTypes: true });
244
- } catch {
245
- return;
246
- }
247
- for (const entry of entries) {
248
- const abs = path.join(dir, entry.name);
249
- if (entry.isDirectory()) walk(abs);
250
- else if (entry.name === 'manifest.json') {
251
- try {
252
- for (const op of JSON.parse(fs.readFileSync(abs, 'utf-8'))) if (op.generated) urls.add(urlForId(normalizeEntryId(op.slug)));
253
- } catch {}
254
- }
255
- }
256
- })(root);
257
- return urls;
258
- }
259
-
260
- /** Every `href` in writedocs.json, and redirect destinations. */
261
- function configLinks(config) {
262
- const found = [];
263
- (function walk(node, trail) {
264
- if (Array.isArray(node)) node.forEach((item, i) => walk(item, [...trail, i]));
265
- else if (node && typeof node === 'object') {
266
- for (const [key, value] of Object.entries(node)) {
267
- if (key === 'href' && typeof value === 'string') found.push({ href: value, path: [...trail, key] });
268
- else walk(value, [...trail, key]);
269
- }
270
- }
271
- })(config, []);
272
- (Array.isArray(config?.redirects) ? config.redirects : []).forEach((r, i) => {
273
- if (typeof r?.destination === 'string') found.push({ href: r.destination, path: ['redirects', i, 'destination'] });
274
- });
275
- return found;
276
- }
277
-
278
- /**
279
- * Checks every internal link in `contentDir`. `configText` is writedocs.json's
280
- * raw text (valid JSON - the CLI checks that first). Returns
281
- * { pages, links, external, broken } - `broken` is a list of issues shaped
282
- * like lib/content-check.js's: { file, line?, message, suggestion? }.
283
- */
284
- export async function checkLinks(contentDir, configText) {
285
- const { slug, default: Slugger } = await loadSlugger();
286
- const urlOf = await pageUrlResolver();
287
- const config = JSON.parse(configText);
288
-
289
- // --- What the site has -------------------------------------------------
290
- const pageFiles = findAllPages(contentDir);
291
- const pages = new Map(); // url -> { rel, abs, scan }
292
- const urlOfFile = new Map(); // rel -> url
293
- const scans = new Map(); // abs -> scanFile() result (or null)
294
- const scanOnce = async (abs) => {
295
- if (!scans.has(abs)) scans.set(abs, await scanFile(abs, { slug, Slugger }));
296
- return scans.get(abs);
297
- };
298
- for (const rel of pageFiles) {
299
- const abs = path.join(contentDir, rel);
300
- const scan = await scanOnce(abs);
301
- const url = urlOf(rel, scan?.data?.slug);
302
- pages.set(url, { rel, abs, scan });
303
- urlOfFile.set(rel, url);
304
- }
305
- const generated = generatedPageUrls(contentDir);
306
- const redirects = new Set(
307
- (Array.isArray(config.redirects) ? config.redirects : [])
308
- .map((r) => (typeof r?.source === 'string' ? `/${r.source.replace(/^\/+|\/+$/g, '')}/`.replace(/^\/\/$/, '/') : null))
309
- .filter(Boolean)
310
- );
311
- // Where generated API pages used to be - redirects too (lib/moved-api-pages.js).
312
- for (const { source } of readMovedApiPages(contentDir)) redirects.add(`${source}/`);
313
- const specs = readSpecPaths(contentDir);
314
- const rules = projectIgnore(contentDir);
315
- const special = new Set(['/llms.txt', '/llms-full.txt', '/404.html', '/404/', '/robots.txt']);
316
- // With the consent banner on, #cookie-settings opens it from any page.
317
- const pageWideAnchors = new Set(consentOptions(config.integrations?.consent) ? [CONSENT_SETTINGS_ANCHOR] : []);
318
- if (config.domain) ['/sitemap.xml', '/sitemap-index.xml'].forEach((p) => special.add(p));
319
- const knownUrls = [...pages.keys(), ...generated, ...redirects];
320
- // Folder addresses with no page of their own redirect to one under them
321
- // (lib/folder-redirects.js), so a link to one isn't broken.
322
- const folders = new Set(
323
- [...folderAddresses([...pages.keys(), ...generated].map((url) => url.replace(/^\/+|\/+$/g, '')))].map((folder) => `/${folder}/`)
324
- );
325
-
326
- // Anchors a page can be linked to: its own, plus those of every snippet
327
- // it imports (they render inside it).
328
- const snippetPath = (spec, fromAbs) =>
329
- spec.startsWith('/') ? path.join(contentDir, spec) : path.resolve(path.dirname(fromAbs), spec);
330
- const anchorCache = new Map();
331
- async function anchorsOf(abs, seen = new Set()) {
332
- if (anchorCache.has(abs)) return anchorCache.get(abs);
333
- if (seen.has(abs)) return new Set();
334
- seen.add(abs);
335
- const scan = await scanOnce(abs);
336
- const all = new Set(scan?.anchors ?? []);
337
- for (const spec of scan?.imports ?? []) for (const a of await anchorsOf(snippetPath(spec, abs), seen)) all.add(a);
338
- anchorCache.set(abs, all);
339
- return all;
340
- }
341
-
342
- // Root-relative image/font paths something displays - see the "Any other
343
- // file" case below. Snippets are scanned here too, so the set is complete
344
- // before the first link is checked.
345
- const displayedAssets = new Set();
346
- async function collectDisplayed(abs, seen = new Set()) {
347
- if (seen.has(abs)) return;
348
- seen.add(abs);
349
- const scan = await scanOnce(abs);
350
- for (const link of scan?.links ?? []) if (link.kind !== 'link' && link.href.startsWith('/')) displayedAssets.add(link.href.split(/[?#]/)[0]);
351
- for (const spec of scan?.imports ?? []) await collectDisplayed(snippetPath(spec, abs), seen);
352
- }
353
- for (const page of pages.values()) await collectDisplayed(page.abs);
354
- (function walk(node) {
355
- if (typeof node === 'string') {
356
- if (node.startsWith('/') && ASSET_EXTENSIONS.has(path.posix.extname(node).toLowerCase())) displayedAssets.add(node);
357
- } else if (Array.isArray(node)) node.forEach(walk);
358
- else if (node && typeof node === 'object') Object.values(node).forEach(walk);
359
- })(config);
360
-
361
- // --- Checking one link -------------------------------------------------
362
- const broken = [];
363
- const reported = new Set();
364
- let checked = 0;
365
- let external = 0;
366
-
367
- /** `pageUrl`: the URL of the page the link renders on (relative links
368
- * resolve from it). `fileAbs`: the file the link is written in. */
369
- async function check(href, { file, line, kind, pageUrl, fileAbs }) {
370
- const value = String(href ?? '').trim();
371
- if (!value || value === '#' || value.startsWith('{') || value.includes('{{')) return;
372
- if (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('//')) {
373
- external += 1;
374
- return;
375
- }
376
- checked += 1;
377
- const report = (message, suggestion) => {
378
- const key = `${file}\n${line}\n${value}`;
379
- if (reported.has(key)) return;
380
- reported.add(key);
381
- broken.push({ file, line, message, suggestion });
382
- };
383
-
384
- // A Markdown image with a relative path is resolved from the file's own
385
- // folder at build time (Astro's image pipeline), not from the URL.
386
- if (kind === 'image' && fileAbs && !value.startsWith('/') && !value.startsWith('#')) {
387
- const target = path.resolve(path.dirname(fileAbs), decodeURI(value.split(/[?#]/)[0]));
388
- if (!fs.existsSync(target)) report(`Image ${value} - there's no file at ${path.relative(contentDir, target).split(path.sep).join('/')}.`);
389
- return;
390
- }
391
-
392
- let url;
393
- try {
394
- url = new URL(value, BASE + (pageUrl ?? '/'));
395
- } catch {
396
- report(`${value} - not a valid link.`);
397
- return;
398
- }
399
- let pathname;
400
- try {
401
- pathname = decodeURI(url.pathname);
402
- } catch {
403
- pathname = url.pathname;
404
- }
405
- const hash = url.hash ? decodeURIComponent(url.hash.slice(1)) : '';
406
- const extension = path.posix.extname(pathname.replace(/\/+$/, '')).toLowerCase();
407
- const isRelative = !value.startsWith('/') && !value.startsWith('#');
408
-
409
- // A page (or /x/index.html).
410
- let pageKey = null;
411
- if (!extension || pathname.endsWith('/index.html')) {
412
- pageKey = pathname.replace(/\/index\.html$/, '/').replace(/\/?$/, '/');
413
- }
414
- if (pageKey !== null) {
415
- if (pages.has(pageKey)) {
416
- if (!hash || hash === 'top' || pageWideAnchors.has(hash)) return;
417
- const anchors = await anchorsOf(pages.get(pageKey).abs);
418
- if (anchors.has(hash)) return;
419
- const suggestion = closest(hash, [...anchors]);
420
- const onPage = pageKey === pageUrl && value.startsWith('#') ? 'this page' : pageKey;
421
- report(
422
- `${value} - ${onPage} has no heading or anchor "#${hash}".`,
423
- suggestion ? `Did you mean #${suggestion}?` : undefined
424
- );
425
- return;
426
- }
427
- // "/" always exists: the home page, or a redirect to the first page.
428
- if (pageKey === '/' || generated.has(pageKey) || redirects.has(pageKey) || folders.has(pageKey) || special.has(pageKey.replace(/\/$/, '') || '/')) return;
429
- if (special.has(pathname)) return;
430
-
431
- // Mintlify-style relative link: resolved from the file's folder
432
- // instead of the page's URL, would it land on a page?
433
- if (isRelative && pageUrl && pageUrl !== '/') {
434
- const siblingBase = pageUrl.replace(/[^/]+\/$/, '');
435
- const alt = new URL(value, BASE + siblingBase);
436
- const altKey = decodeURI(alt.pathname).replace(/\/?$/, '/');
437
- if (pages.has(altKey) || generated.has(altKey)) {
438
- report(
439
- `${value} - relative links resolve from the page's own URL (${pageUrl}), so this one points to ${pageKey}, which doesn't exist.`,
440
- `Write ${altKey}${alt.hash} instead.`
441
- );
442
- return;
443
- }
444
- }
445
- const suggestion = closest(pageKey, knownUrls);
446
- report(`${value} - there's no page at ${pageKey}.`, suggestion ? `Did you mean ${suggestion}?` : undefined);
447
- return;
448
- }
449
-
450
- // A link to a page's source file (docs/setup.mdx) instead of its URL.
451
- if (extension === '.mdx' || extension === '.md') {
452
- const bare = pathname.replace(/\.mdx?$/i, '').replace(/\/?$/, '/');
453
- if (extension === '.md' && contextMenuOptions(config.contextMenu).length && pages.has(bare)) return; // the page's Markdown copy (on unless "contextMenu": false)
454
- // Written as a file path, so look it up as one: from the file's own
455
- // folder when relative.
456
- const filePath = isRelative && fileAbs ? path.resolve(path.dirname(fileAbs), decodeURI(value.split(/[?#]/)[0])) : path.join(contentDir, pathname);
457
- const rel = path.relative(contentDir, filePath).split(path.sep).join('/');
458
- const byFile = urlOfFile.get(rel) ?? (pages.has(bare) ? bare : null);
459
- report(
460
- `${value} - links to a source file, which isn't published.`,
461
- byFile ? `Link to the page's URL instead: ${byFile}` : undefined
462
- );
463
- return;
464
- }
465
-
466
- // Any other file.
467
- if (special.has(pathname)) return;
468
- const segments = pathname.replace(/^\/+/, '').split('/');
469
- // A file the ignore rules leave out (lib/wdignore.js) is never published,
470
- // in public/ or anywhere else - so a link to it is a broken one.
471
- const leftOut = (rel) => {
472
- if (!rules.ignores(rel)) return false;
473
- report(
474
- `${value} - ${rel} is in the project, but the ignore rules leave it out, so it isn't published.`,
475
- rules.isLocked(rel)
476
- ? "It's a kind of file that is never published (a key, a .env, .git/)."
477
- : `To publish it, bring it back in .wdignore - a line with !${rel}, or its folder's (!folder/) when the whole folder is left out.`
478
- );
479
- return true;
480
- };
481
- if (fs.existsSync(path.join(contentDir, 'public', ...segments))) {
482
- leftOut(['public', ...segments].join('/'));
483
- return;
484
- }
485
- const inProject = path.join(contentDir, ...segments);
486
- if (fs.existsSync(inProject)) {
487
- if (leftOut(segments.join('/'))) return;
488
- // The build publishes the project's files at their own path
489
- // (lib/project-files.js) - images, PDFs, data files. What it doesn't:
490
- // the files the site is built from (writedocs.json, an OpenAPI spec),
491
- // anything in a dot-folder, and kinds of file it doesn't know.
492
- if (isPublishedFile(segments.join('/'), { specs, rules })) return;
493
- // An image or font a page displays is copied wherever it is
494
- // (lib/styles-asset-integration.js).
495
- if (ASSET_EXTENSIONS.has(extension) && displayedAssets.has(pathname)) return;
496
- report(
497
- `${value} - ${pathname} is in the project, but it isn't a file the build publishes.`,
498
- `To publish it as it is, move it to public${pathname}.`
499
- );
500
- return;
501
- }
502
- report(`${value} - there's no file at ${pathname}.`);
503
- }
504
-
505
- // --- The pages, their snippets, and writedocs.json ---------------------
506
- const relOf = (abs) => path.relative(contentDir, abs).split(path.sep).join('/');
507
- const snippetsChecked = new Set();
508
- async function checkFile(abs, pageUrl, seen) {
509
- const scan = await scanOnce(abs);
510
- if (!scan) return;
511
- const file = relOf(abs);
512
- for (const link of scan.links) await check(link.href, { file, line: link.line, kind: link.kind, pageUrl, fileAbs: abs });
513
- for (const spec of scan.imports) {
514
- const snippet = snippetPath(spec, abs);
515
- // A snippet the ignore rules leave out (lib/wdignore.js) isn't part of
516
- // the project a site is built from: where the rules are applied before
517
- // the build (the WriteDocs platform's sync), the import finds no file.
518
- const snippetRel = relOf(snippet);
519
- if (!snippetRel.startsWith('..') && fs.existsSync(snippet) && rules.ignores(snippetRel)) {
520
- const key = [file, 'import', snippetRel].join('\n');
521
- if (!reported.has(key)) {
522
- reported.add(key);
523
- broken.push({
524
- file,
525
- message: `import of ${spec} - ${snippetRel} is in the project, but the ignore rules leave it out, so the build can't count on it.`,
526
- suggestion: rules.isLocked(snippetRel) ? 'Move the snippet out of that path.' : `Bring it back in .wdignore (!${snippetRel}), or move the snippet.`,
527
- });
528
- }
529
- }
530
- if (seen.has(snippet) || snippetsChecked.has(`${snippet}\n${pageUrl}`)) continue;
531
- snippetsChecked.add(`${snippet}\n${pageUrl}`);
532
- await checkFile(snippet, pageUrl, new Set([...seen, snippet]));
533
- }
534
- }
535
- for (const [url, page] of pages) await checkFile(page.abs, url, new Set([page.abs]));
536
-
537
- const locate = createJsonLocator(configText);
538
- for (const { href, path: jsonPath } of configLinks(config)) {
539
- await check(href, { file: 'writedocs.json', line: locate(jsonPath)?.line, kind: 'link', pageUrl: '/' });
540
- }
541
-
542
- broken.sort((a, b) => a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0));
543
- return { pages: pages.size, links: checked, external, broken };
544
- }
1
+ // `writedocs broken-links`: every internal link in the content - page
2
+ // bodies, the snippets they import, and writedocs.json - checked against the
3
+ // site the build would produce, without building it. Plain JavaScript,
4
+ // loaded by plain Node from an installed package (see lib/icons.js's
5
+ // comment on why not TypeScript).
6
+ //
7
+ // A link is broken when, on the built site:
8
+ // - no page, redirect or file is at its address;
9
+ // - its #anchor isn't on the target page (headings, titled components -
10
+ // Callout/Accordion/Update and friends - and elements with an `id`).
11
+ // #cookie-settings is on every page when writedocs.json turns on
12
+ // `integrations.consent`: it opens the consent banner (lib/consent.js);
13
+ // - it names a file the build doesn't publish (lib/project-files.js says
14
+ // which files of a project are published as they are).
15
+ //
16
+ // Addresses are worked out the way the build works them out:
17
+ // - a page's URL is its frontmatter `slug`, or else its file path with
18
+ // every segment put through github-slugger - Astro's own glob-loader
19
+ // id (getContentEntryIdAndSlug in astro/dist/content/utils.js), which
20
+ // is why `docs/API Guide/v1.2.mdx` is served at /docs/api-guide/v12/;
21
+ // - heading ids come from github-slugger too, deduped per page the way
22
+ // Astro's rehypeHeadingIds does; titled components' ids from
23
+ // lib/mdx-title-anchor-ids.js's own rule;
24
+ // - a relative link resolves the way a browser resolves it, from the
25
+ // page's URL - which ends in a slash (/docs/guides/setup/), so
26
+ // `install` on that page means /docs/guides/setup/install/, not a
27
+ // sibling page. Mintlify's URLs have no trailing slash, so migrated
28
+ // relative links are the usual casualty; the message says so.
29
+ //
30
+ // External links (http:, mailto:, ...) aren't checked.
31
+ import fs from 'node:fs';
32
+ import { estreeText } from './plain-text.js';
33
+ import path from 'node:path';
34
+ import { createRequire } from 'node:module';
35
+ import { pathToFileURL } from 'node:url';
36
+ import matter from 'gray-matter';
37
+ import { visit } from 'unist-util-visit';
38
+ import { findAllPages } from './pages.js';
39
+ import { createJsonLocator, contextMenuOptions } from './config-schema.js';
40
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
41
+ import { folderAddresses } from './folder-redirects.js';
42
+ import { isPublishedFile, readSpecPaths } from './project-files.js';
43
+ import { projectIgnore } from './project-ignore.js';
44
+ import { readMovedApiPages } from './moved-api-pages.js';
45
+ import { consentOptions, CONSENT_SETTINGS_ANCHOR } from './consent.js';
46
+
47
+ // The same github-slugger Astro builds page URLs and heading ids with -
48
+ // resolved through Astro itself, so the two can't drift apart.
49
+ let sluggerModule = null;
50
+ async function loadSlugger() {
51
+ if (!sluggerModule) {
52
+ const require = createRequire(import.meta.url);
53
+ const fromAstro = createRequire(require.resolve('astro/package.json'));
54
+ sluggerModule = await import(pathToFileURL(fromAstro.resolve('github-slugger')).href);
55
+ }
56
+ return sluggerModule;
57
+ }
58
+
59
+ const processors = {};
60
+ async function parse(text, format) {
61
+ if (!processors[format]) {
62
+ const { createProcessor } = await import('@mdx-js/mdx');
63
+ processors[format] = createProcessor({ format });
64
+ }
65
+ return processors[format].parse(text);
66
+ }
67
+
68
+ // Images and fonts are published from anywhere in the project; every other
69
+ // file only from public/ (lib/styles-asset-integration.js).
70
+ const ASSET_EXTENSIONS = new Set(['.svg', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.ico', '.woff', '.woff2', '.ttf', '.otf']);
71
+ // lib/mdx-title-anchor-ids.js
72
+ const TITLED_COMPONENTS = ['Callout', 'Note', 'Info', 'Tip', 'Warning', 'Danger', 'Check', 'Accordion', 'Update'];
73
+ const titleSlug = (value) =>
74
+ value
75
+ .toLowerCase()
76
+ .replace(/[^a-z0-9]+/g, '-')
77
+ .replace(/^-+|-+$/g, '');
78
+
79
+ const BASE = 'http://writedocs.invalid';
80
+
81
+ function normalizeEntryId(id) {
82
+ const trimmed = String(id).replace(/^\/+/, '').replace(/\/+$/, '');
83
+ return trimmed === '' ? 'index' : trimmed;
84
+ }
85
+ const urlForId = (id) => (id === 'index' ? '/' : `/${id}/`);
86
+
87
+ /** (rel, frontmatterSlug) => the URL the build serves that page at: its
88
+ * frontmatter `slug`, or its file path with each segment through
89
+ * github-slugger (see this file's header). Also used by
90
+ * lib/writedocs-legacy-convert.js, for redirects from old addresses. */
91
+ export async function pageUrlResolver() {
92
+ const { slug } = await loadSlugger();
93
+ return (rel, frontmatterSlug) =>
94
+ urlForId(
95
+ frontmatterSlug
96
+ ? normalizeEntryId(frontmatterSlug)
97
+ : normalizeEntryId(
98
+ rel
99
+ .replace(/\.mdx?$/i, '')
100
+ .split('/')
101
+ .map((segment) => slug(segment))
102
+ .join('/')
103
+ .replace(/\/index$/, '')
104
+ )
105
+ );
106
+ }
107
+
108
+ function textOf(node) {
109
+ if (typeof node.value === 'string' && (node.type === 'text' || node.type === 'inlineCode')) return node.value;
110
+ return (node.children ?? []).map(textOf).join('');
111
+ }
112
+
113
+ function attribute(node, name) {
114
+ const attr = node.attributes?.find((a) => a.type === 'mdxJsxAttribute' && a.name === name);
115
+ return attr && typeof attr.value === 'string' ? attr.value : null;
116
+ }
117
+
118
+ /** A component's title as text - a JSX title (`title={<><code>X</code> y</>}`)
119
+ * included, the way lib/mdx-title-anchor-ids.js reads it. */
120
+ function titleText(node, name) {
121
+ const attr = node.attributes?.find((a) => a.type === 'mdxJsxAttribute' && a.name === name);
122
+ if (!attr) return null;
123
+ return typeof attr.value === 'string' ? attr.value : estreeText(attr.value?.data?.estree) || null;
124
+ }
125
+
126
+ /** Everything a page or snippet file links to and can be linked to. */
127
+ async function scanFile(absPath, { slug, Slugger }) {
128
+ let raw;
129
+ try {
130
+ raw = fs.readFileSync(absPath, 'utf-8').replace(/\r\n/g, '\n');
131
+ } catch {
132
+ return null;
133
+ }
134
+ let parsed;
135
+ try {
136
+ parsed = matter(raw, {});
137
+ } catch {
138
+ return null; // invalid frontmatter - `writedocs validate` reports it
139
+ }
140
+ const bodyStart = raw.lastIndexOf(parsed.content);
141
+ const lineOffset = bodyStart > 0 ? raw.slice(0, bodyStart).split('\n').length - 1 : 0;
142
+ let tree;
143
+ try {
144
+ tree = await parse(parsed.content, /\.mdx$/i.test(absPath) ? 'mdx' : 'md');
145
+ } catch {
146
+ return null; // doesn't parse - `writedocs validate` reports it
147
+ }
148
+
149
+ const links = []; // { href, line, kind: 'link' | 'image' | 'src' }
150
+ const anchors = new Set();
151
+ const imports = [];
152
+ const lineOf = (node) => (node.position?.start?.line ? node.position.start.line + lineOffset : undefined);
153
+ const headingSlugger = new Slugger();
154
+ const titleSeen = new Map();
155
+
156
+ visit(tree, (node) => {
157
+ switch (node.type) {
158
+ case 'link':
159
+ case 'definition':
160
+ links.push({ href: node.url, line: lineOf(node), kind: 'link' });
161
+ break;
162
+ case 'image':
163
+ links.push({ href: node.url, line: lineOf(node), kind: 'image' });
164
+ break;
165
+ case 'heading': {
166
+ const text = textOf(node);
167
+ if (text.trim()) anchors.add(headingSlugger.slug(text));
168
+ break;
169
+ }
170
+ case 'html': {
171
+ // Raw HTML in a .md page.
172
+ for (const m of node.value.matchAll(/\bhref\s*=\s*["']([^"']*)["']/gi)) links.push({ href: m[1], line: lineOf(node), kind: 'link' });
173
+ for (const m of node.value.matchAll(/\bsrc\s*=\s*["']([^"']*)["']/gi)) links.push({ href: m[1], line: lineOf(node), kind: 'src' });
174
+ for (const m of node.value.matchAll(/\b(?:id|name)\s*=\s*["']([^"']+)["']/gi)) anchors.add(m[1]);
175
+ break;
176
+ }
177
+ case 'mdxjsEsm':
178
+ for (const m of node.value.matchAll(/\bfrom\s*['"]([^'"]+\.mdx?)['"]/g)) imports.push(m[1]);
179
+ break;
180
+ case 'mdxJsxFlowElement':
181
+ case 'mdxJsxTextElement': {
182
+ const href = attribute(node, 'href');
183
+ if (href !== null) links.push({ href, line: lineOf(node), kind: 'link' });
184
+ if (!/^(iframe|script|embed)$/i.test(node.name ?? '')) {
185
+ for (const name of ['src', 'img']) {
186
+ const value = attribute(node, name);
187
+ if (value !== null) links.push({ href: value, line: lineOf(node), kind: 'src' });
188
+ }
189
+ }
190
+ const id = attribute(node, 'id');
191
+ if (id) anchors.add(id);
192
+ if (TITLED_COMPONENTS.includes(node.name)) {
193
+ const title = titleText(node, node.name === 'Update' ? 'label' : 'title');
194
+ const base = title ? titleSlug(title) : '';
195
+ if (base) {
196
+ const prior = titleSeen.get(base) ?? 0;
197
+ titleSeen.set(base, prior + 1);
198
+ anchors.add(prior === 0 ? base : `${base}-${prior + 1}`);
199
+ }
200
+ }
201
+ break;
202
+ }
203
+ }
204
+ });
205
+ return { data: parsed.data ?? {}, links, anchors, imports };
206
+ }
207
+
208
+ function editDistance(a, b) {
209
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
210
+ for (let i = 1; i <= a.length; i++) {
211
+ let prev = row[0];
212
+ row[0] = i;
213
+ for (let j = 1; j <= b.length; j++) {
214
+ const tmp = row[j];
215
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
216
+ prev = tmp;
217
+ }
218
+ }
219
+ return row[b.length];
220
+ }
221
+
222
+ function closest(value, candidates) {
223
+ let best = null;
224
+ let bestDistance = Infinity;
225
+ for (const c of candidates) {
226
+ const d = editDistance(value.toLowerCase(), c.toLowerCase());
227
+ if (d < bestDistance) {
228
+ best = c;
229
+ bestDistance = d;
230
+ }
231
+ }
232
+ return best !== null && bestDistance <= Math.max(2, Math.floor(value.length * 0.3)) ? best : null;
233
+ }
234
+
235
+ /** Generated OpenAPI pages' URLs, from the manifests generateApiPages()
236
+ * (src/cli/generate-api-pages.js) wrote - it runs first. */
237
+ function generatedPageUrls(contentDir) {
238
+ const urls = new Set();
239
+ const root = path.join(writedocsTempDir(contentDir), 'openapi');
240
+ (function walk(dir) {
241
+ let entries;
242
+ try {
243
+ entries = fs.readdirSync(dir, { withFileTypes: true });
244
+ } catch {
245
+ return;
246
+ }
247
+ for (const entry of entries) {
248
+ const abs = path.join(dir, entry.name);
249
+ if (entry.isDirectory()) walk(abs);
250
+ else if (entry.name === 'manifest.json') {
251
+ try {
252
+ for (const op of JSON.parse(fs.readFileSync(abs, 'utf-8'))) if (op.generated) urls.add(urlForId(normalizeEntryId(op.slug)));
253
+ } catch {}
254
+ }
255
+ }
256
+ })(root);
257
+ return urls;
258
+ }
259
+
260
+ /** Every `href` in writedocs.json, and redirect destinations. */
261
+ function configLinks(config) {
262
+ const found = [];
263
+ (function walk(node, trail) {
264
+ if (Array.isArray(node)) node.forEach((item, i) => walk(item, [...trail, i]));
265
+ else if (node && typeof node === 'object') {
266
+ for (const [key, value] of Object.entries(node)) {
267
+ if (key === 'href' && typeof value === 'string') found.push({ href: value, path: [...trail, key] });
268
+ else walk(value, [...trail, key]);
269
+ }
270
+ }
271
+ })(config, []);
272
+ (Array.isArray(config?.redirects) ? config.redirects : []).forEach((r, i) => {
273
+ if (typeof r?.destination === 'string') found.push({ href: r.destination, path: ['redirects', i, 'destination'] });
274
+ });
275
+ return found;
276
+ }
277
+
278
+ /**
279
+ * Checks every internal link in `contentDir`. `configText` is writedocs.json's
280
+ * raw text (valid JSON - the CLI checks that first). Returns
281
+ * { pages, links, external, broken } - `broken` is a list of issues shaped
282
+ * like lib/content-check.js's: { file, line?, message, suggestion? }.
283
+ */
284
+ export async function checkLinks(contentDir, configText) {
285
+ const { slug, default: Slugger } = await loadSlugger();
286
+ const urlOf = await pageUrlResolver();
287
+ const config = JSON.parse(configText);
288
+
289
+ // --- What the site has -------------------------------------------------
290
+ const pageFiles = findAllPages(contentDir);
291
+ const pages = new Map(); // url -> { rel, abs, scan }
292
+ const urlOfFile = new Map(); // rel -> url
293
+ const scans = new Map(); // abs -> scanFile() result (or null)
294
+ const scanOnce = async (abs) => {
295
+ if (!scans.has(abs)) scans.set(abs, await scanFile(abs, { slug, Slugger }));
296
+ return scans.get(abs);
297
+ };
298
+ for (const rel of pageFiles) {
299
+ const abs = path.join(contentDir, rel);
300
+ const scan = await scanOnce(abs);
301
+ const url = urlOf(rel, scan?.data?.slug);
302
+ pages.set(url, { rel, abs, scan });
303
+ urlOfFile.set(rel, url);
304
+ }
305
+ const generated = generatedPageUrls(contentDir);
306
+ const redirects = new Set(
307
+ (Array.isArray(config.redirects) ? config.redirects : [])
308
+ .map((r) => (typeof r?.source === 'string' ? `/${r.source.replace(/^\/+|\/+$/g, '')}/`.replace(/^\/\/$/, '/') : null))
309
+ .filter(Boolean)
310
+ );
311
+ // Where generated API pages used to be - redirects too (lib/moved-api-pages.js).
312
+ for (const { source } of readMovedApiPages(contentDir)) redirects.add(`${source}/`);
313
+ const specs = readSpecPaths(contentDir);
314
+ const rules = projectIgnore(contentDir);
315
+ const special = new Set(['/llms.txt', '/llms-full.txt', '/404.html', '/404/', '/robots.txt']);
316
+ // With the consent banner on, #cookie-settings opens it from any page.
317
+ const pageWideAnchors = new Set(consentOptions(config.integrations?.consent) ? [CONSENT_SETTINGS_ANCHOR] : []);
318
+ if (config.domain) ['/sitemap.xml', '/sitemap-index.xml'].forEach((p) => special.add(p));
319
+ const knownUrls = [...pages.keys(), ...generated, ...redirects];
320
+ // Folder addresses with no page of their own redirect to one under them
321
+ // (lib/folder-redirects.js), so a link to one isn't broken.
322
+ const folders = new Set(
323
+ [...folderAddresses([...pages.keys(), ...generated].map((url) => url.replace(/^\/+|\/+$/g, '')))].map((folder) => `/${folder}/`)
324
+ );
325
+
326
+ // Anchors a page can be linked to: its own, plus those of every snippet
327
+ // it imports (they render inside it).
328
+ const snippetPath = (spec, fromAbs) =>
329
+ spec.startsWith('/') ? path.join(contentDir, spec) : path.resolve(path.dirname(fromAbs), spec);
330
+ const anchorCache = new Map();
331
+ async function anchorsOf(abs, seen = new Set()) {
332
+ if (anchorCache.has(abs)) return anchorCache.get(abs);
333
+ if (seen.has(abs)) return new Set();
334
+ seen.add(abs);
335
+ const scan = await scanOnce(abs);
336
+ const all = new Set(scan?.anchors ?? []);
337
+ for (const spec of scan?.imports ?? []) for (const a of await anchorsOf(snippetPath(spec, abs), seen)) all.add(a);
338
+ anchorCache.set(abs, all);
339
+ return all;
340
+ }
341
+
342
+ // Root-relative image/font paths something displays - see the "Any other
343
+ // file" case below. Snippets are scanned here too, so the set is complete
344
+ // before the first link is checked.
345
+ const displayedAssets = new Set();
346
+ async function collectDisplayed(abs, seen = new Set()) {
347
+ if (seen.has(abs)) return;
348
+ seen.add(abs);
349
+ const scan = await scanOnce(abs);
350
+ for (const link of scan?.links ?? []) if (link.kind !== 'link' && link.href.startsWith('/')) displayedAssets.add(link.href.split(/[?#]/)[0]);
351
+ for (const spec of scan?.imports ?? []) await collectDisplayed(snippetPath(spec, abs), seen);
352
+ }
353
+ for (const page of pages.values()) await collectDisplayed(page.abs);
354
+ (function walk(node) {
355
+ if (typeof node === 'string') {
356
+ if (node.startsWith('/') && ASSET_EXTENSIONS.has(path.posix.extname(node).toLowerCase())) displayedAssets.add(node);
357
+ } else if (Array.isArray(node)) node.forEach(walk);
358
+ else if (node && typeof node === 'object') Object.values(node).forEach(walk);
359
+ })(config);
360
+
361
+ // --- Checking one link -------------------------------------------------
362
+ const broken = [];
363
+ const reported = new Set();
364
+ let checked = 0;
365
+ let external = 0;
366
+
367
+ /** `pageUrl`: the URL of the page the link renders on (relative links
368
+ * resolve from it). `fileAbs`: the file the link is written in. */
369
+ async function check(href, { file, line, kind, pageUrl, fileAbs }) {
370
+ const value = String(href ?? '').trim();
371
+ if (!value || value === '#' || value.startsWith('{') || value.includes('{{')) return;
372
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith('//')) {
373
+ external += 1;
374
+ return;
375
+ }
376
+ checked += 1;
377
+ const report = (message, suggestion) => {
378
+ const key = `${file}\n${line}\n${value}`;
379
+ if (reported.has(key)) return;
380
+ reported.add(key);
381
+ broken.push({ file, line, message, suggestion });
382
+ };
383
+
384
+ // A Markdown image with a relative path is resolved from the file's own
385
+ // folder at build time (Astro's image pipeline), not from the URL.
386
+ if (kind === 'image' && fileAbs && !value.startsWith('/') && !value.startsWith('#')) {
387
+ const target = path.resolve(path.dirname(fileAbs), decodeURI(value.split(/[?#]/)[0]));
388
+ if (!fs.existsSync(target)) report(`Image ${value} - there's no file at ${path.relative(contentDir, target).split(path.sep).join('/')}.`);
389
+ return;
390
+ }
391
+
392
+ let url;
393
+ try {
394
+ url = new URL(value, BASE + (pageUrl ?? '/'));
395
+ } catch {
396
+ report(`${value} - not a valid link.`);
397
+ return;
398
+ }
399
+ let pathname;
400
+ try {
401
+ pathname = decodeURI(url.pathname);
402
+ } catch {
403
+ pathname = url.pathname;
404
+ }
405
+ const hash = url.hash ? decodeURIComponent(url.hash.slice(1)) : '';
406
+ const extension = path.posix.extname(pathname.replace(/\/+$/, '')).toLowerCase();
407
+ const isRelative = !value.startsWith('/') && !value.startsWith('#');
408
+
409
+ // A page (or /x/index.html).
410
+ let pageKey = null;
411
+ if (!extension || pathname.endsWith('/index.html')) {
412
+ pageKey = pathname.replace(/\/index\.html$/, '/').replace(/\/?$/, '/');
413
+ }
414
+ if (pageKey !== null) {
415
+ if (pages.has(pageKey)) {
416
+ if (!hash || hash === 'top' || pageWideAnchors.has(hash)) return;
417
+ const anchors = await anchorsOf(pages.get(pageKey).abs);
418
+ if (anchors.has(hash)) return;
419
+ const suggestion = closest(hash, [...anchors]);
420
+ const onPage = pageKey === pageUrl && value.startsWith('#') ? 'this page' : pageKey;
421
+ report(
422
+ `${value} - ${onPage} has no heading or anchor "#${hash}".`,
423
+ suggestion ? `Did you mean #${suggestion}?` : undefined
424
+ );
425
+ return;
426
+ }
427
+ // "/" always exists: the home page, or a redirect to the first page.
428
+ if (pageKey === '/' || generated.has(pageKey) || redirects.has(pageKey) || folders.has(pageKey) || special.has(pageKey.replace(/\/$/, '') || '/')) return;
429
+ if (special.has(pathname)) return;
430
+
431
+ // Mintlify-style relative link: resolved from the file's folder
432
+ // instead of the page's URL, would it land on a page?
433
+ if (isRelative && pageUrl && pageUrl !== '/') {
434
+ const siblingBase = pageUrl.replace(/[^/]+\/$/, '');
435
+ const alt = new URL(value, BASE + siblingBase);
436
+ const altKey = decodeURI(alt.pathname).replace(/\/?$/, '/');
437
+ if (pages.has(altKey) || generated.has(altKey)) {
438
+ report(
439
+ `${value} - relative links resolve from the page's own URL (${pageUrl}), so this one points to ${pageKey}, which doesn't exist.`,
440
+ `Write ${altKey}${alt.hash} instead.`
441
+ );
442
+ return;
443
+ }
444
+ }
445
+ const suggestion = closest(pageKey, knownUrls);
446
+ report(`${value} - there's no page at ${pageKey}.`, suggestion ? `Did you mean ${suggestion}?` : undefined);
447
+ return;
448
+ }
449
+
450
+ // A link to a page's source file (docs/setup.mdx) instead of its URL.
451
+ if (extension === '.mdx' || extension === '.md') {
452
+ const bare = pathname.replace(/\.mdx?$/i, '').replace(/\/?$/, '/');
453
+ if (extension === '.md' && contextMenuOptions(config.contextMenu).length && pages.has(bare)) return; // the page's Markdown copy (on unless "contextMenu": false)
454
+ // Written as a file path, so look it up as one: from the file's own
455
+ // folder when relative.
456
+ const filePath = isRelative && fileAbs ? path.resolve(path.dirname(fileAbs), decodeURI(value.split(/[?#]/)[0])) : path.join(contentDir, pathname);
457
+ const rel = path.relative(contentDir, filePath).split(path.sep).join('/');
458
+ const byFile = urlOfFile.get(rel) ?? (pages.has(bare) ? bare : null);
459
+ report(
460
+ `${value} - links to a source file, which isn't published.`,
461
+ byFile ? `Link to the page's URL instead: ${byFile}` : undefined
462
+ );
463
+ return;
464
+ }
465
+
466
+ // Any other file.
467
+ if (special.has(pathname)) return;
468
+ const segments = pathname.replace(/^\/+/, '').split('/');
469
+ // A file the ignore rules leave out (lib/wdignore.js) is never published,
470
+ // in public/ or anywhere else - so a link to it is a broken one.
471
+ const leftOut = (rel) => {
472
+ if (!rules.ignores(rel)) return false;
473
+ report(
474
+ `${value} - ${rel} is in the project, but the ignore rules leave it out, so it isn't published.`,
475
+ rules.isLocked(rel)
476
+ ? "It's a kind of file that is never published (a key, a .env, .git/)."
477
+ : `To publish it, bring it back in .wdignore - a line with !${rel}, or its folder's (!folder/) when the whole folder is left out.`
478
+ );
479
+ return true;
480
+ };
481
+ if (fs.existsSync(path.join(contentDir, 'public', ...segments))) {
482
+ leftOut(['public', ...segments].join('/'));
483
+ return;
484
+ }
485
+ const inProject = path.join(contentDir, ...segments);
486
+ if (fs.existsSync(inProject)) {
487
+ if (leftOut(segments.join('/'))) return;
488
+ // The build publishes the project's files at their own path
489
+ // (lib/project-files.js) - images, PDFs, data files. What it doesn't:
490
+ // the files the site is built from (writedocs.json, an OpenAPI spec),
491
+ // anything in a dot-folder, and kinds of file it doesn't know.
492
+ if (isPublishedFile(segments.join('/'), { specs, rules })) return;
493
+ // An image or font a page displays is copied wherever it is
494
+ // (lib/styles-asset-integration.js).
495
+ if (ASSET_EXTENSIONS.has(extension) && displayedAssets.has(pathname)) return;
496
+ report(
497
+ `${value} - ${pathname} is in the project, but it isn't a file the build publishes.`,
498
+ `To publish it as it is, move it to public${pathname}.`
499
+ );
500
+ return;
501
+ }
502
+ report(`${value} - there's no file at ${pathname}.`);
503
+ }
504
+
505
+ // --- The pages, their snippets, and writedocs.json ---------------------
506
+ const relOf = (abs) => path.relative(contentDir, abs).split(path.sep).join('/');
507
+ const snippetsChecked = new Set();
508
+ async function checkFile(abs, pageUrl, seen) {
509
+ const scan = await scanOnce(abs);
510
+ if (!scan) return;
511
+ const file = relOf(abs);
512
+ for (const link of scan.links) await check(link.href, { file, line: link.line, kind: link.kind, pageUrl, fileAbs: abs });
513
+ for (const spec of scan.imports) {
514
+ const snippet = snippetPath(spec, abs);
515
+ // A snippet the ignore rules leave out (lib/wdignore.js) isn't part of
516
+ // the project a site is built from: where the rules are applied before
517
+ // the build (the WriteDocs platform's sync), the import finds no file.
518
+ const snippetRel = relOf(snippet);
519
+ if (!snippetRel.startsWith('..') && fs.existsSync(snippet) && rules.ignores(snippetRel)) {
520
+ const key = [file, 'import', snippetRel].join('\n');
521
+ if (!reported.has(key)) {
522
+ reported.add(key);
523
+ broken.push({
524
+ file,
525
+ message: `import of ${spec} - ${snippetRel} is in the project, but the ignore rules leave it out, so the build can't count on it.`,
526
+ suggestion: rules.isLocked(snippetRel) ? 'Move the snippet out of that path.' : `Bring it back in .wdignore (!${snippetRel}), or move the snippet.`,
527
+ });
528
+ }
529
+ }
530
+ if (seen.has(snippet) || snippetsChecked.has(`${snippet}\n${pageUrl}`)) continue;
531
+ snippetsChecked.add(`${snippet}\n${pageUrl}`);
532
+ await checkFile(snippet, pageUrl, new Set([...seen, snippet]));
533
+ }
534
+ }
535
+ for (const [url, page] of pages) await checkFile(page.abs, url, new Set([page.abs]));
536
+
537
+ const locate = createJsonLocator(configText);
538
+ for (const { href, path: jsonPath } of configLinks(config)) {
539
+ await check(href, { file: 'writedocs.json', line: locate(jsonPath)?.line, kind: 'link', pageUrl: '/' });
540
+ }
541
+
542
+ broken.sort((a, b) => a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0));
543
+ return { pages: pages.size, links: checked, external, broken };
544
+ }