docs/ext/extensionRepos/parsers.ts

1303 lines · 33791 bytes

84 symbols in this file
   1import type {
   2  Rating,
   3  RepoSite
   4} from '../../.vitepress/theme/components/extrepo/types'
   5
   6interface MihonIndexSource {
   7  id: string
   8  name: string
   9  language: string
  10  homeUrl: string
  11  mirrorUrls?: string[]
  12}
  13
  14interface MihonIndexExtension {
  15  name: string
  16  packageName: string
  17  resources: {
  18    apkUrl: string
  19    iconUrl: string
  20    jarUrl: string
  21  }
  22  extensionLib: string
  23  versionCode: string
  24  versionName: string
  25  contentWarning: string
  26  sources: MihonIndexSource[]
  27}
  28
  29interface MihonIndex {
  30  name: string
  31  badgeLabel: string
  32  signingKey: string
  33  contact?: {
  34    website?: string
  35    discord?: string
  36  }
  37  extensionList: {
  38    extensions: MihonIndexExtension[]
  39  }
  40}
  41
  42export interface RepoData {
  43  sites: RepoSite[]
  44  suwatteV6?: boolean
  45  suwatteListUrl?: string
  46}
  47
  48interface MihonSource {
  49  name: string
  50  lang: string
  51  baseUrl: string
  52}
  53
  54interface MihonExtension {
  55  pkg: string
  56  nsfw?: number
  57  sources?: MihonSource[]
  58}
  59
  60interface AidokuSource {
  61  name: string
  62  iconURL: string
  63  languages?: string[]
  64  contentRating?: number
  65  baseURL: string
  66}
  67
  68interface AidokuIndex {
  69  sources: AidokuSource[]
  70}
  71
  72interface AidokuLegacySource {
  73  name: string
  74  icon: string
  75  lang: string
  76  nsfw?: number
  77}
  78
  79interface PaperbackSource {
  80  id: string
  81  name: string
  82  icon: string
  83  language?: string
  84  contentRating?: string
  85  websiteBaseURL?: string
  86}
  87
  88interface PaperbackIndex {
  89  sources: PaperbackSource[]
  90  builtWith?: { toolchain?: string }
  91}
  92
  93interface CloudstreamRepo {
  94  name?: string
  95  pluginLists: string[]
  96}
  97
  98interface CloudstreamRepoListItem {
  99  url: string
 100  verified?: boolean
 101}
 102
 103export interface RepoListEntry {
 104  label: string
 105  indexUrl: string
 106  repoUrl?: string
 107}
 108
 109interface CloudstreamPlugin {
 110  name: string
 111  iconUrl?: string
 112  language?: string
 113}
 114
 115interface HayaseExtension {
 116  name: string
 117  icon?: string
 118  languages?: string[]
 119}
 120
 121interface LNReaderPlugin {
 122  name: string
 123  lang: string
 124  url: string
 125  iconUrl?: string
 126}
 127
 128interface MangayomiSource {
 129  name: string
 130  lang: string
 131  baseUrl: string
 132  iconUrl?: string
 133  isNsfw?: boolean
 134}
 135
 136interface IReaderSource {
 137  pkg: string
 138  apk: string
 139  name: string
 140  lang: string
 141  nsfw?: boolean
 142}
 143
 144interface SuwatteCatalogSource {
 145  name: string
 146  website?: string
 147  languages?: string[]
 148  thumbnail?: string
 149  path?: string
 150}
 151
 152interface SuwatteCatalogIndex {
 153  listUrl?: string
 154  catalogVersion?: number
 155  sources: SuwatteCatalogSource[]
 156}
 157
 158interface ManaSource {
 159  id?: string
 160  name: string
 161  thumbnail?: string
 162  website?: string
 163  rating?: number
 164  supportedLanguages?: string[]
 165}
 166
 167interface ManaIndex {
 168  repositoryName?: string
 169  sources: ManaSource[]
 170}
 171
 172interface KotatsuSite {
 173  name: string
 174  lang: string
 175  url: string
 176  icon: string
 177  contentType: string
 178  isBroken: boolean
 179}
 180
 181interface KotatsuIndex {
 182  sites: KotatsuSite[]
 183}
 184
 185interface NuvioScraper {
 186  name: string
 187  icon?: string
 188  logo?: string
 189  description?: string
 190  types?: string[]
 191  supportedTypes?: string[]
 192  language?: string[]
 193  contentLanguage?: string[]
 194  enabled?: boolean
 195}
 196
 197interface NuvioManifest {
 198  name?: string
 199  scrapers?: NuvioScraper[]
 200}
 201
 202interface SoraRepoIndexEntry {
 203  name: string
 204  source: string
 205  path?: string
 206  error?: string
 207}
 208
 209interface SoraRepoIndex {
 210  repos: SoraRepoIndexEntry[]
 211}
 212
 213interface SoraModule {
 214  sourceName: string
 215  iconUrl?: string
 216  iconURL?: string
 217  language?: string
 218  baseUrl?: string
 219  scriptUrl?: string
 220  scriptURL?: string
 221  wotaku_sourceName?: string
 222  wotaku_language?: string[]
 223  wotaku_type?: string[]
 224}
 225
 226export interface SoraAuthorRepo {
 227  label: string
 228  repoUrl?: string
 229  indexUrl: string
 230}
 231
 232interface StremioAddon {
 233  name?: string
 234  icon?: string | null
 235  manifestUrl: string
 236  types?: string[] | null
 237}
 238
 239interface StremioCollection {
 240  addons?: StremioAddon[]
 241}
 242
 243interface EchoExtension {
 244  id: string
 245  type: string
 246  name: string
 247  subtitle?: string
 248  iconUrl?: string
 249  url?: string
 250  updateUrl: string
 251}
 252
 253export interface EchoAuthorRepo {
 254  label: string
 255  repoUrl?: string
 256  indexUrl: string
 257}
 258
 259interface SeanimeMarketplaceEntry {
 260  id?: string
 261  name: string
 262  description?: string
 263  author?: string
 264  version?: string
 265  type?: string
 266  language?: string
 267  lang?: string
 268  icon?: string
 269  manifestURI: string
 270  payloadURI?: string
 271  website?: string
 272  workingTag?: boolean
 273  brokenTag?: boolean
 274  deprecatedTag?: boolean
 275}
 276
 277const FETCH_TIMEOUT_MS = 15000
 278const FETCH_CONCURRENCY = 10
 279
 280export type FetchJson = (url: string) => Promise<unknown | undefined>
 281
 282export async function fetchJsonHttp(url: string): Promise<unknown | undefined> {
 283  for (let attempt = 0; attempt < 2; attempt++) {
 284    const ctrl = new AbortController()
 285    const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
 286    try {
 287      const res = await fetch(url, { signal: ctrl.signal })
 288      if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
 289      return (await res.json()) as unknown
 290    } catch {
 291      if (attempt === 1) return undefined
 292    } finally {
 293      clearTimeout(timer)
 294    }
 295  }
 296  return undefined
 297}
 298
 299async function mapLimit<T, R>(
 300  items: T[],
 301  limit: number,
 302  fn: (item: T, i: number) => Promise<R>
 303): Promise<R[]> {
 304  const out: R[] = new Array(items.length)
 305  let next = 0
 306  const workers = Array.from(
 307    { length: Math.min(limit, items.length) },
 308    async () => {
 309      while (next < items.length) {
 310        const i = next++
 311        out[i] = await fn(items[i], i)
 312      }
 313    }
 314  )
 315  await Promise.all(workers)
 316  return out
 317}
 318
 319function isCloudstreamRepoList(
 320  json: unknown
 321): json is Array<string | CloudstreamRepoListItem> {
 322  if (!Array.isArray(json) || json.length === 0) return false
 323  return json.every((item) => {
 324    if (typeof item === 'string') return /^https?:\/\//.test(item)
 325    if (item && typeof item === 'object') {
 326      const rec = item as Record<string, unknown>
 327      if (
 328        'name' in rec || 'lang' in rec || 'baseUrl' in rec || 'baseURL' in rec
 329      ) return false
 330      return typeof rec.url === 'string' && /^https?:\/\//.test(rec.url)
 331    }
 332    return false
 333  })
 334}
 335
 336function inferRepoUrl(rawUrl: string): string | undefined {
 337  try {
 338    const u = new URL(rawUrl)
 339    const parts = u.pathname.split('/').filter(Boolean)
 340    if (u.hostname === 'raw.githubusercontent.com' && parts.length >= 2) {
 341      return `https://github.com/${parts[0]}/${parts[1]}`
 342    }
 343    const dashRaw = u.pathname.indexOf('/-/raw/')
 344    if (dashRaw > 0) return `${u.origin}${u.pathname.slice(0, dashRaw)}`
 345    const rawSeg = parts.indexOf('raw')
 346    if (rawSeg > 1) return `${u.origin}/${parts.slice(0, rawSeg).join('/')}`
 347  } catch {
 348    return undefined
 349  }
 350  return undefined
 351}
 352
 353function inferLabel(rawUrl: string): string {
 354  const repoUrl = inferRepoUrl(rawUrl)
 355  if (repoUrl) {
 356    try {
 357      const parts = new URL(repoUrl).pathname.split('/').filter(Boolean)
 358      if (parts.length >= 2) {
 359        return `${parts[parts.length - 2]}/${parts[parts.length - 1]}`
 360      }
 361      if (parts.length === 1) return decodeURIComponent(parts[0])
 362    } catch {
 363      // fall through below
 364    }
 365  }
 366  try {
 367    const parts = new URL(rawUrl).pathname.split('/').filter(Boolean)
 368    return decodeURIComponent(
 369      parts[parts.length - 2] ?? parts[parts.length - 1] ?? rawUrl
 370    )
 371  } catch {
 372    return rawUrl
 373  }
 374}
 375
 376function repoListLabel(indexUrl: string, repoJson: unknown): string {
 377  if (repoJson && typeof repoJson === 'object' && !Array.isArray(repoJson)) {
 378    const name = (repoJson as { name?: unknown }).name
 379    if (typeof name === 'string' && name.trim() !== '') return name.trim()
 380  }
 381  return inferLabel(indexUrl)
 382}
 383
 384function ratingFromLevel(level: number): Rating {
 385  if (level >= 2) return 'nsfw'
 386  if (level >= 1) return 'mixed'
 387  return 'safe'
 388}
 389
 390const LANG_ALIASES: Record<string, string> = {
 391  jp: 'ja',
 392  english: 'en',
 393  'bahasa indonesia': 'id',
 394  español: 'es',
 395  français: 'fr',
 396  polski: 'pl',
 397  português: 'pt',
 398  'tiếng việt': 'vi',
 399  türkçe: 'tr',
 400  русский: 'ru',
 401  українська: 'uk',
 402  ไทย: 'th',
 403  العربية: 'ar',
 404  chinese: 'zh',
 405  japanese: 'ja',
 406  korean: 'ko',
 407  french: 'fr',
 408  german: 'de',
 409  greek: 'el',
 410  indonesian: 'id',
 411  italian: 'it',
 412  spanish: 'es',
 413  turkish: 'tr',
 414  polish: 'pl',
 415  russian: 'ru',
 416  portuguese: 'pt',
 417  arabic: 'ar',
 418  tamil: 'ta',
 419  ukrainian: 'uk',
 420  vietnamese: 'vi',
 421  thai: 'th',
 422  hindi: 'hi',
 423  malay: 'ms',
 424  serbian: 'sr',
 425  hin: 'hi',
 426  tam: 'ta',
 427  tel: 'te',
 428  mal: 'ml',
 429  kan: 'kn',
 430  ben: 'bn',
 431  ita: 'it',
 432  jpn: 'ja',
 433  kor: 'ko',
 434  chi: 'zh',
 435  ch: 'zh',
 436  ger: 'de',
 437  deu: 'de',
 438  fra: 'fr',
 439  fre: 'fr',
 440  spa: 'es',
 441  por: 'pt',
 442  rus: 'ru',
 443  ara: 'ar',
 444  tur: 'tr',
 445  pol: 'pl',
 446  ukr: 'uk',
 447  vie: 'vi',
 448  tha: 'th',
 449  ind: 'id',
 450  may: 'ms',
 451  msa: 'ms',
 452  ba: 'bn',
 453  kr: 'ko',
 454  pe: 'fa',
 455  nld: 'nl',
 456  dut: 'nl',
 457  swe: 'sv',
 458  nor: 'no',
 459  dan: 'da',
 460  fin: 'fi',
 461  ell: 'el',
 462  heb: 'he'
 463}
 464
 465const LANG_SUBSTRING_ALIASES: [RegExp, string][] = [
 466  [/日语原版/, 'ja'],
 467  [/中文|汉语|漢語|轻小说/, 'zh'],
 468  [/日本語/, 'ja'],
 469  [/한국어|조선말/, 'ko']
 470]
 471
 472const langCache = new Map<string, string>()
 473
 474function normalizeLang(lang: string): string {
 475  const hit = langCache.get(lang)
 476  if (hit !== undefined) return hit
 477  const cleaned = lang.replace(/[\u200E\u200F]/g, '').trim()
 478  let out: string
 479  if (cleaned === '') out = 'all'
 480  else {
 481    const exact = LANG_ALIASES[cleaned.toLowerCase()]
 482    if (exact) out = exact
 483    else {
 484      out = cleaned.toLowerCase()
 485      for (const [re, code] of LANG_SUBSTRING_ALIASES) {
 486        if (re.test(cleaned)) {
 487          out = code
 488          break
 489        }
 490      }
 491      if (out === 'multi') out = 'all'
 492    }
 493  }
 494  if (langCache.size > 2000) langCache.clear()
 495  langCache.set(lang, out)
 496  return out
 497}
 498
 499function sortSites(sites: RepoSite[]): RepoSite[] {
 500  return sites.sort((a, b) => a.name.localeCompare(b.name))
 501}
 502
 503function addSite(
 504  seen: Set<string>,
 505  key: string,
 506  sites: RepoSite[],
 507  site: RepoSite
 508): void {
 509  if (seen.has(key)) return
 510  seen.add(key)
 511  sites.push(site)
 512}
 513
 514function toRepoDataMihon(
 515  iconBase: string,
 516  extensions: MihonExtension[]
 517): RepoSite[] {
 518  const seen = new Set<string>()
 519  const sites: RepoSite[] = []
 520  for (const ext of extensions) {
 521    const icon = `${iconBase}/icon/${ext.pkg}.png`
 522    for (const source of ext.sources ?? []) {
 523      addSite(
 524        seen,
 525        `${source.name}::${source.lang}::${source.baseUrl}`,
 526        sites,
 527        {
 528          name: source.name ?? ext.pkg,
 529          lang: source.lang ?? 'all',
 530          icon,
 531          url: source.baseUrl ?? '',
 532          rating: ext.nsfw === 1 ? 'nsfw' : 'safe'
 533        }
 534      )
 535    }
 536  }
 537  return sites
 538}
 539
 540function toRepoDataAidoku(iconBase: string, index: AidokuIndex): RepoSite[] {
 541  const seen = new Set<string>()
 542  const sites: RepoSite[] = []
 543  for (const source of index.sources ?? []) {
 544    const icon = `${iconBase}/${source.iconURL}`
 545    const rating = ratingFromLevel(source.contentRating ?? 0)
 546    const langs = source.languages?.length ? source.languages : ['all']
 547    for (const rawLang of langs) {
 548      const lang = normalizeLang(rawLang)
 549      addSite(seen, `${source.name}::${lang}::${source.baseURL}`, sites, {
 550        name: source.name,
 551        lang,
 552        icon,
 553        url: source.baseURL,
 554        rating
 555      })
 556    }
 557  }
 558  return sites
 559}
 560
 561function toRepoDataPaperback(
 562  iconBase: string,
 563  index: PaperbackIndex
 564): RepoSite[] {
 565  const seen = new Set<string>()
 566  const sites: RepoSite[] = []
 567  const iconDir = index.builtWith?.toolchain?.startsWith('0.8')
 568    ? 'includes'
 569    : 'static'
 570  for (const source of index.sources ?? []) {
 571    const lang = normalizeLang(source.language ?? 'all')
 572    const key = `${source.id}::${lang}`
 573    if (seen.has(key)) continue
 574    seen.add(key)
 575    const icon = `${iconBase}/${source.id}/${iconDir}/${source.icon}`
 576    const rating: Rating = source.contentRating === 'ADULT'
 577      ? 'nsfw'
 578      : source.contentRating === 'MATURE'
 579      ? 'suggestive'
 580      : 'safe'
 581    sites.push({
 582      name: source.name,
 583      lang,
 584      icon,
 585      url: source.websiteBaseURL ?? '',
 586      rating
 587    })
 588  }
 589  return sites
 590}
 591
 592function normalizeGoogleFaviconUrl(url: string): string {
 593  return url.replace('%size%', '64')
 594}
 595
 596async function toRepoDataCloudstream(
 597  repo: CloudstreamRepo,
 598  fetchJson: FetchJson
 599): Promise<RepoSite[]> {
 600  const seen = new Set<string>()
 601  const sites: RepoSite[] = []
 602  const lists = await mapLimit(
 603    repo.pluginLists,
 604    FETCH_CONCURRENCY,
 605    url => fetchJson(url)
 606  )
 607  for (const list of lists) {
 608    if (!Array.isArray(list)) continue
 609    for (const plugin of list as CloudstreamPlugin[]) {
 610      if (seen.has(plugin.name)) continue
 611      seen.add(plugin.name)
 612      const lang = normalizeLang(plugin.language ?? 'all')
 613      const icon = plugin.iconUrl
 614        ? normalizeGoogleFaviconUrl(plugin.iconUrl)
 615        : ''
 616      sites.push({ name: plugin.name, lang, icon, url: '', rating: 'safe' })
 617    }
 618  }
 619  return sites
 620}
 621
 622function toRepoDataAidokuLegacy(
 623  iconBase: string,
 624  sources: AidokuLegacySource[]
 625): RepoSite[] {
 626  const seen = new Set<string>()
 627  const sites: RepoSite[] = []
 628  for (const source of sources) {
 629    const lang = normalizeLang(source.lang)
 630    addSite(seen, `${source.name}::${lang}`, sites, {
 631      name: source.name,
 632      lang,
 633      icon: `${iconBase}/icons/${source.icon}`,
 634      url: '',
 635      rating: ratingFromLevel(source.nsfw ?? 0)
 636    })
 637  }
 638  return sites
 639}
 640
 641function toRepoDataHayase(extensions: HayaseExtension[]): RepoSite[] {
 642  const seen = new Set<string>()
 643  const sites: RepoSite[] = []
 644  for (const ext of extensions) {
 645    const langs = ext.languages?.length ? ext.languages : ['all']
 646    for (const rawLang of langs) {
 647      const lang = normalizeLang(rawLang)
 648      addSite(seen, `${ext.name}::${lang}`, sites, {
 649        name: ext.name,
 650        lang,
 651        icon: ext.icon ?? '',
 652        url: '',
 653        rating: 'safe'
 654      })
 655    }
 656  }
 657  return sites
 658}
 659
 660function toRepoDataStremio(index: StremioCollection): RepoSite[] {
 661  return (index.addons ?? [])
 662    .filter((addon) => addon.manifestUrl)
 663    .map((addon): RepoSite => ({
 664      name: addon.name ?? addon.manifestUrl,
 665      lang: 'all',
 666      icon: addon.icon ?? '',
 667      url: '',
 668      rating: 'safe',
 669      contentTypes: addon.types?.length
 670        ? [...new Set(addon.types.filter(Boolean))]
 671        : undefined,
 672      installUrl: `stremio://${addon.manifestUrl.replace(/^[a-z]+:\/\//i, '')}`,
 673      copyUrl: addon.manifestUrl
 674    }))
 675}
 676
 677function toRepoDataMangayomi(sources: MangayomiSource[]): RepoSite[] {
 678  const seen = new Set<string>()
 679  const sites: RepoSite[] = []
 680  for (const source of sources) {
 681    const lang = normalizeLang(source.lang)
 682    addSite(seen, `${source.name}::${lang}`, sites, {
 683      name: source.name,
 684      lang,
 685      icon: source.iconUrl ?? '',
 686      url: source.baseUrl,
 687      rating: source.isNsfw ? 'nsfw' : 'safe'
 688    })
 689  }
 690  return sites
 691}
 692
 693function toRepoDataIReader(sources: IReaderSource[]): RepoSite[] {
 694  const seen = new Set<string>()
 695  const sites: RepoSite[] = []
 696  for (const source of sources) {
 697    const lang = normalizeLang(source.lang)
 698    addSite(seen, `${source.name}::${lang}`, sites, {
 699      name: source.name,
 700      lang,
 701      icon: '',
 702      url: '',
 703      rating: source.nsfw ? 'nsfw' : 'safe'
 704    })
 705  }
 706  return sites
 707}
 708
 709function toRepoDataSuwatte(
 710  iconBase: string,
 711  index: SuwatteCatalogIndex
 712): { sites: RepoSite[]; listUrl: string } {
 713  const seen = new Set<string>()
 714  const sites: RepoSite[] = []
 715  const listUrl = index.listUrl ?? iconBase
 716  const isV6 = index.catalogVersion === undefined
 717  for (const source of index.sources ?? []) {
 718    const langs = source.languages?.length ? source.languages : ['all']
 719    const icon = source.thumbnail
 720      ? (/^https?:\/\//i.test(source.thumbnail)
 721        ? source.thumbnail
 722        : `${iconBase}/assets/${source.thumbnail}`)
 723      : ''
 724    const installUrl = source.path
 725      ? (isV6
 726        ? `suwatte://runner?url=${listUrl}&runner=${source.path}`
 727        : `suwatte://AddSourceFromList?list=${listUrl}&source=${source.path}`)
 728      : undefined
 729    for (const rawLang of langs) {
 730      const lang = normalizeLang(rawLang)
 731      addSite(seen, `${source.name}::${lang}`, sites, {
 732        name: source.name,
 733        lang,
 734        icon,
 735        url: source.website ?? '',
 736        rating: 'safe',
 737        installUrl
 738      })
 739    }
 740  }
 741  return { sites, listUrl }
 742}
 743
 744function toRepoDataMana(iconBase: string, index: ManaIndex): RepoSite[] {
 745  const seen = new Set<string>()
 746  const sites: RepoSite[] = []
 747  for (const source of index.sources ?? []) {
 748    if (!source?.name) continue
 749    const langs = source.supportedLanguages?.length
 750      ? source.supportedLanguages
 751      : ['all']
 752    const icon = source.thumbnail
 753      ? (/^https?:\/\//i.test(source.thumbnail)
 754        ? source.thumbnail
 755        : `${iconBase}/assets/${source.thumbnail}`)
 756      : ''
 757    const rating = ratingFromLevel(source.rating ?? 0)
 758    const repoParam = encodeURIComponent(iconBase)
 759    const installUrl = source.id
 760      ? `mana://install-source?repo=${repoParam}&id=${encodeURIComponent(source.id)}`
 761      : undefined
 762    for (const rawLang of langs) {
 763      const lang = normalizeLang(rawLang.split(/[_-]/)[0] ?? rawLang)
 764      addSite(seen, `${source.name}::${lang}`, sites, {
 765        name: source.name,
 766        lang,
 767        icon,
 768        url: source.website ?? '',
 769        rating,
 770        installUrl
 771      })
 772    }
 773  }
 774  return sites
 775}
 776
 777function toRepoDataKotatsu(index: KotatsuIndex): RepoSite[] {
 778  const seen = new Set<string>()
 779  const sites: RepoSite[] = []
 780  for (const site of index.sites) {
 781    const lang = normalizeLang(site.lang ?? 'all')
 782    const contentType = site.contentType ?? ''
 783    const rating: Rating = contentType.includes('HENTAI') ? 'nsfw' : 'safe'
 784    addSite(seen, `${site.name}::${lang}::${site.url}`, sites, {
 785      name: site.name ?? 'Unknown',
 786      lang,
 787      icon: site.icon,
 788      url: site.url ?? '',
 789      rating,
 790      contentType,
 791      isBroken: site.isBroken || undefined
 792    })
 793  }
 794  return sites
 795}
 796
 797function nuvioLangs(scraper: NuvioScraper): string[] {
 798  const raw = scraper.contentLanguage ?? scraper.language ?? []
 799  return [
 800    ...new Set(
 801      raw
 802        .filter(lang => typeof lang === 'string' && lang.trim() !== '')
 803        .map(lang => normalizeLang(lang))
 804    )
 805  ]
 806}
 807
 808function toRepoDataNuvio(manifest: NuvioManifest): RepoSite[] {
 809  const seen = new Set<string>()
 810  const sites: RepoSite[] = []
 811  for (const scraper of manifest.scrapers ?? []) {
 812    if (!scraper?.name || scraper.enabled === false) continue
 813    const languages = nuvioLangs(scraper)
 814    const lang = languages.length === 1 ? languages[0] : 'all'
 815    const types = [
 816      ...new Set(
 817        (scraper.supportedTypes ?? scraper.types ?? []).filter(
 818          (type): type is string => typeof type === 'string' && type !== ''
 819        )
 820      )
 821    ]
 822    const icon = scraper.logo ?? scraper.icon ?? ''
 823    addSite(seen, `${scraper.name}::${lang}::${icon}`, sites, {
 824      name: scraper.name,
 825      lang,
 826      languages: languages.length ? languages : undefined,
 827      icon,
 828      url: '',
 829      rating: 'safe',
 830      contentType: types[0],
 831      contentTypes: types.length ? types : undefined
 832    })
 833  }
 834  return sortSites(sites)
 835}
 836
 837function isNuvioManifest(json: unknown): json is NuvioManifest {
 838  return !!json && typeof json === 'object' && !Array.isArray(json) &&
 839    Array.isArray((json as NuvioManifest).scrapers)
 840}
 841
 842function isEchoExtensionList(json: unknown): json is EchoExtension[] {
 843  if (!Array.isArray(json) || json.length === 0) return false
 844  const first = json[0] as Record<string, unknown>
 845  return typeof first.updateUrl === 'string' &&
 846    typeof first.subtitle === 'string' && !('lang' in first) &&
 847    !('baseUrl' in first)
 848}
 849
 850function parseEchoRepo(
 851  updateUrl: string
 852): {
 853  host: string
 854  owner: string
 855  repo: string
 856  repoUrl: string
 857  ownerUrl: string
 858} | undefined {
 859  const githubMatch = updateUrl.match(
 860    /^https:\/\/api\.github\.com\/repos\/([^/]+)\/([^/]+)\/releases(?:\/|$)/
 861  )
 862  if (githubMatch) {
 863    const [, owner, repo] = githubMatch
 864    return {
 865      host: 'github.com',
 866      owner,
 867      repo,
 868      repoUrl: `https://github.com/${owner}/${repo}`,
 869      ownerUrl: `https://github.com/${owner}`
 870    }
 871  }
 872  const gitlabMatch = updateUrl.match(
 873    /^https:\/\/(gitlab\.com)\/api\/v4\/projects\/([^/]+)\/releases(?:\/|$)/
 874  )
 875  if (gitlabMatch) {
 876    const [, host, encodedPath] = gitlabMatch
 877    const path = decodeURIComponent(encodedPath)
 878    const owner = path.slice(0, path.lastIndexOf('/'))
 879    const repo = path.slice(path.lastIndexOf('/') + 1)
 880    if (!owner || !repo) return undefined
 881    return {
 882      host,
 883      owner,
 884      repo,
 885      repoUrl: `https://${host}/${path}`,
 886      ownerUrl: `https://${host}/${owner}`
 887    }
 888  }
 889  return undefined
 890}
 891
 892function toRepoDataEchoExtensions(extensions: EchoExtension[]): RepoSite[] {
 893  const seen = new Set<string>()
 894  const sites: RepoSite[] = []
 895  for (const ext of extensions) {
 896    if (seen.has(`${ext.id}::${ext.updateUrl}`)) continue
 897    seen.add(`${ext.id}::${ext.updateUrl}`)
 898    const repo = parseEchoRepo(ext.updateUrl)
 899    sites.push({
 900      name: ext.name,
 901      lang: 'all',
 902      icon: ext.iconUrl ?? '',
 903      url: ext.url ?? repo?.repoUrl ?? '',
 904      rating: 'safe',
 905      contentType: ext.type,
 906      installUrl: repo?.repoUrl
 907    })
 908  }
 909  return sortSites(sites)
 910}
 911
 912function loadEchoExtensionList(
 913  indexUrl: string,
 914  extensions: EchoExtension[]
 915): {
 916  sites: RepoSite[]
 917  authorRepos: EchoAuthorRepo[]
 918  sitesByAuthor: Record<string, RepoData>
 919} {
 920  const byAuthor = new Map<
 921    string,
 922    { label: string; ownerUrl?: string; exts: EchoExtension[] }
 923  >()
 924  for (const ext of extensions) {
 925    const repo = parseEchoRepo(ext.updateUrl)
 926    const key = repo ? `${repo.host}:${repo.owner}` : 'Unknown'
 927    const bucket = byAuthor.get(key)
 928    if (bucket) bucket.exts.push(ext)
 929    else {byAuthor.set(key, {
 930        label: repo?.owner ?? 'Unknown',
 931        ownerUrl: repo?.ownerUrl,
 932        exts: [ext]
 933      })}
 934  }
 935  const authorRepos: EchoAuthorRepo[] = []
 936  const sitesByAuthor: Record<string, RepoData> = {}
 937  for (const [key, { label, ownerUrl, exts }] of byAuthor) {
 938    const authorIndexUrl = `${indexUrl}#${key}`
 939    sitesByAuthor[authorIndexUrl] = { sites: toRepoDataEchoExtensions(exts) }
 940    authorRepos.push({ label, repoUrl: ownerUrl, indexUrl: authorIndexUrl })
 941  }
 942  authorRepos.sort((a, b) => a.label.localeCompare(b.label))
 943  return {
 944    sites: toRepoDataEchoExtensions(extensions),
 945    authorRepos,
 946    sitesByAuthor
 947  }
 948}
 949
 950function isSoraRepoIndex(json: unknown): json is SoraRepoIndex {
 951  return !!json && typeof json === 'object' &&
 952    Array.isArray((json as SoraRepoIndex).repos)
 953}
 954
 955function normalizeSoraLang(language: string | undefined): string {
 956  const stripped = (language ?? '').replace(/\s*\([^)]*\)\s*$/, '').trim()
 957  if (stripped.toLowerCase().startsWith('multi')) return 'all'
 958  return normalizeLang(stripped)
 959}
 960
 961function toRepoDataSoraModules(modules: SoraModule[]): RepoSite[] {
 962  const seen = new Set<string>()
 963  const sites: RepoSite[] = []
 964
 965  for (const mod of modules) {
 966    const name = mod.wotaku_sourceName ?? mod.sourceName
 967    const langs = mod.wotaku_language?.length
 968      ? mod.wotaku_language
 969      : [mod.language]
 970    const scriptUrl = mod.scriptUrl ?? mod.scriptURL
 971    const installUrl = scriptUrl?.replace(/\.js$/i, '.json')
 972    for (const rawLang of langs) {
 973      const lang = normalizeSoraLang(rawLang)
 974      const key = `${name}::${lang}::${installUrl ?? ''}`
 975      if (seen.has(key)) continue
 976      seen.add(key)
 977      sites.push({
 978        name,
 979        lang,
 980        icon: mod.iconUrl ?? mod.iconURL ?? '',
 981        url: mod.baseUrl ?? '',
 982        rating: 'safe',
 983        contentType: mod.wotaku_type?.[0],
 984        installUrl: installUrl ? `sora://module?url=${installUrl}` : undefined
 985      })
 986    }
 987  }
 988
 989  return sortSites(sites)
 990}
 991
 992async function loadSoraRepoIndex(
 993  indexUrl: string,
 994  index: SoraRepoIndex,
 995  fetchJson: FetchJson
 996): Promise<{
 997  sites: RepoSite[]
 998  authorRepos: SoraAuthorRepo[]
 999  sitesByAuthor: Record<string, RepoData>
1000}> {
1001  const seen = new Set<string>()
1002  const sites: RepoSite[] = []
1003  const authorRepos: SoraAuthorRepo[] = []
1004  const sitesByAuthor: Record<string, RepoData> = {}
1005
1006  const entries = index.repos.filter(repo => repo.path && !repo.error)
1007  const fileUrls = entries.map(repo => new URL(repo.path!, indexUrl).toString())
1008  const moduleLists = await mapLimit(
1009    fileUrls,
1010    FETCH_CONCURRENCY,
1011    url => fetchJson(url)
1012  )
1013
1014  entries.forEach((repo, i) => {
1015    const modules = moduleLists[i]
1016    const authorSites = Array.isArray(modules)
1017      ? toRepoDataSoraModules(modules as SoraModule[])
1018      : []
1019    const fileUrl = fileUrls[i]
1020    sitesByAuthor[fileUrl] = { sites: authorSites }
1021    authorRepos.push({
1022      label: repo.name,
1023      repoUrl: repo.source?.replace(/\.git$/, ''),
1024      indexUrl: fileUrl
1025    })
1026    for (const site of authorSites) {
1027      const key = `${site.name}::${site.lang}::${site.installUrl ?? ''}`
1028      if (seen.has(key)) continue
1029      seen.add(key)
1030      sites.push(site)
1031    }
1032  })
1033
1034  authorRepos.sort((a, b) => a.label.localeCompare(b.label))
1035  return {
1036    sites: sortSites(sites),
1037    authorRepos,
1038    sitesByAuthor
1039  }
1040}
1041
1042function toRepoDataLNReader(plugins: LNReaderPlugin[]): RepoSite[] {
1043  const seen = new Set<string>()
1044  const sites: RepoSite[] = []
1045  for (const plugin of plugins) {
1046    const lang = normalizeLang(plugin.lang)
1047    addSite(seen, `${plugin.name}::${lang}`, sites, {
1048      name: plugin.name,
1049      lang,
1050      icon: plugin.iconUrl ?? '',
1051      url: plugin.url,
1052      rating: 'safe'
1053    })
1054  }
1055  return sites
1056}
1057
1058const CONTENT_WARNING_RATING: Record<string, Rating> = {
1059  CONTENT_WARNING_NSFW: 'nsfw',
1060  CONTENT_WARNING_MIXED: 'mixed',
1061  CONTENT_WARNING_SAFE: 'safe'
1062}
1063
1064function toRepoDataMihonNew(index: MihonIndex): RepoSite[] {
1065  const seen = new Set<string>()
1066  const sites: RepoSite[] = []
1067  for (const ext of index.extensionList.extensions) {
1068    const icon = ext.resources.iconUrl
1069    const rating = CONTENT_WARNING_RATING[ext.contentWarning] ?? 'safe'
1070    for (const source of ext.sources) {
1071      addSite(
1072        seen,
1073        `${source.name}::${source.language}::${source.homeUrl}`,
1074        sites,
1075        {
1076          name: source.name ?? 'Unknown',
1077          lang: source.language ?? 'all',
1078          icon,
1079          url: source.homeUrl ?? '',
1080          rating
1081        }
1082      )
1083    }
1084  }
1085  return sortSites(sites)
1086}
1087
1088function toRepoDataSeanime(entries: SeanimeMarketplaceEntry[]): RepoSite[] {
1089  const seen = new Set<string>()
1090  const sites: RepoSite[] = []
1091  for (const ext of entries) {
1092    if (!ext?.name || !ext?.manifestURI) continue
1093    if (seen.has(ext.manifestURI)) continue
1094    seen.add(ext.manifestURI)
1095    const author = ext.author?.trim()
1096    sites.push({
1097      name: ext.name,
1098      lang: normalizeLang(ext.lang ?? 'all'),
1099      icon: ext.icon ?? '',
1100      url: ext.website ?? '',
1101      rating: 'safe',
1102      contentType: ext.type ?? '',
1103      isBroken: ext.brokenTag || ext.deprecatedTag ? true : undefined,
1104      author: author || undefined,
1105      copyUrl: ext.manifestURI
1106    })
1107  }
1108  return sortSites(sites)
1109}
1110
1111function isSeanimeMarketplaceList(
1112  json: unknown
1113): json is SeanimeMarketplaceEntry[] {
1114  if (!Array.isArray(json) || json.length === 0) return false
1115  const first = json[0]
1116  return Boolean(
1117    first && typeof first === 'object' &&
1118      typeof (first as Record<string, unknown>).manifestURI === 'string'
1119  )
1120}
1121
1122async function toRepoData(
1123  indexUrl: string,
1124  json: unknown,
1125  fetchJson: FetchJson
1126): Promise<RepoData> {
1127  const iconBase = indexUrl.slice(0, indexUrl.lastIndexOf('/'))
1128  let sites: RepoSite[]
1129  let suwatteV6: boolean | undefined
1130  let suwatteListUrl: string | undefined
1131
1132  if (
1133    json && typeof json === 'object' &&
1134    Array.isArray((json as StremioCollection).addons)
1135  ) {
1136    return { sites: toRepoDataStremio(json as StremioCollection) }
1137  }
1138
1139  if (
1140    json && typeof json === 'object' && !Array.isArray(json) &&
1141    'extensionList' in (json as Record<string, unknown>)
1142  ) {
1143    return { sites: toRepoDataMihonNew(json as MihonIndex) }
1144  }
1145
1146  if (Array.isArray(json)) {
1147    const first = json[0] as Record<string, unknown> | undefined
1148    if (isSeanimeMarketplaceList(json)) {
1149      sites = toRepoDataSeanime(json)
1150    } else if (first && 'manifestVersion' in first) {
1151      sites = toRepoDataHayase(json as HayaseExtension[])
1152    } else if (first && 'iconUrl' in first && 'site' in first) {
1153      sites = toRepoDataLNReader(json as LNReaderPlugin[])
1154    } else if (first && 'sources' in first) {
1155      sites = toRepoDataMihon(iconBase, json as MihonExtension[])
1156    } else if (first && 'pkg' in first && 'apk' in first) {
1157      sites = toRepoDataIReader(json as IReaderSource[])
1158    } else if (first && 'iconUrl' in first && 'baseUrl' in first) {
1159      sites = toRepoDataMangayomi(json as MangayomiSource[])
1160    } else {
1161      sites = toRepoDataAidokuLegacy(iconBase, json as AidokuLegacySource[])
1162    }
1163  } else if (Array.isArray((json as CloudstreamRepo).pluginLists)) {
1164    sites = await toRepoDataCloudstream(json as CloudstreamRepo, fetchJson)
1165  } else if (
1166    (json as AidokuIndex).sources?.length &&
1167    'iconURL' in (json as AidokuIndex).sources[0]
1168  ) {
1169    sites = toRepoDataAidoku(iconBase, json as AidokuIndex)
1170  } else if (
1171    (json as ManaIndex).sources?.length &&
1172    ('supportedLanguages' in (json as ManaIndex).sources[0] ||
1173      'environment' in (json as ManaIndex).sources[0])
1174  ) {
1175    sites = toRepoDataMana(iconBase, json as ManaIndex)
1176  } else if (
1177    (json as SuwatteCatalogIndex).sources?.length &&
1178    'thumbnail' in (json as SuwatteCatalogIndex).sources[0]
1179  ) {
1180    const result = toRepoDataSuwatte(iconBase, json as SuwatteCatalogIndex)
1181    sites = result.sites
1182    suwatteListUrl = result.listUrl
1183    suwatteV6 = (json as SuwatteCatalogIndex).catalogVersion === undefined
1184  } else if (Array.isArray((json as KotatsuIndex).sites)) {
1185    sites = toRepoDataKotatsu(json as KotatsuIndex)
1186  } else if (isNuvioManifest(json)) {
1187    sites = toRepoDataNuvio(json)
1188  } else {
1189    sites = toRepoDataPaperback(iconBase, json as PaperbackIndex)
1190  }
1191  return { sites: sortSites(sites), suwatteV6, suwatteListUrl }
1192}
1193
1194export interface ExtensionRepoData {
1195  sites: Record<string, RepoData>
1196  soraAuthors: Record<string, SoraAuthorRepo[]>
1197  echoAuthors: Record<string, EchoAuthorRepo[]>
1198  repoLists: Record<string, RepoListEntry[]>
1199}
1200
1201export async function assembleSchemeData(
1202  indexUrls: string[],
1203  listUrls: string[],
1204  fetchJson: FetchJson
1205): Promise<ExtensionRepoData> {
1206  const listUrlSet = new Set(listUrls)
1207  const sites: Record<string, RepoData> = {}
1208  const soraAuthors: Record<string, SoraAuthorRepo[]> = {}
1209  const echoAuthors: Record<string, EchoAuthorRepo[]> = {}
1210  const repoLists: Record<string, RepoListEntry[]> = {}
1211  const pendingByAuthor: Record<string, RepoData> = {}
1212
1213  const listJsons = await mapLimit(
1214    listUrls,
1215    FETCH_CONCURRENCY,
1216    url => fetchJson(url)
1217  )
1218  const listIndexGroups: {
1219    indexUrls: string[]
1220    repoJsons: unknown[]
1221    failed: boolean
1222  }[] = await Promise.all(listJsons.map(async (json) => {
1223    if (json === undefined) {
1224      return { indexUrls: [], repoJsons: [], failed: true }
1225    }
1226    if (!isCloudstreamRepoList(json)) {
1227      return { indexUrls: [], repoJsons: [], failed: false }
1228    }
1229    const indexUrls = [
1230      ...new Set(
1231        json.map(item => typeof item === 'string' ? item : item.url)
1232      )
1233    ]
1234    const repoJsons = await mapLimit(
1235      indexUrls,
1236      FETCH_CONCURRENCY,
1237      url => fetchJson(url)
1238    )
1239    return { indexUrls, repoJsons, failed: false }
1240  }))
1241  listUrls.forEach((listUrl, li) => {
1242    const { indexUrls, repoJsons, failed } = listIndexGroups[li]
1243    if (failed) return
1244    if (indexUrls.length === 0) {
1245      repoLists[listUrl] = []
1246      return
1247    }
1248    const entries: RepoListEntry[] = indexUrls.map((indexUrl, i) => ({
1249      label: repoListLabel(indexUrl, repoJsons[i]),
1250      indexUrl,
1251      repoUrl: inferRepoUrl(indexUrl)
1252    }))
1253    entries.sort((a, b) => a.label.localeCompare(b.label))
1254    repoLists[listUrl] = entries
1255  })
1256  const listRepoPairs = listIndexGroups.filter(g => !g.failed).flatMap(g =>
1257    g.indexUrls.map((url, i) => ({ url, json: g.repoJsons[i] })).filter(p =>
1258      p.json !== undefined
1259    )
1260  )
1261  const listRepoResults = await mapLimit(
1262    listRepoPairs,
1263    FETCH_CONCURRENCY,
1264    async ({ url, json }) => ({
1265      url,
1266      data: await toRepoData(url, json, fetchJson)
1267    })
1268  )
1269  for (const { url, data } of listRepoResults) {
1270    if (!(url in sites)) sites[url] = data
1271  }
1272
1273  const remaining = indexUrls.filter(url =>
1274    !listUrlSet.has(url) && !(url in sites)
1275  )
1276  const jsons = await mapLimit(
1277    remaining,
1278    FETCH_CONCURRENCY,
1279    url => fetchJson(url)
1280  )
1281  for (let i = 0; i < remaining.length; i++) {
1282    const url = remaining[i]
1283    const json = jsons[i]
1284    if (json === undefined) continue
1285    if (isSoraRepoIndex(json)) {
1286      const result = await loadSoraRepoIndex(url, json, fetchJson)
1287      sites[url] = { sites: result.sites }
1288      soraAuthors[url] = result.authorRepos
1289      Object.assign(pendingByAuthor, result.sitesByAuthor)
1290      continue
1291    }
1292    if (isEchoExtensionList(json)) {
1293      const result = loadEchoExtensionList(url, json)
1294      sites[url] = { sites: result.sites }
1295      echoAuthors[url] = result.authorRepos
1296      Object.assign(pendingByAuthor, result.sitesByAuthor)
1297      continue
1298    }
1299    sites[url] = await toRepoData(url, json, fetchJson)
1300  }
1301  Object.assign(sites, pendingByAuthor)
1302  return { sites, soraAuthors, echoAuthors, repoLists }
1303}