docs/ext/extensionRepos.data.ts

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

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