docs/ext/extensionRepos/shared.ts

178 lines · 5497 bytes

15 symbols in this file
  1import {
  2  existsSync,
  3  mkdirSync,
  4  readdirSync,
  5  readFileSync,
  6  renameSync,
  7  statSync,
  8  writeFileSync
  9} from 'node:fs'
 10import { dirname, join } from 'node:path'
 11import { fileURLToPath } from 'node:url'
 12import { parseExtRepoAttrs } from './attrs'
 13import { assembleSchemeData, type ExtensionRepoData } from './parsers'
 14
 15export type { ExtensionRepoData } from './parsers'
 16
 17const IGNORED_DIRS = new Set(['node_modules', '.vitepress', '.git'])
 18const FETCH_TIMEOUT_MS = 15000
 19const CACHE_TTL_MS = 6 * 60 * 60 * 1000
 20
 21const EXT_DIR = dirname(fileURLToPath(import.meta.url))
 22const DOCS_DIR = join(EXT_DIR, '..', '..')
 23const CACHE_DIR = join(EXT_DIR, '..', '..', '.vitepress/cache/extension-repos')
 24let cacheDirReady = false
 25
 26function findMarkdownFiles(dir: string): string[] {
 27  const files: string[] = []
 28  for (const entry of readdirSync(dir, { withFileTypes: true })) {
 29    if (entry.isDirectory()) {
 30      if (!IGNORED_DIRS.has(entry.name)) {
 31        files.push(...findMarkdownFiles(join(dir, entry.name)))
 32      }
 33    } else if (entry.name.endsWith('.md')) {
 34      files.push(join(dir, entry.name))
 35    }
 36  }
 37  return files
 38}
 39
 40// Single scan of all md files, collecting urls for one scheme only.
 41function collectScheme(
 42  scheme: string
 43): { indexUrls: string[]; listUrls: string[] } {
 44  const indexUrls = new Set<string>()
 45  const listUrls = new Set<string>()
 46  const blockRe = /:::\s*extrepo([^\n]*)\n([\s\S]*?)\n\s*:::/g
 47  const rowRe =
 48    /^\s*-\s*(raw|manga|anime|novel|data)\s*:\s*(https?:\/\/\S+)\s*$/i
 49  const headingRe = /^\s*==\s+.+$/
 50  const buildRe = /^\s*--\s+.+$/
 51
 52  function flushEntry(
 53    plainRaws: string[],
 54    variantUrls: string[],
 55    buildRaws: string[],
 56    dataUrls: string[]
 57  ): void {
 58    for (const url of variantUrls) indexUrls.add(url)
 59    for (const url of buildRaws) indexUrls.add(url)
 60    for (const url of dataUrls) indexUrls.add(url)
 61    if (dataUrls.length === 0) {
 62      for (const url of plainRaws) indexUrls.add(url)
 63    }
 64  }
 65
 66  for (const file of findMarkdownFiles(DOCS_DIR)) {
 67    const src = readFileSync(file, 'utf-8')
 68    let block: RegExpExecArray | null
 69    blockRe.lastIndex = 0
 70    while ((block = blockRe.exec(src))) {
 71      const headerAttrs = parseBlockAttrs(block[1])
 72      if ((headerAttrs.scheme || 'mihon') !== scheme) continue
 73      if (headerAttrs.from) listUrls.add(headerAttrs.from)
 74      let plainRaws: string[] = []
 75      let variantUrls: string[] = []
 76      let buildRaws: string[] = []
 77      let dataUrls: string[] = []
 78      let inEntry = false
 79      let inBuild = false
 80      for (const line of block[2].split('\n')) {
 81        if (headingRe.test(line)) {
 82          if (inEntry) flushEntry(plainRaws, variantUrls, buildRaws, dataUrls)
 83          plainRaws = []
 84          variantUrls = []
 85          buildRaws = []
 86          dataUrls = []
 87          inEntry = true
 88          inBuild = false
 89          continue
 90        }
 91        if (buildRe.test(line)) {
 92          inBuild = true
 93          continue
 94        }
 95        const row = rowRe.exec(line)
 96        if (row && inEntry) {
 97          const key = row[1].toLowerCase()
 98          const url = row[2].trim()
 99          if (key === 'data') dataUrls.push(url)
100          else if (key === 'raw') (inBuild ? buildRaws : plainRaws).push(url)
101          else variantUrls.push(url)
102        }
103      }
104      if (inEntry) flushEntry(plainRaws, variantUrls, buildRaws, dataUrls)
105    }
106  }
107  return { indexUrls: [...indexUrls], listUrls: [...listUrls] }
108}
109
110function parseBlockAttrs(header: string): { scheme?: string; from?: string } {
111  const attrs = parseExtRepoAttrs(header)
112  return { scheme: attrs.scheme, from: attrs.from }
113}
114
115function cachePathFor(url: string): string {
116  return join(CACHE_DIR, `${Buffer.from(url).toString('base64url')}.json`)
117}
118
119const inflight = new Map<string, Promise<unknown>>()
120
121async function fetchOnce(url: string): Promise<unknown> {
122  const cachePath = cachePathFor(url)
123  if (
124    existsSync(cachePath) &&
125    Date.now() - statSync(cachePath).mtimeMs < CACHE_TTL_MS
126  ) {
127    return JSON.parse(readFileSync(cachePath, 'utf-8'))
128  }
129  const ctrl = new AbortController()
130  const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
131  try {
132    const res = await fetch(url, { signal: ctrl.signal })
133    if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
134    const json = await res.json()
135    if (!cacheDirReady) {
136      mkdirSync(CACHE_DIR, { recursive: true })
137      cacheDirReady = true
138    }
139    const tmp = `${cachePath}.${process.pid}.tmp`
140    writeFileSync(tmp, JSON.stringify(json))
141    renameSync(tmp, cachePath)
142    return json
143  } finally {
144    clearTimeout(timer)
145  }
146}
147
148function fetchIndex(url: string): Promise<unknown> {
149  const hit = inflight.get(url)
150  if (hit) return hit
151  const p = (async () => {
152    for (let attempt = 0; attempt < 2; attempt++) {
153      try {
154        return await fetchOnce(url)
155      } catch (err) {
156        if (attempt === 1) {
157          const cachePath = cachePathFor(url)
158          if (existsSync(cachePath)) {
159            return JSON.parse(readFileSync(cachePath, 'utf-8'))
160          }
161          console.warn(
162            `[extrepo] failed to fetch ${url}: ${(err as Error).message}`
163          )
164          return []
165        }
166      }
167    }
168  })() as Promise<unknown>
169  inflight.set(url, p)
170  return p
171}
172
173export async function loadScheme(
174  scheme: string
175): Promise<ExtensionRepoData> {
176  const { indexUrls, listUrls } = collectScheme(scheme)
177  return assembleSchemeData(indexUrls, listUrls, fetchIndex)
178}