docs/ext/extensionRepos.data.ts

c5d5a5e6d8127763d92162dd39b34a6092451d93
wotaku/docs/ext/extensionRepos.data.ts history · blame · raw

826 lines · 24725 bytes

  1import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
  2import { dirname, join } from 'node:path'
  3import { fileURLToPath } from 'node:url'
  4
  5const IGNORED_DIRS = new Set(['node_modules', '.vitepress', '.git'])
  6
  7export type Rating = 'safe' | 'suggestive' | 'nsfw'
  8
  9export interface RepoSite {
 10  name: string
 11  lang: string
 12  icon: string
 13  url: string
 14  rating: Rating
 15  contentType?: string
 16  streamType?: string
 17  quality?: string
 18  isBroken?: boolean
 19  installUrl?: string
 20}
 21
 22interface MihonIndexSource {
 23  id: string
 24  name: string
 25  language: string
 26  homeUrl: string
 27  mirrorUrls?: string[]
 28}
 29
 30interface MihonIndexExtension {
 31  name: string
 32  packageName: string
 33  resources: {
 34    apkUrl: string
 35    iconUrl: string
 36    jarUrl: string
 37  }
 38  extensionLib: string
 39  versionCode: string
 40  versionName: string
 41  contentWarning: string
 42  sources: MihonIndexSource[]
 43}
 44
 45interface MihonIndex {
 46  name: string
 47  badgeLabel: string
 48  signingKey: string
 49  contact?: {
 50    website?: string
 51    discord?: string
 52  }
 53  extensionList: {
 54    extensions: MihonIndexExtension[]
 55  }
 56}
 57
 58export interface RepoData {
 59  sites: RepoSite[]
 60  suwatteV6?: boolean
 61  suwatteListUrl?: string
 62}
 63
 64interface MihonSource {
 65  name: string
 66  lang: string
 67  baseUrl: string
 68}
 69
 70interface MihonExtension {
 71  pkg: string
 72  nsfw?: number
 73  sources?: MihonSource[]
 74}
 75
 76interface AidokuSource {
 77  name: string
 78  iconURL: string
 79  languages?: string[]
 80  contentRating?: number
 81  baseURL: string
 82}
 83
 84interface AidokuIndex {
 85  sources: AidokuSource[]
 86}
 87
 88interface AidokuLegacySource {
 89  name: string
 90  icon: string
 91  lang: string
 92  nsfw?: number
 93}
 94
 95interface PaperbackSource {
 96  id: string
 97  name: string
 98  icon: string
 99  language?: string
100  contentRating?: string
101  websiteBaseURL?: string
102}
103
104interface PaperbackIndex {
105  sources: PaperbackSource[]
106  builtWith?: { toolchain?: string }
107}
108
109interface CloudstreamRepo {
110  pluginLists: string[]
111}
112
113interface CloudstreamPlugin {
114  name: string
115  iconUrl?: string
116  language?: string
117}
118
119interface HayaseExtension {
120  name: string
121  icon?: string
122  languages?: string[]
123}
124
125interface LegadoBookSource {
126  bookSourceName: string
127  bookSourceUrl: string
128  bookSourceGroup?: string
129}
130
131interface LNReaderPlugin {
132  name: string
133  lang: string
134  url: string
135  iconUrl?: string
136}
137
138interface MangayomiSource {
139  name: string
140  lang: string
141  baseUrl: string
142  iconUrl?: string
143  isNsfw?: boolean
144}
145
146interface IReaderSource {
147  pkg: string
148  apk: string
149  name: string
150  lang: string
151  nsfw?: boolean
152}
153
154interface SuwatteCatalogSource {
155  name: string
156  website?: string
157  languages?: string[]
158  thumbnail?: string
159  path?: string
160}
161
162interface SuwatteCatalogIndex {
163  listUrl?: string
164  catalogVersion?: number
165  sources: SuwatteCatalogSource[]
166}
167
168// For kotatsu
169interface KotatsuSite {
170  name: string
171  lang: string
172  url: string
173  icon: string
174  contentType: string
175  isBroken: boolean
176}
177
178interface KotatsuIndex {
179  sites: KotatsuSite[]
180}
181
182interface SoraRepoIndexEntry {
183  slug: string
184  name: string
185  source: string
186  path?: string
187  totalSources?: number
188  error?: string
189}
190
191interface SoraRepoIndex {
192  repos: SoraRepoIndexEntry[]
193}
194
195interface SoraModule {
196  sourceName: string
197  iconUrl?: string
198  iconURL?: string
199  language?: string
200  baseUrl?: string
201  scriptUrl?: string
202  scriptURL?: string
203  wotaku_sourceName?: string
204  wotaku_language?: string[]
205  wotaku_type?: string[]
206  wotaku_streamType?: string[]
207  wotaku_quality?: string[]
208}
209
210export interface SoraAuthorRepo {
211  label: string
212  repoUrl?: string
213  indexUrl: string
214}
215
216interface EchoExtension {
217  id: string
218  type: string
219  name: string
220  subtitle?: string
221  iconUrl?: string
222  url?: string
223  updateUrl: string
224}
225
226export interface EchoAuthorRepo {
227  label: string
228  repoUrl?: string
229  indexUrl: string
230}
231
232const EXT_DIR = dirname(fileURLToPath(import.meta.url))
233const DOCS_DIR = join(EXT_DIR, '..')
234const CACHE_DIR = join(EXT_DIR, '../.vitepress/cache/extension-repos')
235const CACHE_TTL_MS = 6 * 60 * 60 * 1000
236
237function findMarkdownFiles(dir: string): string[] {
238  const files: string[] = []
239  for (const entry of readdirSync(dir, { withFileTypes: true })) {
240    if (entry.isDirectory()) {
241      if (!IGNORED_DIRS.has(entry.name)) files.push(...findMarkdownFiles(join(dir, entry.name)))
242    } else if (entry.name.endsWith('.md')) {
243      files.push(join(dir, entry.name))
244    }
245  }
246  return files
247}
248
249function collectIndexUrls(): string[] {
250  const urls = new Set<string>()
251  const blockRe = /:::\s*extrepo[^\n]*\n([\s\S]*?)\n\s*:::/g
252  const rowRe = /^\s*-\s*(?:raw|manga|anime|novel|data)\s*:\s*(https?:\/\/\S+)\s*$/gim
253
254  for (const file of findMarkdownFiles(DOCS_DIR)) {
255    const src = readFileSync(file, 'utf-8')
256
257    let block: RegExpExecArray | null
258    blockRe.lastIndex = 0
259    while ((block = blockRe.exec(src))) {
260      rowRe.lastIndex = 0
261      let row: RegExpExecArray | null
262      while ((row = rowRe.exec(block[1]))) urls.add(row[1].trim())
263    }
264  }
265  return [...urls]
266}
267
268function cachePathFor(url: string): string {
269  return join(CACHE_DIR, `${Buffer.from(url).toString('base64url')}.json`)
270}
271
272async function fetchIndex(url: string): Promise<unknown> {
273  const cachePath = cachePathFor(url)
274  if (existsSync(cachePath) && Date.now() - statSync(cachePath).mtimeMs < CACHE_TTL_MS) {
275    return JSON.parse(readFileSync(cachePath, 'utf-8'))
276  }
277
278  try {
279    const res = await fetch(url)
280    if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
281    const json = await res.json()
282    mkdirSync(CACHE_DIR, { recursive: true })
283    writeFileSync(cachePath, JSON.stringify(json))
284    return json
285  } catch (err) {
286    if (existsSync(cachePath)) return JSON.parse(readFileSync(cachePath, 'utf-8'))
287    console.warn(`[extrepo] failed to fetch ${url}: ${(err as Error).message}`)
288    return []
289  }
290}
291
292function ratingFromLevel(level: number): Rating {
293  if (level >= 2) return 'nsfw'
294  if (level >= 1) return 'suggestive'
295  return 'safe'
296}
297
298const LANG_ALIASES: Record<string, string> = {
299  jp: 'ja',
300  english: 'en',
301  'bahasa indonesia': 'id',
302  español: 'es',
303  français: 'fr',
304  polski: 'pl',
305  português: 'pt',
306  'tiếng việt': 'vi',
307  türkçe: 'tr',
308  русский: 'ru',
309  українська: 'uk',
310  ไทย: 'th',
311  العربية: 'ar',
312  chinese: 'zh',
313  japanese: 'ja',
314  korean: 'ko',
315  french: 'fr',
316  german: 'de',
317  greek: 'el',
318  indonesian: 'id',
319  italian: 'it',
320  spanish: 'es',
321  turkish: 'tr',
322  polish: 'pl',
323  russian: 'ru',
324  portuguese: 'pt',
325  arabic: 'ar',
326  tamil: 'ta',
327  ukrainian: 'uk',
328  vietnamese: 'vi',
329  thai: 'th',
330  hindi: 'hi',
331  malay: 'ms',
332  serbian: 'sr'
333}
334
335const LANG_SUBSTRING_ALIASES: [RegExp, string][] = [
336  [/日语原版/, 'ja'],
337  [/中文|汉语|漢語|轻小说/, 'zh'],
338  [/日本語/, 'ja'],
339  [/한국어|조선말/, 'ko']
340]
341
342function normalizeLang(lang: string): string {
343  // Strip bidi control marks (e.g. U+200E/U+200F) some indices prepend to lang names.
344  const cleaned = lang.replace(/[‎‏]/g, '').trim()
345  if (cleaned === '') return 'all'
346  const exact = LANG_ALIASES[cleaned.toLowerCase()]
347  if (exact) return exact
348  for (const [re, code] of LANG_SUBSTRING_ALIASES) {
349    if (re.test(cleaned)) return code
350  }
351  const key = cleaned.toLowerCase()
352  return key === 'multi' ? 'all' : key
353}
354
355function toRepoDataMihon(iconBase: string, extensions: MihonExtension[]): RepoSite[] {
356  const seen = new Set<string>()
357  const sites: RepoSite[] = []
358
359  for (const ext of extensions) {
360    const icon = `${iconBase}/icon/${ext.pkg}.png`
361    for (const source of ext.sources ?? []) {
362      const key = `${source.name}::${source.lang}::${source.baseUrl}`
363      if (seen.has(key)) continue
364      seen.add(key)
365      sites.push({ name: source.name, lang: source.lang, icon, url: source.baseUrl, rating: ext.nsfw === 1 ? 'nsfw' : 'safe' })
366    }
367  }
368
369  return sites
370}
371
372function toRepoDataAidoku(iconBase: string, index: AidokuIndex): RepoSite[] {
373  const seen = new Set<string>()
374  const sites: RepoSite[] = []
375
376  for (const source of index.sources ?? []) {
377    const icon = `${iconBase}/${source.iconURL}`
378    const rating = ratingFromLevel(source.contentRating ?? 0)
379    const langs = source.languages?.length ? source.languages : ['all']
380    for (const rawLang of langs) {
381      const lang = normalizeLang(rawLang)
382      const key = `${source.name}::${lang}::${source.baseURL}`
383      if (seen.has(key)) continue
384      seen.add(key)
385      sites.push({ name: source.name, lang, icon, url: source.baseURL, rating })
386    }
387  }
388
389  return sites
390}
391
392function toRepoDataPaperback(iconBase: string, index: PaperbackIndex): RepoSite[] {
393  const seen = new Set<string>()
394  const sites: RepoSite[] = []
395  // Legacy 0.8.x toolchain builds serve icons under `<id>/includes/`
396  const iconDir = index.builtWith?.toolchain?.startsWith('0.8') ? 'includes' : 'static'
397
398  for (const source of index.sources ?? []) {
399    const lang = normalizeLang(source.language ?? 'all')
400    const key = `${source.id}::${lang}`
401    if (seen.has(key)) continue
402    seen.add(key)
403    const icon = `${iconBase}/${source.id}/${iconDir}/${source.icon}`
404    const rating: Rating = source.contentRating === 'ADULT' ? 'nsfw' : source.contentRating === 'MATURE' ? 'suggestive' : 'safe'
405    sites.push({ name: source.name, lang, icon, url: source.websiteBaseURL ?? '', rating })
406  }
407
408  return sites
409}
410
411function normalizeGoogleFaviconUrl(url: string): string {
412  return url.replace('%size%', '64')
413}
414
415async function toRepoDataCloudstream(repo: CloudstreamRepo): Promise<RepoSite[]> {
416  const seen = new Set<string>()
417  const sites: RepoSite[] = []
418
419  const lists = await Promise.all(repo.pluginLists.map(url => fetchIndex(url)))
420  for (const list of lists) {
421    if (!Array.isArray(list)) continue
422    for (const plugin of list as CloudstreamPlugin[]) {
423      if (seen.has(plugin.name)) continue
424      seen.add(plugin.name)
425      const lang = normalizeLang(plugin.language ?? 'all')
426      const icon = plugin.iconUrl ? normalizeGoogleFaviconUrl(plugin.iconUrl) : ''
427      sites.push({ name: plugin.name, lang, icon, url: '', rating: 'safe' })
428    }
429  }
430
431  return sites
432}
433
434function toRepoDataAidokuLegacy(iconBase: string, sources: AidokuLegacySource[]): RepoSite[] {
435  const seen = new Set<string>()
436  const sites: RepoSite[] = []
437
438  for (const source of sources) {
439    const lang = normalizeLang(source.lang)
440    const key = `${source.name}::${lang}`
441    if (seen.has(key)) continue
442    seen.add(key)
443    sites.push({ name: source.name, lang, icon: `${iconBase}/icons/${source.icon}`, url: '', rating: ratingFromLevel(source.nsfw ?? 0) })
444  }
445
446  return sites
447}
448
449function toRepoDataHayase(extensions: HayaseExtension[]): RepoSite[] {
450  const seen = new Set<string>()
451  const sites: RepoSite[] = []
452
453  for (const ext of extensions) {
454    const langs = ext.languages?.length ? ext.languages : ['all']
455    for (const rawLang of langs) {
456      const lang = normalizeLang(rawLang)
457      const key = `${ext.name}::${lang}`
458      if (seen.has(key)) continue
459      seen.add(key)
460      sites.push({ name: ext.name, lang, icon: ext.icon ?? '', url: '', rating: 'safe' })
461    }
462  }
463
464  return sites
465}
466
467function toRepoDataLegado(sources: LegadoBookSource[]): RepoSite[] {
468  const seen = new Set<string>()
469  const sites: RepoSite[] = []
470
471  for (const source of sources) {
472    const lang = normalizeLang(source.bookSourceGroup ?? 'all')
473    const key = `${source.bookSourceName}::${lang}`
474    if (seen.has(key)) continue
475    seen.add(key)
476    sites.push({ name: source.bookSourceName, lang, icon: '', url: source.bookSourceUrl, rating: 'safe' })
477  }
478
479  return sites
480}
481
482function toRepoDataMangayomi(sources: MangayomiSource[]): RepoSite[] {
483  const seen = new Set<string>()
484  const sites: RepoSite[] = []
485
486  for (const source of sources) {
487    const lang = normalizeLang(source.lang)
488    const key = `${source.name}::${lang}`
489    if (seen.has(key)) continue
490    seen.add(key)
491    sites.push({ name: source.name, lang, icon: source.iconUrl ?? '', url: source.baseUrl, rating: source.isNsfw ? 'nsfw' : 'safe' })
492  }
493
494  return sites
495}
496
497function toRepoDataIReader(sources: IReaderSource[]): RepoSite[] {
498  const seen = new Set<string>()
499  const sites: RepoSite[] = []
500
501  for (const source of sources) {
502    const lang = normalizeLang(source.lang)
503    const key = `${source.name}::${lang}`
504    if (seen.has(key)) continue
505    seen.add(key)
506    // No confirmed icon path convention in this repo's format — omit rather than guess wrong.
507    sites.push({ name: source.name, lang, icon: '', url: '', rating: source.nsfw ? 'nsfw' : 'safe' })
508  }
509
510  return sites
511}
512
513function toRepoDataSuwatte(iconBase: string, index: SuwatteCatalogIndex): { sites: RepoSite[]; listUrl: string } {
514  const seen = new Set<string>()
515  const sites: RepoSite[] = []
516
517  const listUrl = index.listUrl ?? iconBase
518  const isV6 = index.catalogVersion === undefined
519
520  for (const source of index.sources ?? []) {
521    const langs = source.languages?.length ? source.languages : ['all']
522    const icon = source.thumbnail
523      ? (/^https?:\/\//i.test(source.thumbnail) ? source.thumbnail : `${iconBase}/assets/${source.thumbnail}`)
524      : ''
525    const installUrl = source.path
526      ? (isV6
527          ? `suwatte://runner?url=${listUrl}&runner=${source.path}`
528          : `suwatte://AddSourceFromList?list=${listUrl}&source=${source.path}`)
529      : undefined
530    for (const rawLang of langs) {
531      const lang = normalizeLang(rawLang)
532      const key = `${source.name}::${lang}`
533      if (seen.has(key)) continue
534      seen.add(key)
535      sites.push({ name: source.name, lang, icon, url: source.website ?? '', rating: 'safe', installUrl })
536    }
537  }
538
539  return { sites, listUrl }
540}
541
542function toRepoDataKotatsu(index: KotatsuIndex): RepoSite[] {
543  const seen = new Set<string>()
544  const sites: RepoSite[] = []
545
546  for (const site of index.sites) {
547    const lang = normalizeLang(site.lang)
548    const key = `${site.name}::${lang}::${site.url}`
549    if (seen.has(key)) continue
550    seen.add(key)
551    const rating: Rating = site.contentType.includes('HENTAI') ? 'nsfw' : 'safe'
552    sites.push({ name: site.name, lang, icon: site.icon, url: site.url, rating, contentType: site.contentType, isBroken: site.isBroken || undefined })
553  }
554
555  return sites
556}
557
558function isSoraRepoIndex(json: unknown): json is SoraRepoIndex {
559  return !!json && typeof json === 'object' && Array.isArray((json as SoraRepoIndex).repos)
560}
561
562function normalizeSoraLang(language: string | undefined): string {
563  const stripped = (language ?? '').replace(/\s*\([^)]*\)\s*$/, '').trim()
564  if (stripped.toLowerCase().startsWith('multi')) return 'all'
565  return normalizeLang(stripped)
566}
567
568function toRepoDataSoraModules(modules: SoraModule[]): RepoSite[] {
569  const seen = new Set<string>()
570  const sites: RepoSite[] = []
571
572  for (const mod of modules) {
573    const name = mod.wotaku_sourceName ?? mod.sourceName
574    const langs = mod.wotaku_language?.length ? mod.wotaku_language : [mod.language]
575    const scriptUrl = mod.scriptUrl ?? mod.scriptURL
576    const installUrl = scriptUrl?.replace(/\.js$/i, '.json')
577    for (const rawLang of langs) {
578      const lang = normalizeSoraLang(rawLang)
579      const key = `${name}::${lang}::${installUrl ?? ''}`
580      if (seen.has(key)) continue
581      seen.add(key)
582      sites.push({
583        name,
584        lang,
585        icon: mod.iconUrl ?? mod.iconURL ?? '',
586        url: mod.baseUrl ?? '',
587        rating: 'safe',
588        contentType: mod.wotaku_type?.[0],
589        streamType: mod.wotaku_streamType?.[0],
590        quality: mod.wotaku_quality?.[0],
591        installUrl: installUrl ? `sora://module?url=${installUrl}` : undefined
592      })
593    }
594  }
595
596  sites.sort((a, b) => a.name.localeCompare(b.name))
597  return sites
598}
599
600async function loadSoraRepoIndex(indexUrl: string, index: SoraRepoIndex): Promise<{ sites: RepoSite[]; authorRepos: SoraAuthorRepo[]; sitesByAuthor: Record<string, RepoData> }> {
601  const seen = new Set<string>()
602  const sites: RepoSite[] = []
603  const authorRepos: SoraAuthorRepo[] = []
604  const sitesByAuthor: Record<string, RepoData> = {}
605
606  const entries = index.repos.filter(repo => repo.path && !repo.error)
607  const fileUrls = entries.map(repo => new URL(repo.path!, indexUrl).toString())
608  const moduleLists = await Promise.all(fileUrls.map(url => fetchIndex(url)))
609
610  entries.forEach((repo, i) => {
611    const modules = moduleLists[i]
612    const authorSites = Array.isArray(modules) ? toRepoDataSoraModules(modules as SoraModule[]) : []
613    const fileUrl = fileUrls[i]
614    sitesByAuthor[fileUrl] = { sites: authorSites }
615    authorRepos.push({ label: repo.name, repoUrl: repo.source?.replace(/\.git$/, ''), indexUrl: fileUrl })
616    for (const site of authorSites) {
617      const key = `${site.name}::${site.lang}::${site.installUrl ?? ''}`
618      if (seen.has(key)) continue
619      seen.add(key)
620      sites.push(site)
621    }
622  })
623
624  authorRepos.sort((a, b) => a.label.localeCompare(b.label))
625  sites.sort((a, b) => a.name.localeCompare(b.name))
626  return { sites, authorRepos, sitesByAuthor }
627}
628
629function isEchoExtensionList(json: unknown): json is EchoExtension[] {
630  if (!Array.isArray(json) || json.length === 0) return false
631  const first = json[0] as Record<string, unknown>
632  return typeof first.updateUrl === 'string' && typeof first.subtitle === 'string' && !('lang' in first) && !('baseUrl' in first)
633}
634
635function parseEchoRepo(updateUrl: string): { host: string; owner: string; repo: string; repoUrl: string; ownerUrl: string } | undefined {
636  const githubMatch = updateUrl.match(/^https:\/\/api\.github\.com\/repos\/([^/]+)\/([^/]+)\/releases$/)
637  if (githubMatch) {
638    const [, owner, repo] = githubMatch
639    return { host: 'github.com', owner, repo, repoUrl: `https://github.com/${owner}/${repo}`, ownerUrl: `https://github.com/${owner}` }
640  }
641
642  const gitlabMatch = updateUrl.match(/^https:\/\/(gitlab\.com)\/api\/v4\/projects\/([^/]+)\/releases\b/)
643  if (gitlabMatch) {
644    const [, host, encodedPath] = gitlabMatch
645    const path = decodeURIComponent(encodedPath)
646    const owner = path.slice(0, path.lastIndexOf('/'))
647    const repo = path.slice(path.lastIndexOf('/') + 1)
648    if (!owner || !repo) return undefined
649    return { host, owner, repo, repoUrl: `https://${host}/${path}`, ownerUrl: `https://${host}/${owner}` }
650  }
651
652  return undefined
653}
654
655function toRepoDataEchoExtensions(extensions: EchoExtension[]): RepoSite[] {
656  const seen = new Set<string>()
657  const sites: RepoSite[] = []
658
659  for (const ext of extensions) {
660    const key = `${ext.id}::${ext.updateUrl}`
661    if (seen.has(key)) continue
662    seen.add(key)
663    const repo = parseEchoRepo(ext.updateUrl)
664    sites.push({
665      name: ext.name,
666      lang: 'all',
667      icon: ext.iconUrl ?? '',
668      url: ext.url ?? repo?.repoUrl ?? '',
669      rating: 'safe',
670      contentType: ext.type,
671      installUrl: repo?.repoUrl
672    })
673  }
674
675  sites.sort((a, b) => a.name.localeCompare(b.name))
676  return sites
677}
678
679function loadEchoExtensionList(indexUrl: string, extensions: EchoExtension[]): { sites: RepoSite[]; authorRepos: EchoAuthorRepo[]; sitesByAuthor: Record<string, RepoData> } {
680  const byAuthor = new Map<string, { label: string; ownerUrl?: string; exts: EchoExtension[] }>()
681  for (const ext of extensions) {
682    const repo = parseEchoRepo(ext.updateUrl)
683    const key = repo ? `${repo.host}:${repo.owner}` : 'Unknown'
684    const bucket = byAuthor.get(key)
685    if (bucket) bucket.exts.push(ext)
686    else byAuthor.set(key, { label: repo?.owner ?? 'Unknown', ownerUrl: repo?.ownerUrl, exts: [ext] })
687  }
688
689  const authorRepos: EchoAuthorRepo[] = []
690  const sitesByAuthor: Record<string, RepoData> = {}
691  for (const [key, { label, ownerUrl, exts }] of byAuthor) {
692    const authorIndexUrl = `${indexUrl}#${key}`
693    sitesByAuthor[authorIndexUrl] = { sites: toRepoDataEchoExtensions(exts) }
694    authorRepos.push({ label, repoUrl: ownerUrl, indexUrl: authorIndexUrl })
695  }
696
697  authorRepos.sort((a, b) => a.label.localeCompare(b.label))
698  return { sites: toRepoDataEchoExtensions(extensions), authorRepos, sitesByAuthor }
699}
700
701function toRepoDataLNReader(plugins: LNReaderPlugin[]): RepoSite[] {
702  const seen = new Set<string>()
703  const sites: RepoSite[] = []
704
705  for (const plugin of plugins) {
706    const lang = normalizeLang(plugin.lang)
707    const key = `${plugin.name}::${lang}`
708    if (seen.has(key)) continue
709    seen.add(key)
710    sites.push({ name: plugin.name, lang, icon: plugin.iconUrl ?? '', url: plugin.url, rating: 'safe' })
711  }
712
713  return sites
714}
715
716const CONTENT_WARNING_RATING: Record<string, Rating> = {
717  CONTENT_WARNING_NSFW: 'nsfw',
718  CONTENT_WARNING_MIXED: 'suggestive',
719  CONTENT_WARNING_SAFE: 'safe'
720}
721
722function toRepoDataMihonNew(index: MihonIndex): RepoSite[] {
723  const seen = new Set<string>()
724  const sites: RepoSite[] = []
725
726  for (const ext of index.extensionList.extensions) {
727    const icon = ext.resources.iconUrl
728    const rating = CONTENT_WARNING_RATING[ext.contentWarning] ?? 'safe'
729
730    for (const source of ext.sources) {
731      const key = `${source.name}::${source.language}::${source.homeUrl}`
732      if (seen.has(key)) continue
733      seen.add(key)
734      sites.push({ name: source.name, lang: source.language, icon, url: source.homeUrl, rating })
735    }
736  }
737
738  sites.sort((a, b) => a.name.localeCompare(b.name))
739  return sites
740}
741
742async function toRepoData(indexUrl: string, json: unknown): Promise<RepoData> {
743  const iconBase = indexUrl.slice(0, indexUrl.lastIndexOf('/'))
744  let sites: RepoSite[]
745  let suwatteV6: boolean | undefined
746  let suwatteListUrl: string | undefined
747
748  if (
749    json && typeof json === 'object' && !Array.isArray(json)
750    && 'extensionList' in (json as Record<string, unknown>)
751  ) {
752    sites = toRepoDataMihonNew(json as MihonIndex)
753    return { sites }
754  }
755
756  if (Array.isArray(json)) {
757    const first = json[0] as Record<string, unknown> | undefined
758    if (first && 'bookSourceUrl' in first) {
759      sites = toRepoDataLegado(json as LegadoBookSource[])
760    } else if (first && 'manifestVersion' in first) {
761      sites = toRepoDataHayase(json as HayaseExtension[])
762    } else if (first && 'iconUrl' in first && 'site' in first) {
763      sites = toRepoDataLNReader(json as LNReaderPlugin[])
764    } else if (first && 'sources' in first) {
765      sites = toRepoDataMihon(iconBase, json as MihonExtension[])
766    } else if (first && 'pkg' in first && 'apk' in first) {
767      sites = toRepoDataIReader(json as IReaderSource[])
768    } else if (first && 'iconUrl' in first && 'baseUrl' in first) {
769      sites = toRepoDataMangayomi(json as MangayomiSource[])
770    } else {
771      sites = toRepoDataAidokuLegacy(iconBase, json as AidokuLegacySource[])
772    }
773  } else if (Array.isArray((json as CloudstreamRepo).pluginLists)) {
774    sites = await toRepoDataCloudstream(json as CloudstreamRepo)
775  } else if ((json as AidokuIndex).sources?.length && 'iconURL' in (json as AidokuIndex).sources[0]) {
776    sites = toRepoDataAidoku(iconBase, json as AidokuIndex)
777  } else if ((json as SuwatteCatalogIndex).sources?.length && 'thumbnail' in (json as SuwatteCatalogIndex).sources[0]) {
778    const result = toRepoDataSuwatte(iconBase, json as SuwatteCatalogIndex)
779    sites = result.sites
780    suwatteListUrl = result.listUrl
781    suwatteV6 = (json as SuwatteCatalogIndex).catalogVersion === undefined
782  } else if (Array.isArray((json as KotatsuIndex).sites)) {
783    sites = toRepoDataKotatsu(json as KotatsuIndex)
784  } else {
785    sites = toRepoDataPaperback(iconBase, json as PaperbackIndex)
786  }
787  sites.sort((a, b) => a.name.localeCompare(b.name))
788  return { sites, suwatteV6, suwatteListUrl }
789}
790
791export interface ExtensionRepoData {
792  sites: Record<string, RepoData>
793  soraAuthors: Record<string, SoraAuthorRepo[]>
794  echoAuthors: Record<string, EchoAuthorRepo[]>
795}
796
797export declare const data: ExtensionRepoData
798
799export default {
800  watch: ['../**/*.md'],
801  async load(): Promise<ExtensionRepoData> {
802    const urls = collectIndexUrls()
803    const sites: Record<string, RepoData> = {}
804    const soraAuthors: Record<string, SoraAuthorRepo[]> = {}
805    const echoAuthors: Record<string, EchoAuthorRepo[]> = {}
806    await Promise.all(urls.map(async url => {
807      const json = await fetchIndex(url)
808      if (isSoraRepoIndex(json)) {
809        const result = await loadSoraRepoIndex(url, json)
810        sites[url] = { sites: result.sites }
811        soraAuthors[url] = result.authorRepos
812        Object.assign(sites, result.sitesByAuthor)
813        return
814      }
815      if (isEchoExtensionList(json)) {
816        const result = loadEchoExtensionList(url, json)
817        sites[url] = { sites: result.sites }
818        echoAuthors[url] = result.authorRepos
819        Object.assign(sites, result.sitesByAuthor)
820        return
821      }
822      sites[url] = await toRepoData(url, json)
823    }))
824    return { sites, soraAuthors, echoAuthors }
825  }
826}