@writedocs/generator 0.10.14 → 0.10.15

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