docs/.vitepress/plugins/urlSearchPlugin.ts
219 lines · 6211 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 containerStack: string[] = []
19 const collapsibleStack: {
20 anchor: string
21 headings: string[]
22 }[] = []
23 let currentAnchor = ''
24
25 // Strip frontmatter
26 const body = src.startsWith('---')
27 ? src.replace(/^---[\s\S]*?---\n?/, '')
28 : src
29 const lines = body.split('\n')
30
31 const rControl = /[\u0000-\u001f]/g
32 const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g
33 const rCombining = /[\u0300-\u036F]/g
34
35 const stripHeadingMarkup = (value: string) =>
36 value
37 .replace(/\{[^}]*\}\s*$/, '')
38 .replace(/<[^>]*>/g, '')
39 .replace(/`([^`]+)`/g, '$1')
40 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
41 .replace(/[*_~]/g, '')
42 .trim()
43
44 const slugify = (value: string) =>
45 stripHeadingMarkup(value)
46 .normalize('NFKD')
47 .replace(rCombining, '')
48 .replace(rControl, '')
49 .replace(rSpecial, '-')
50 .replace(/-{2,}/g, '-')
51 .replace(/^-+|-+$/g, '')
52 .replace(/^(\d)/, '_$1')
53 .toLowerCase()
54
55 const getAnchor = (text: string) => {
56 const slug = slugify(text)
57 const count = slugCounts.get(slug) ?? 0
58 slugCounts.set(slug, count + 1)
59 return count === 0 ? slug : `${slug}-${count}`
60 }
61
62 const setHeading = (level: number, text: string) => {
63 headingStack[level] = text
64 headingStack.length = level + 1
65 currentAnchor = getAnchor(text)
66 }
67
68 const getTitles = () => headingStack.filter(Boolean)
69
70 for (let i = 0; i < lines.length; i++) {
71 const line = lines[i]
72
73 const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/)
74 if (containerOpenMatch) {
75 containerStack.push(containerOpenMatch[1].toLowerCase())
76 } else if (/^\s*:{3,}\s*$/.test(line)) {
77 containerStack.pop()
78 }
79
80 const tabMatch = line.match(/^\s*==\s+(.+)$/)
81 if (tabMatch && containerStack.includes('tabs')) {
82 const title = tabMatch[1].trim()
83 if (title) {
84 // The markdown renderer injects a hidden H3 for each tab label.
85 // Mirror that heading so URL search deep-links to the selected tab.
86 setHeading(2, title)
87 }
88 continue
89 }
90
91 const collapsibleMatch = line.match(
92 /^\s*<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\1)[^>]*>\s*$/i
93 )
94 if (collapsibleMatch) {
95 collapsibleStack.push({
96 anchor: currentAnchor,
97 headings: [...headingStack]
98 })
99
100 let nextLine = i + 1
101 while (nextLine < lines.length && lines[nextLine].trim() === '') {
102 nextLine++
103 }
104
105 // The markdown renderer injects a searchable H3 for collapsibles that
106 // don't already start with a heading. Mirror that anchor so URL search
107 // can deep-link into and auto-open those collapsibles.
108 if (!/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) {
109 setHeading(2, collapsibleMatch[2].trim())
110 }
111 continue
112 }
113
114 if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
115 const previous = collapsibleStack.pop()
116 if (previous) {
117 currentAnchor = previous.anchor
118 headingStack.length = 0
119 headingStack.push(...previous.headings)
120 }
121 continue
122 }
123
124 // Heading: ## Title or === Title (setext-style ignored, ATX only)
125 const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
126 if (headingMatch) {
127 const level = headingMatch[1].length - 1
128 const text = headingMatch[2].trim()
129 setHeading(level, text)
130 continue
131 }
132
133 // Markdown links: [text](https://...)
134 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
135 let m: RegExpExecArray | null
136 while ((m = linkRE.exec(line)) !== null) {
137 const linkText = renderEmojiShortcodes(m[1].trim())
138 const href = m[2].trim()
139 const key = href + '\x00' + currentAnchor
140 if (seen.has(key)) continue
141 seen.add(key)
142 results.push({
143 href,
144 linkText,
145 pageId,
146 anchor: currentAnchor,
147 titles: getTitles()
148 })
149 }
150
151 // Bare angle-bracket URLs: <https://...>
152 const bareRE = /<(https?:\/\/[^>]+)>/g
153 while ((m = bareRE.exec(line)) !== null) {
154 const href = m[1].trim()
155 const key = href + '\x00' + currentAnchor
156 if (seen.has(key)) continue
157 seen.add(key)
158 results.push({
159 href,
160 linkText: href,
161 pageId,
162 anchor: currentAnchor,
163 titles: getTitles()
164 })
165 }
166 }
167
168 return results
169}
170
171const collectedByPage = new Map<string, PageLink[]>()
172
173function getPageId(page: string) {
174 return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
175}
176
177function getDedupedLinks() {
178 const seen = new Set<string>()
179 const deduped: PageLink[] = []
180
181 for (const links of collectedByPage.values()) {
182 for (const link of links) {
183 const key = link.href + '\x00' + link.pageId + '\x00' + link.anchor
184 if (seen.has(key)) continue
185 seen.add(key)
186 deduped.push(link)
187 }
188 }
189
190 return deduped
191}
192
193export function collectPageLinks(src: string, page: string) {
194 const pageId = getPageId(page)
195 collectedByPage.set(pageId, extractLinksFromMarkdown(src, pageId))
196}
197
198export function writeUrlSearchIndex(outDir: string) {
199 const deduped = getDedupedLinks()
200 const outPath = join(outDir, 'url-search-index.json')
201 writeFileSync(outPath, JSON.stringify(deduped), 'utf-8')
202 console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`)
203}
204
205export function urlSearchDevPlugin() {
206 return {
207 name: 'url-search-dev',
208 configureServer(server: any) {
209 server.middlewares.use(
210 '/url-search-index.json',
211 (_req: any, res: any) => {
212 const deduped = getDedupedLinks()
213 res.setHeader('Content-Type', 'application/json')
214 res.end(JSON.stringify(deduped))
215 }
216 )
217 }
218 }
219}