docs/.vitepress/plugins/urlSearchPlugin.ts
180 lines · 5157 bytes
1import { writeFileSync } from 'node:fs'
2import { join } from 'node:path'
3import { renderEmojiShortcodes } from '../configs/markdown/emoji'
4
5export interface PageLink {
6 href: string
7 linkText: string
8 pageId: string
9 anchor: string
10 titles: string[]
11}
12
13function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
14 const results: PageLink[] = []
15 const seen = new Set<string>()
16 const headingStack: string[] = []
17 const slugCounts = new Map<string, number>()
18 const collapsibleStack: {
19 anchor: string
20 headings: string[]
21 }[] = []
22 let currentAnchor = ''
23
24 // Strip frontmatter
25 const body = src.startsWith('---')
26 ? src.replace(/^---[\s\S]*?---\n?/, '')
27 : src
28 const lines = body.split('\n')
29
30 const slugify = (value: string) =>
31 value
32 .replace(/\{[^}]*\}\s*$/, '')
33 .replace(/<[^>]*>/g, '')
34 .replace(/`([^`]+)`/g, '$1')
35 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
36 .replace(/[*_~]/g, '')
37 .trim()
38 .toLowerCase()
39 .replace(/[^\w\s-]/g, '')
40 .replace(/\s+/g, '-')
41 .replace(/-+/g, '-')
42 .replace(/^-|-$/g, '')
43
44 const getAnchor = (text: string) => {
45 const slug = slugify(text)
46 const count = slugCounts.get(slug) ?? 0
47 slugCounts.set(slug, count + 1)
48 return count === 0 ? slug : `${slug}-${count}`
49 }
50
51 const setHeading = (level: number, text: string) => {
52 headingStack[level] = text
53 headingStack.length = level + 1
54 currentAnchor = getAnchor(text)
55 }
56
57 for (let i = 0; i < lines.length; i++) {
58 const line = lines[i]
59
60 const collapsibleMatch = line.match(
61 /^\s*<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\1)[^>]*>\s*$/i
62 )
63 if (collapsibleMatch) {
64 collapsibleStack.push({
65 anchor: currentAnchor,
66 headings: [...headingStack]
67 })
68
69 let nextLine = i + 1
70 while (nextLine < lines.length && lines[nextLine].trim() === '') {
71 nextLine++
72 }
73
74 // The markdown renderer injects a searchable H3 for collapsibles that
75 // don't already start with a heading. Mirror that anchor so URL search
76 // can deep-link into and auto-open those collapsibles.
77 if (!/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) {
78 setHeading(2, collapsibleMatch[2].trim())
79 }
80 continue
81 }
82
83 if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
84 const previous = collapsibleStack.pop()
85 if (previous) {
86 currentAnchor = previous.anchor
87 headingStack.length = 0
88 headingStack.push(...previous.headings)
89 }
90 continue
91 }
92
93 // Heading: ## Title or === Title (setext-style ignored, ATX only)
94 const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
95 if (headingMatch) {
96 const level = headingMatch[1].length - 1
97 const text = headingMatch[2].trim()
98 setHeading(level, text)
99 continue
100 }
101
102 // Markdown links: [text](https://...)
103 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
104 let m: RegExpExecArray | null
105 while ((m = linkRE.exec(line)) !== null) {
106 const linkText = renderEmojiShortcodes(m[1].trim())
107 const href = m[2].trim()
108 const key = href + '\x00' + currentAnchor
109 if (seen.has(key)) continue
110 seen.add(key)
111 results.push({
112 href,
113 linkText,
114 pageId,
115 anchor: currentAnchor,
116 titles: headingStack.filter(Boolean)
117 })
118 }
119
120 // Bare angle-bracket URLs: <https://...>
121 const bareRE = /<(https?:\/\/[^>]+)>/g
122 while ((m = bareRE.exec(line)) !== null) {
123 const href = m[1].trim()
124 const key = href + '\x00' + currentAnchor
125 if (seen.has(key)) continue
126 seen.add(key)
127 results.push({
128 href,
129 linkText: href,
130 pageId,
131 anchor: currentAnchor,
132 titles: headingStack.filter(Boolean)
133 })
134 }
135 }
136
137 return results
138}
139
140const collected: PageLink[] = []
141
142export function collectPageLinks(src: string, page: string) {
143 const pageId = '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
144 collected.push(...extractLinksFromMarkdown(src, pageId))
145}
146
147export function writeUrlSearchIndex(outDir: string) {
148 const seen = new Set<string>()
149 const deduped = collected.filter((l) => {
150 const key = l.href + '\x00' + l.pageId + '\x00' + l.anchor
151 if (seen.has(key)) return false
152 seen.add(key)
153 return true
154 })
155 const outPath = join(outDir, 'url-search-index.json')
156 writeFileSync(outPath, JSON.stringify(deduped), 'utf-8')
157 console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`)
158}
159
160export function urlSearchDevPlugin() {
161 return {
162 name: 'url-search-dev',
163 configureServer(server: any) {
164 server.middlewares.use(
165 '/url-search-index.json',
166 (_req: any, res: any) => {
167 const seen = new Set<string>()
168 const deduped = collected.filter((l) => {
169 const key = l.href + '\x00' + l.pageId + '\x00' + l.anchor
170 if (seen.has(key)) return false
171 seen.add(key)
172 return true
173 })
174 res.setHeader('Content-Type', 'application/json')
175 res.end(JSON.stringify(deduped))
176 }
177 )
178 }
179 }
180}