docs/.vitepress/plugins/urlSearchPlugin.ts

main
wotaku/docs/.vitepress/plugins/urlSearchPlugin.ts history · blame · raw

571 lines · 16089 bytes

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