Raw
1 import { readFileSync } from "fs"
2
3 const REGEX = /export const metadata = {[\s\S]*title: `(?<title>.*)`/
4
5 export function findMetadataTitle(content: string): string | undefined {
6 const headingMatch = REGEX.exec(content)
7
8 return headingMatch?.groups?.title
9 }
10
11 export function findPageHeading(content: string): string | undefined {
12 const headingMatch = /# (?<title>.*)/.exec(content)
13
14 return headingMatch?.groups?.title
15 }
16
17 export function findAllPageHeadings({
18 content,
19 level = 1,
20 }: {
21 content: string
22 level?: number
23 }): string[] {
24 const regex = new RegExp(
25 `^${"#".repeat(level)}(?!#) (?<title>.*?)(?:\n|$)`,
26 "gm"
27 )
28 const matches = [...content.matchAll(regex)]
29 return matches.map((match) => match.groups?.title).filter(Boolean) as string[]
30 }
31
32 export function findPageTitle(filePath: string): string | undefined {
33 const content = readFileSync(filePath, "utf-8")
34
35 return findMetadataTitle(content) || findPageHeading(content)
36 }