docs/.vitepress/plugins/urlSearchPlugin.ts
537 lines · 15119 bytes
1import matter from 'gray-matter'
2import { existsSync, readFileSync, writeFileSync } from 'node:fs'
3import { join } from 'node:path'
4import { renderEmojiShortcodes } from '../configs/markdown/emoji'
5import {
6 getCollapsibleHeadingAnchor,
7 getTabAnchor,
8 getTabHeadingAnchor,
9 getUniqueAnchor,
10 parseTabLabel,
11 slugifyAnchor,
12 stripHeadingMarkup
13} from '../utils/tabAnchors'
14
15export interface PageLink {
16 href: string
17 linkText: string
18 pageId: string
19 anchor: string
20 titles: string[]
21 tabs?: string[]
22 tables?: string[]
23 mirror?: string
24}
25
26export interface TabTarget {
27 pageId: string
28 anchor: string
29 tabs: string[]
30}
31
32interface PageSearchMetadata {
33 links: PageLink[]
34 tabTargets: TabTarget[]
35}
36
37interface TableMoreBlock {
38 anchor: string
39 startLine: number
40 endLine: number
41}
42
43const isPipeLine = (line: string) => line.trim().startsWith('|')
44
45function splitTableCells(line: string): string[] {
46 let s = line.trim()
47 if (s.startsWith('|')) s = s.slice(1)
48 if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1)
49 return s.split(/(?<!\\)\|/)
50}
51
52function isDelimiterRow(line: string): boolean {
53 const cells = splitTableCells(line)
54 return cells.length > 0 &&
55 cells.every((cell) => /^:?-+:?$/.test(cell.trim()))
56}
57
58const isMoreMarker = (line: string) => /^<more\s*\/?>$/i.test(line.trim())
59
60// Find `data-table-more` anchors in document order (mirrors tableMorePlugin).
61function findTableMoreBlocks(lines: string[]): TableMoreBlock[] {
62 const blocks: TableMoreBlock[] = []
63 const n = lines.length
64 let count = 0
65 let i = 0
66
67 while (i < n) {
68 if (!isMoreMarker(lines[i])) {
69 i++
70 continue
71 }
72 // Marker must directly follow a table run.
73 let t = i - 1
74 while (t >= 0 && lines[t].trim() === '') t--
75 if (t < 0 || !isPipeLine(lines[t])) {
76 i++
77 continue
78 }
79 let runStart = t
80 while (runStart - 1 >= 0 && isPipeLine(lines[runStart - 1])) runStart--
81 let hasDelimiter = false
82 for (let k = runStart; k <= t; k++) {
83 if (isDelimiterRow(lines[k])) {
84 hasDelimiter = true
85 break
86 }
87 }
88 if (!hasDelimiter) {
89 i++
90 continue
91 }
92 // Hidden rows: bare pipe lines or a full table.
93 let h = i + 1
94 while (h < n && lines[h].trim() === '') h++
95 let hiddenEnd = -1
96 if (h < n && isPipeLine(lines[h])) {
97 if (
98 h + 1 < n && isPipeLine(lines[h + 1]) && isDelimiterRow(lines[h + 1])
99 ) {
100 // Full second table needs a body row.
101 if (h + 2 < n && isPipeLine(lines[h + 2])) {
102 let e = h + 2
103 while (e + 1 < n && isPipeLine(lines[e + 1])) e++
104 hiddenEnd = e
105 }
106 } else {
107 let e = h
108 while (e + 1 < n && isPipeLine(lines[e + 1])) e++
109 hiddenEnd = e
110 }
111 }
112 if (hiddenEnd === -1) {
113 i++
114 continue
115 }
116 blocks.push({ anchor: String(count++), startLine: runStart, endLine: hiddenEnd })
117 i = hiddenEnd + 1
118 }
119
120 return blocks
121}
122
123function extractSearchMetadataFromMarkdown(
124 src: string,
125 pageId: string
126): PageSearchMetadata {
127 const links: PageLink[] = []
128 const seenLinks = new Map<string, PageLink>()
129 const tabTargets = new Map<string, TabTarget>()
130 const headingStack: string[] = []
131 const slugCounts = new Map<string, number>()
132 const tabAnchorCounts = new Map<string, number>()
133 const collapsibleAnchorCounts = new Map<string, number>()
134 const containerStack: string[] = []
135 const tabPath: string[] = []
136 const tabResetStack: {
137 anchor: string
138 headings: string[]
139 }[] = []
140 const collapsibleStack: {
141 anchor: string
142 headings: string[]
143 }[] = []
144 let currentAnchor = ''
145 let extrepoEntryName: string | null = null
146
147 const mirrorCache = new Map<
148 string,
149 { src: string; mirrors: string[]; title: string } | null
150 >()
151
152 const getMirrorUrls = (id: string) => {
153 if (mirrorCache.has(id)) return mirrorCache.get(id)
154 // Direct URL form needs no mirror file.
155 if (/^https?:\/\/\S+$/i.test(id)) {
156 let title = id
157 try {
158 title = new URL(id).hostname.replace(/^www\./i, '')
159 } catch {
160 /* keep raw */
161 }
162 const entry = { src: id, mirrors: [] as string[], title }
163 mirrorCache.set(id, entry)
164 return entry
165 }
166 try {
167 const filePath = join(
168 process.cwd(),
169 'docs/.vitepress/mirrors',
170 `${id}.md`
171 )
172 if (!existsSync(filePath)) {
173 mirrorCache.set(id, null)
174 return null
175 }
176 const fileContent = readFileSync(filePath, 'utf-8')
177 const { data, content } = matter(fileContent)
178 const src = typeof data.src === 'string' ? data.src.trim() : ''
179 const title = typeof data.title === 'string' && data.title.trim()
180 ? data.title.trim()
181 : id
182 const urls: string[] = []
183 const seen = new Set<string>()
184 for (const m of content.matchAll(/https?:\/\/[^\s<>"')\]]+/g)) {
185 const url = m[0].replace(/[.,;:!?]+$/, '')
186 if (!seen.has(url) && url !== src) {
187 seen.add(url)
188 urls.push(url)
189 }
190 }
191 const entry = { src, mirrors: urls, title }
192 mirrorCache.set(id, entry)
193 return entry
194 } catch {
195 mirrorCache.set(id, null)
196 return null
197 }
198 }
199
200 const getMirrorMainLabel = (line: string, fallback: string) => {
201 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
202 let m: RegExpExecArray | null
203 while ((m = linkRE.exec(line)) !== null) {
204 const label = m[1].trim()
205 if (!label || /^:.*:$/.test(label)) continue
206 return renderEmojiShortcodes(label)
207 }
208 return fallback
209 }
210
211 const body = src.startsWith('---')
212 ? src.replace(/^---[\s\S]*?---\n?/, '')
213 : src
214 const lines = body.split('\n')
215
216 const getAnchor = (text: string) => {
217 const slug = slugifyAnchor(text)
218 const count = slugCounts.get(slug) ?? 0
219 slugCounts.set(slug, count + 1)
220 return count === 0 ? slug : `${slug}-${count}`
221 }
222
223 const getCurrentTabPath = () => tabPath.filter(Boolean)
224
225 const recordTabTarget = (anchor: string) => {
226 const tabs = getCurrentTabPath()
227 if (!anchor || !tabs.length) return
228 tabTargets.set(anchor, { pageId, anchor, tabs })
229 }
230
231 const setHeading = (level: number, text: string, anchor?: string) => {
232 const title = stripHeadingMarkup(text)
233 if (!title) return
234
235 headingStack[level] = title
236 headingStack.length = level + 1
237 currentAnchor = anchor || getAnchor(title)
238 recordTabTarget(currentAnchor)
239 }
240
241 const getTitles = () => headingStack.filter(Boolean)
242
243 const restoreHeadingState = (state: {
244 anchor: string
245 headings: string[]
246 }) => {
247 currentAnchor = state.anchor
248 headingStack.length = 0
249 headingStack.push(...state.headings)
250 }
251
252 const getTabsDepth = () =>
253 containerStack.filter((name) => name === 'tabs').length
254
255 // Anchors must match the renderer `data-table-more` counter.
256 const tableMoreBlocks = findTableMoreBlocks(lines)
257
258 const tablesForLine = (idx: number): string[] => {
259 const out: string[] = []
260 for (const block of tableMoreBlocks) {
261 if (idx >= block.startLine && idx <= block.endLine) out.push(block.anchor)
262 }
263 return out
264 }
265
266 const pushLink = (
267 href: string,
268 linkText: string,
269 lineIdx: number,
270 extra?: { mirror?: string }
271 ) => {
272 const tabs = getCurrentTabPath()
273 const tables = tablesForLine(lineIdx)
274 const key = [
275 href,
276 currentAnchor,
277 tabs.join('/')
278 ].join('\x00')
279 const existing = seenLinks.get(key)
280 if (existing) {
281 if (tables.length) {
282 const merged = [...existing.tables ?? []]
283 for (const anchor of tables) {
284 if (!merged.includes(anchor)) merged.push(anchor)
285 }
286 existing.tables = merged
287 }
288 if (extra?.mirror && !existing.mirror) existing.mirror = extra.mirror
289 return
290 }
291
292 const link: PageLink = {
293 href,
294 linkText,
295 pageId,
296 anchor: currentAnchor,
297 titles: getTitles(),
298 ...(tabs.length ? { tabs } : {}),
299 ...(tables.length ? { tables } : {}),
300 ...(extra?.mirror ? { mirror: extra.mirror } : {})
301 }
302 seenLinks.set(key, link)
303 links.push(link)
304 }
305
306 for (let i = 0; i < lines.length; i++) {
307 const line = lines[i]
308
309 const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/)
310 if (containerOpenMatch) {
311 const containerName = containerOpenMatch[1].toLowerCase()
312 containerStack.push(containerName)
313 if (containerName === 'tabs') {
314 tabResetStack.push({
315 anchor: currentAnchor,
316 headings: [...headingStack]
317 })
318 }
319 } else if (/^\s*:{3,}\s*$/.test(line)) {
320 const closed = containerStack.pop()
321 if (closed === 'tabs') {
322 tabPath.length = getTabsDepth()
323 const resetState = tabResetStack.pop()
324 if (resetState) restoreHeadingState(resetState)
325 } else if (closed === 'extrepo') {
326 extrepoEntryName = null
327 }
328 }
329
330 if (
331 containerStack.includes('extrepo') && !containerStack.includes('tabs')
332 ) {
333 const extrepoHeadingMatch = line.match(/^\s*==\s+(.+)$/)
334 if (extrepoHeadingMatch) {
335 extrepoEntryName = extrepoHeadingMatch[1].trim()
336 continue
337 }
338
339 if (extrepoEntryName) {
340 const fieldMatch = line.match(
341 /^\s*-\s*(?:url|raw|src|manga|anime|novel)\s*:\s*(\S+)/
342 )
343 if (fieldMatch) {
344 pushLink(fieldMatch[1].trim(), extrepoEntryName, i)
345 continue
346 }
347 }
348 }
349
350 const tabMatch = line.match(/^\s*==\s+(.+)$/)
351 if (tabMatch && containerStack.includes('tabs')) {
352 const rawTitle = tabMatch[1]
353 const parsed = parseTabLabel(rawTitle)
354 if (parsed.label) {
355 const depth = getTabsDepth()
356 const anchor = getTabAnchor(rawTitle, tabAnchorCounts)
357 const headingAnchor = getTabHeadingAnchor(anchor)
358 tabPath[depth - 1] = anchor
359 tabPath.length = depth
360
361 // Mirror injected tab headings for deep-linking.
362 setHeading(2, parsed.label, headingAnchor)
363 }
364 continue
365 }
366
367 const collapsibleMatch = line.match(
368 /^\s*<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\1)[^>]*>\s*$/i
369 )
370 if (collapsibleMatch) {
371 collapsibleStack.push({
372 anchor: currentAnchor,
373 headings: [...headingStack]
374 })
375
376 const parsed = parseTabLabel(collapsibleMatch[2])
377 const collapsibleAnchor = parsed.anchor ||
378 getUniqueAnchor(parsed.label, collapsibleAnchorCounts)
379
380 let nextLine = i + 1
381 while (nextLine < lines.length && lines[nextLine].trim() === '') {
382 nextLine++
383 }
384
385 // Mirror injected collapsible headings for deep-linking.
386 if (!/^#{1,6}\s+/.test(lines[nextLine]?.trim() ?? '')) {
387 setHeading(
388 containerStack.includes('tabs') ? 3 : 2,
389 parsed.label,
390 getCollapsibleHeadingAnchor(collapsibleAnchor)
391 )
392 }
393 continue
394 }
395
396 if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
397 const previous = collapsibleStack.pop()
398 if (previous) restoreHeadingState(previous)
399 continue
400 }
401
402 const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
403 if (headingMatch) {
404 const level = headingMatch[1].length - 1
405 setHeading(level, headingMatch[2].trim())
406 continue
407 }
408
409 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
410 let m: RegExpExecArray | null
411 while ((m = linkRE.exec(line)) !== null) {
412 pushLink(m[2].trim(), renderEmojiShortcodes(m[1].trim()), i)
413 }
414
415 const bareRE = /<(https?:\/\/[^>]+)>/g
416 while ((m = bareRE.exec(line)) !== null) {
417 const href = m[1].trim()
418 pushLink(href, href, i)
419 }
420
421 const mirrorRE = /==m:(.+?)==/g
422 let pm: RegExpExecArray | null
423 while ((pm = mirrorRE.exec(line)) !== null) {
424 const id = pm[1].trim()
425 if (!id) continue
426 const mirror = getMirrorUrls(id)
427 if (!mirror) continue
428 const label = getMirrorMainLabel(line, mirror.title)
429 const srcNorm = mirror.src.trim()
430 for (const href of [mirror.src, ...mirror.mirrors]) {
431 if (!href) continue
432 const h = href.trim()
433 // File src is the normal link; only mirrors get flagged.
434 const isMainSrc = mirror.mirrors.length > 0 && h === srcNorm
435 pushLink(h, label, i, isMainSrc ? undefined : { mirror: id })
436 }
437 }
438 }
439
440 return { links, tabTargets: [...tabTargets.values()] }
441}
442
443const collectedByPage = new Map<string, PageSearchMetadata>()
444
445function getPageId(page: string) {
446 return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
447}
448
449function getDedupedLinks() {
450 const seen = new Map<string, number>()
451 const deduped: PageLink[] = []
452
453 for (const metadata of collectedByPage.values()) {
454 for (const link of metadata.links) {
455 const key = [
456 link.href,
457 link.pageId,
458 link.anchor,
459 link.tabs?.join('/') ?? '',
460 link.tables?.join('/') ?? ''
461 ].join('\x00')
462 const idx = seen.get(key)
463 if (idx !== undefined) {
464 // Keep the mirror-tagged entry so the indicator survives.
465 if (link.mirror && !deduped[idx].mirror) deduped[idx] = link
466 continue
467 }
468 seen.set(key, deduped.length)
469 deduped.push(link)
470 }
471 }
472
473 return deduped
474}
475
476function getDedupedTabTargets() {
477 const seen = new Set<string>()
478 const deduped: TabTarget[] = []
479
480 for (const metadata of collectedByPage.values()) {
481 for (const target of metadata.tabTargets) {
482 const key = [
483 target.pageId,
484 target.anchor,
485 target.tabs.join('/')
486 ].join('\x00')
487 if (seen.has(key)) continue
488 seen.add(key)
489 deduped.push(target)
490 }
491 }
492
493 return deduped
494}
495
496export function collectPageLinks(src: string, page: string) {
497 const pageId = getPageId(page)
498 collectedByPage.set(pageId, extractSearchMetadataFromMarkdown(src, pageId))
499}
500
501export function writeUrlSearchIndex(outDir: string) {
502 const links = getDedupedLinks()
503 const linksPath = join(outDir, 'url-search-index.json')
504 writeFileSync(linksPath, JSON.stringify(links), 'utf-8')
505 console.log(`[url-search] wrote ${links.length} links -> ${linksPath}`)
506
507 const tabTargets = getDedupedTabTargets()
508 const tabTargetsPath = join(outDir, 'tab-search-index.json')
509 writeFileSync(tabTargetsPath, JSON.stringify(tabTargets), 'utf-8')
510 console.log(
511 `[url-search] wrote ${tabTargets.length} tab targets -> ${tabTargetsPath}`
512 )
513}
514
515export function urlSearchDevPlugin() {
516 return {
517 name: 'url-search-dev',
518 configureServer(server: any) {
519 server.middlewares.use(
520 '/url-search-index.json',
521 (_req: any, res: any) => {
522 const deduped = getDedupedLinks()
523 res.setHeader('Content-Type', 'application/json')
524 res.end(JSON.stringify(deduped))
525 }
526 )
527 server.middlewares.use(
528 '/tab-search-index.json',
529 (_req: any, res: any) => {
530 const deduped = getDedupedTabTargets()
531 res.setHeader('Content-Type', 'application/json')
532 res.end(JSON.stringify(deduped))
533 }
534 )
535 }
536 }
537}