-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathhashed-self-reference.mjs
More file actions
48 lines (37 loc) · 1.15 KB
/
hashed-self-reference.mjs
File metadata and controls
48 lines (37 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { lintRule } from 'unified-lint-rule';
const getLinksRecursively = function* (node) {
if (node.url) {
yield node;
}
const { children = [] } = node;
for (const child of children) {
yield* getLinksRecursively(child);
}
};
/**
* Ensures that all self-references begin with `#`
* @type {import('unified-lint-rule').Rule}
*/
const hashedSelfReference = (tree, vfile) => {
const currentFileURL = pathToFileURL(
path.isAbsolute(vfile.path) ? vfile.path : path.join(vfile.cwd, vfile.path)
);
for (const node of getLinksRecursively(tree)) {
const { url } = node;
if (!url || url[0] === '#') {
continue;
}
const targetURL = new URL(url, currentFileURL);
if (targetURL.pathname === currentFileURL.pathname) {
const expected = url.includes('#') ? url.slice(url.indexOf('#')) : '#';
node.url = expected;
vfile.message(
`Self-reference must start with hash (expected "${expected}", got "${url}")`,
node
);
}
}
};
export default lintRule('node-core:hashed-self-reference', hashedSelfReference);