summaryrefslogtreecommitdiff
path: root/scripts/lint.mts
blob: 9a9e6df09a610e4d05799a0c450cc3a2f346f945 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import fs from 'node:fs/promises';
import path from 'node:path';
import fg from 'fast-glob';
import { getTableOfContents } from 'fumadocs-core/server';
import { createGetUrl, getSlugs, parseFilePath } from 'fumadocs-core/source';
import { remarkInclude } from 'fumadocs-mdx/config';
import matter from 'gray-matter';
import { printErrors, scanURLs, validateFiles } from 'next-validate-link';
import remarkMdx from 'remark-mdx';

async function readFromPath(file: string) {
  const content = await fs
    .readFile(path.resolve(file))
    .then((res) => res.toString());
  const parsed = matter(content);

  return {
    path: file,
    data: parsed.data,
    content: parsed.content,
  };
}

async function checkLinks() {
  const blogFiles = await Promise.all(
    await fg('content/**/*.mdx').then((files) => files.map(readFromPath)),
  );

  const blogs = blogFiles.map(async (file) => {
    const info = parseFilePath(path.relative('content', file.path));

    return {
      value: getSlugs(info)[0],
      hashes: (
        await getTableOfContents(
          {
            path: file.path,
            value: file.content,
          },
          [remarkMdx, remarkInclude],
        )
      ).map((item) => item.url.slice(1)),
    };
  });

  const scanned = await scanURLs({
    populate: {
      '(home)/posts/[slug]': await Promise.all(blogs),
    },
  });

  console.log(
    `collected ${scanned.urls.size} URLs, ${scanned.fallbackUrls.length} fallbacks`,
  );

  const getUrl = createGetUrl('/posts');
  printErrors(
    await validateFiles([...blogFiles], {
      scanned,

      pathToUrl(value) {
        const info = parseFilePath(path.relative('content', value));
        return getUrl(getSlugs(info));
      },
    }),
    true,
  );
}

void checkLinks();