react-native-consumet 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/lib/commonjs/extension-registry.json.sig +1 -1
  2. package/lib/commonjs/index.js +18 -0
  3. package/lib/commonjs/index.js.map +1 -1
  4. package/lib/commonjs/models/types.js +6 -0
  5. package/lib/commonjs/models/types.js.map +1 -1
  6. package/lib/commonjs/providers/manga/asurascans.js +160 -96
  7. package/lib/commonjs/providers/manga/asurascans.js.map +1 -1
  8. package/lib/commonjs/providers/manga/flamescans.js +173 -91
  9. package/lib/commonjs/providers/manga/flamescans.js.map +1 -1
  10. package/lib/commonjs/providers/manga/index.js +1 -15
  11. package/lib/commonjs/providers/manga/index.js.map +1 -1
  12. package/lib/commonjs/providers/manga/mangadex.js +234 -227
  13. package/lib/commonjs/providers/manga/mangadex.js.map +1 -1
  14. package/lib/commonjs/providers/manga/mangahere.js +279 -135
  15. package/lib/commonjs/providers/manga/mangahere.js.map +1 -1
  16. package/lib/commonjs/providers/manga/mangakakalot.js +206 -107
  17. package/lib/commonjs/providers/manga/mangakakalot.js.map +1 -1
  18. package/lib/commonjs/providers/manga/mangapill.js +126 -38
  19. package/lib/commonjs/providers/manga/mangapill.js.map +1 -1
  20. package/lib/commonjs/providers/meta/anilist.js +41 -12
  21. package/lib/commonjs/providers/meta/anilist.js.map +1 -1
  22. package/lib/commonjs/utils/index.js +19 -0
  23. package/lib/commonjs/utils/index.js.map +1 -1
  24. package/lib/commonjs/utils/manga.js +60 -0
  25. package/lib/commonjs/utils/manga.js.map +1 -0
  26. package/lib/module/extension-registry.json.sig +1 -1
  27. package/lib/module/index.js +2 -2
  28. package/lib/module/index.js.map +1 -1
  29. package/lib/module/models/types.js +9 -0
  30. package/lib/module/models/types.js.map +1 -1
  31. package/lib/module/providers/manga/asurascans.js +161 -96
  32. package/lib/module/providers/manga/asurascans.js.map +1 -1
  33. package/lib/module/providers/manga/flamescans.js +174 -91
  34. package/lib/module/providers/manga/flamescans.js.map +1 -1
  35. package/lib/module/providers/manga/index.js +1 -15
  36. package/lib/module/providers/manga/index.js.map +1 -1
  37. package/lib/module/providers/manga/mangadex.js +236 -228
  38. package/lib/module/providers/manga/mangadex.js.map +1 -1
  39. package/lib/module/providers/manga/mangahere.js +276 -132
  40. package/lib/module/providers/manga/mangahere.js.map +1 -1
  41. package/lib/module/providers/manga/mangakakalot.js +207 -107
  42. package/lib/module/providers/manga/mangakakalot.js.map +1 -1
  43. package/lib/module/providers/manga/mangapill.js +128 -39
  44. package/lib/module/providers/manga/mangapill.js.map +1 -1
  45. package/lib/module/providers/meta/anilist.js +41 -12
  46. package/lib/module/providers/meta/anilist.js.map +1 -1
  47. package/lib/module/utils/index.js +1 -0
  48. package/lib/module/utils/index.js.map +1 -1
  49. package/lib/module/utils/manga.js +54 -0
  50. package/lib/module/utils/manga.js.map +1 -0
  51. package/lib/typescript/commonjs/src/index.d.ts +2 -2
  52. package/lib/typescript/commonjs/src/index.d.ts.map +1 -1
  53. package/lib/typescript/commonjs/src/models/types.d.ts +38 -5
  54. package/lib/typescript/commonjs/src/models/types.d.ts.map +1 -1
  55. package/lib/typescript/commonjs/src/providers/manga/asurascans.d.ts +14 -4
  56. package/lib/typescript/commonjs/src/providers/manga/asurascans.d.ts.map +1 -1
  57. package/lib/typescript/commonjs/src/providers/manga/flamescans.d.ts +18 -3
  58. package/lib/typescript/commonjs/src/providers/manga/flamescans.d.ts.map +1 -1
  59. package/lib/typescript/commonjs/src/providers/manga/index.d.ts +0 -14
  60. package/lib/typescript/commonjs/src/providers/manga/index.d.ts.map +1 -1
  61. package/lib/typescript/commonjs/src/providers/manga/mangadex.d.ts +22 -5
  62. package/lib/typescript/commonjs/src/providers/manga/mangadex.d.ts.map +1 -1
  63. package/lib/typescript/commonjs/src/providers/manga/mangahere.d.ts +15 -3
  64. package/lib/typescript/commonjs/src/providers/manga/mangahere.d.ts.map +1 -1
  65. package/lib/typescript/commonjs/src/providers/manga/mangakakalot.d.ts +26 -4
  66. package/lib/typescript/commonjs/src/providers/manga/mangakakalot.d.ts.map +1 -1
  67. package/lib/typescript/commonjs/src/providers/manga/mangapill.d.ts +16 -2
  68. package/lib/typescript/commonjs/src/providers/manga/mangapill.d.ts.map +1 -1
  69. package/lib/typescript/commonjs/src/providers/meta/anilist.d.ts.map +1 -1
  70. package/lib/typescript/commonjs/src/utils/index.d.ts +1 -0
  71. package/lib/typescript/commonjs/src/utils/index.d.ts.map +1 -1
  72. package/lib/typescript/commonjs/src/utils/manga.d.ts +19 -0
  73. package/lib/typescript/commonjs/src/utils/manga.d.ts.map +1 -0
  74. package/lib/typescript/module/src/index.d.ts +2 -2
  75. package/lib/typescript/module/src/index.d.ts.map +1 -1
  76. package/lib/typescript/module/src/models/types.d.ts +38 -5
  77. package/lib/typescript/module/src/models/types.d.ts.map +1 -1
  78. package/lib/typescript/module/src/providers/manga/asurascans.d.ts +14 -4
  79. package/lib/typescript/module/src/providers/manga/asurascans.d.ts.map +1 -1
  80. package/lib/typescript/module/src/providers/manga/flamescans.d.ts +18 -3
  81. package/lib/typescript/module/src/providers/manga/flamescans.d.ts.map +1 -1
  82. package/lib/typescript/module/src/providers/manga/index.d.ts +0 -14
  83. package/lib/typescript/module/src/providers/manga/index.d.ts.map +1 -1
  84. package/lib/typescript/module/src/providers/manga/mangadex.d.ts +22 -5
  85. package/lib/typescript/module/src/providers/manga/mangadex.d.ts.map +1 -1
  86. package/lib/typescript/module/src/providers/manga/mangahere.d.ts +15 -3
  87. package/lib/typescript/module/src/providers/manga/mangahere.d.ts.map +1 -1
  88. package/lib/typescript/module/src/providers/manga/mangakakalot.d.ts +26 -4
  89. package/lib/typescript/module/src/providers/manga/mangakakalot.d.ts.map +1 -1
  90. package/lib/typescript/module/src/providers/manga/mangapill.d.ts +16 -2
  91. package/lib/typescript/module/src/providers/manga/mangapill.d.ts.map +1 -1
  92. package/lib/typescript/module/src/providers/meta/anilist.d.ts.map +1 -1
  93. package/lib/typescript/module/src/utils/index.d.ts +1 -0
  94. package/lib/typescript/module/src/utils/index.d.ts.map +1 -1
  95. package/lib/typescript/module/src/utils/manga.d.ts +19 -0
  96. package/lib/typescript/module/src/utils/manga.d.ts.map +1 -0
  97. package/package.json +1 -1
  98. package/src/extension-registry.json.sig +1 -1
  99. package/src/index.tsx +6 -0
  100. package/src/models/types.ts +38 -3
  101. package/src/providers/manga/asurascans.ts +200 -135
  102. package/src/providers/manga/flamescans.ts +221 -118
  103. package/src/providers/manga/index.ts +0 -14
  104. package/src/providers/manga/mangadex.ts +335 -282
  105. package/src/providers/manga/mangahere.ts +309 -156
  106. package/src/providers/manga/mangakakalot.ts +249 -152
  107. package/src/providers/manga/mangapill.ts +163 -64
  108. package/src/providers/meta/anilist.ts +50 -14
  109. package/src/utils/index.ts +1 -0
  110. package/src/utils/manga.ts +58 -0
  111. package/lib/commonjs/providers/manga/brmangas.js +0 -110
  112. package/lib/commonjs/providers/manga/brmangas.js.map +0 -1
  113. package/lib/commonjs/providers/manga/comick.js +0 -154
  114. package/lib/commonjs/providers/manga/comick.js.map +0 -1
  115. package/lib/commonjs/providers/manga/mangahost.js +0 -113
  116. package/lib/commonjs/providers/manga/mangahost.js.map +0 -1
  117. package/lib/commonjs/providers/manga/mangapark.js +0 -97
  118. package/lib/commonjs/providers/manga/mangapark.js.map +0 -1
  119. package/lib/commonjs/providers/manga/mangareader.js +0 -106
  120. package/lib/commonjs/providers/manga/mangareader.js.map +0 -1
  121. package/lib/commonjs/providers/manga/mangasee123.js +0 -161
  122. package/lib/commonjs/providers/manga/mangasee123.js.map +0 -1
  123. package/lib/commonjs/providers/manga/readmanga.js +0 -269
  124. package/lib/commonjs/providers/manga/readmanga.js.map +0 -1
  125. package/lib/commonjs/providers/manga/vyvymanga.js +0 -166
  126. package/lib/commonjs/providers/manga/vyvymanga.js.map +0 -1
  127. package/lib/module/providers/manga/brmangas.js +0 -105
  128. package/lib/module/providers/manga/brmangas.js.map +0 -1
  129. package/lib/module/providers/manga/comick.js +0 -149
  130. package/lib/module/providers/manga/comick.js.map +0 -1
  131. package/lib/module/providers/manga/mangahost.js +0 -108
  132. package/lib/module/providers/manga/mangahost.js.map +0 -1
  133. package/lib/module/providers/manga/mangapark.js +0 -92
  134. package/lib/module/providers/manga/mangapark.js.map +0 -1
  135. package/lib/module/providers/manga/mangareader.js +0 -101
  136. package/lib/module/providers/manga/mangareader.js.map +0 -1
  137. package/lib/module/providers/manga/mangasee123.js +0 -156
  138. package/lib/module/providers/manga/mangasee123.js.map +0 -1
  139. package/lib/module/providers/manga/readmanga.js +0 -264
  140. package/lib/module/providers/manga/readmanga.js.map +0 -1
  141. package/lib/module/providers/manga/vyvymanga.js +0 -161
  142. package/lib/module/providers/manga/vyvymanga.js.map +0 -1
  143. package/lib/typescript/commonjs/src/providers/manga/brmangas.d.ts +0 -18
  144. package/lib/typescript/commonjs/src/providers/manga/brmangas.d.ts.map +0 -1
  145. package/lib/typescript/commonjs/src/providers/manga/comick.d.ts +0 -39
  146. package/lib/typescript/commonjs/src/providers/manga/comick.d.ts.map +0 -1
  147. package/lib/typescript/commonjs/src/providers/manga/mangahost.d.ts +0 -18
  148. package/lib/typescript/commonjs/src/providers/manga/mangahost.d.ts.map +0 -1
  149. package/lib/typescript/commonjs/src/providers/manga/mangapark.d.ts +0 -14
  150. package/lib/typescript/commonjs/src/providers/manga/mangapark.d.ts.map +0 -1
  151. package/lib/typescript/commonjs/src/providers/manga/mangareader.d.ts +0 -18
  152. package/lib/typescript/commonjs/src/providers/manga/mangareader.d.ts.map +0 -1
  153. package/lib/typescript/commonjs/src/providers/manga/mangasee123.d.ts +0 -17
  154. package/lib/typescript/commonjs/src/providers/manga/mangasee123.d.ts.map +0 -1
  155. package/lib/typescript/commonjs/src/providers/manga/readmanga.d.ts +0 -31
  156. package/lib/typescript/commonjs/src/providers/manga/readmanga.d.ts.map +0 -1
  157. package/lib/typescript/commonjs/src/providers/manga/vyvymanga.d.ts +0 -17
  158. package/lib/typescript/commonjs/src/providers/manga/vyvymanga.d.ts.map +0 -1
  159. package/lib/typescript/module/src/providers/manga/brmangas.d.ts +0 -18
  160. package/lib/typescript/module/src/providers/manga/brmangas.d.ts.map +0 -1
  161. package/lib/typescript/module/src/providers/manga/comick.d.ts +0 -39
  162. package/lib/typescript/module/src/providers/manga/comick.d.ts.map +0 -1
  163. package/lib/typescript/module/src/providers/manga/mangahost.d.ts +0 -18
  164. package/lib/typescript/module/src/providers/manga/mangahost.d.ts.map +0 -1
  165. package/lib/typescript/module/src/providers/manga/mangapark.d.ts +0 -14
  166. package/lib/typescript/module/src/providers/manga/mangapark.d.ts.map +0 -1
  167. package/lib/typescript/module/src/providers/manga/mangareader.d.ts +0 -18
  168. package/lib/typescript/module/src/providers/manga/mangareader.d.ts.map +0 -1
  169. package/lib/typescript/module/src/providers/manga/mangasee123.d.ts +0 -17
  170. package/lib/typescript/module/src/providers/manga/mangasee123.d.ts.map +0 -1
  171. package/lib/typescript/module/src/providers/manga/readmanga.d.ts +0 -31
  172. package/lib/typescript/module/src/providers/manga/readmanga.d.ts.map +0 -1
  173. package/lib/typescript/module/src/providers/manga/vyvymanga.d.ts +0 -17
  174. package/lib/typescript/module/src/providers/manga/vyvymanga.d.ts.map +0 -1
  175. package/src/providers/manga/brmangas.ts +0 -148
  176. package/src/providers/manga/comick.ts +0 -285
  177. package/src/providers/manga/mangahost.ts +0 -134
  178. package/src/providers/manga/mangapark.ts +0 -115
  179. package/src/providers/manga/mangareader.ts +0 -132
  180. package/src/providers/manga/mangasee123.ts +0 -187
  181. package/src/providers/manga/readmanga.ts +0 -380
  182. package/src/providers/manga/vyvymanga.ts +0 -237
@@ -1,7 +1,7 @@
1
- import { encode } from 'ascii-url-encoder';
2
- import type { AxiosError, AxiosResponse } from 'axios';
1
+ import type { AxiosError } from 'axios';
3
2
 
4
3
  import {
4
+ type IMangaChapter,
5
5
  type IMangaChapterPage,
6
6
  type IMangaInfo,
7
7
  type IMangaResult,
@@ -11,7 +11,121 @@ import {
11
11
  type ProviderContext,
12
12
  } from '../../models';
13
13
  import { createProviderContext } from '../../utils/create-provider-context';
14
- import { capitalizeFirstLetter, substringBefore } from '../../utils';
14
+ import { parseChapterNumber, sortChaptersForReading } from '../../utils/manga';
15
+
16
+ /** Text in several languages, keyed by language code (`en`, `ja-ro`, `pt-br`, ...). */
17
+ type Localized = Record<string, string | null | undefined>;
18
+
19
+ interface Relationship {
20
+ id: string;
21
+ type: string;
22
+ attributes?: Record<string, any>;
23
+ }
24
+
25
+ interface MangaEntity {
26
+ id: string;
27
+ attributes: {
28
+ title?: Localized;
29
+ altTitles?: Localized[];
30
+ description?: Localized;
31
+ status?: string | null;
32
+ year?: number | null;
33
+ contentRating?: string;
34
+ lastVolume?: string | null;
35
+ lastChapter?: string | null;
36
+ chapterNumbersResetOnNewVolume?: boolean;
37
+ links?: Record<string, string> | null;
38
+ tags?: { attributes: { group: string; name: Localized } }[];
39
+ };
40
+ relationships?: Relationship[];
41
+ }
42
+
43
+ interface ChapterEntity {
44
+ id: string;
45
+ attributes: {
46
+ volume?: string | null;
47
+ chapter?: string | null;
48
+ title?: string | null;
49
+ translatedLanguage?: string;
50
+ pages?: number;
51
+ publishAt?: string;
52
+ readableAt?: string;
53
+ };
54
+ relationships?: Relationship[];
55
+ }
56
+
57
+ const STATUSES: Record<string, MediaStatus> = {
58
+ ongoing: MediaStatus.ONGOING,
59
+ completed: MediaStatus.COMPLETED,
60
+ hiatus: MediaStatus.HIATUS,
61
+ cancelled: MediaStatus.CANCELLED,
62
+ };
63
+
64
+ /** Chapters per feed request (the API's maximum). */
65
+ const FEED_PAGE_SIZE = 500;
66
+ /** MangaDex refuses list requests whose offset + limit is past this. */
67
+ const MAX_RESULT_WINDOW = 10000;
68
+ /** The feed only lists chapters of titles with these ratings; an id the caller already has is any of them. */
69
+ const ALL_CONTENT_RATINGS = ['safe', 'suggestive', 'erotica', 'pornographic'];
70
+
71
+ /** A query string from `[key, value]` pairs; keys such as `includes[]` are sent as they are. */
72
+ const queryString = (params: [string, string | number][]) =>
73
+ params.map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`).join('&');
74
+
75
+ /** A number from MangaDex's numeric strings (`"12"`, `"10.5"`); undefined for empty or other text. */
76
+ const toNumber = (text: string | null | undefined): number | undefined => {
77
+ if (typeof text !== 'string' || text.trim() === '') return undefined;
78
+ const value = Number(text.trim());
79
+ return Number.isFinite(value) ? value : undefined;
80
+ };
81
+
82
+ /** The non-empty texts of a localized map, as `[language, text]` pairs. */
83
+ const entries = (map: Localized | null | undefined): [string, string][] =>
84
+ Object.entries(map ?? {}).flatMap(([lang, text]) =>
85
+ typeof text === 'string' && text.trim() ? [[lang, text.trim()] as [string, string]] : []
86
+ );
87
+
88
+ /**
89
+ * The display title (English: the main title when it is English, else the first English alt title;
90
+ * otherwise the main title) and every other title, without repeats.
91
+ */
92
+ const pickTitles = (main: Localized | undefined, alts: Localized[] | undefined) => {
93
+ const mainTitles = entries(main);
94
+ const altTitleList = (alts ?? []).flatMap((alt) => entries(alt));
95
+ const chosen =
96
+ mainTitles.find(([lang]) => lang === 'en') ??
97
+ altTitleList.find(([lang]) => lang === 'en') ??
98
+ mainTitles[0] ??
99
+ altTitleList[0];
100
+ const title = chosen ? chosen[1] : '';
101
+ const altTitles: string[] = [];
102
+ for (const [, text] of [...mainTitles, ...altTitleList]) {
103
+ if (text !== title && !altTitles.includes(text)) altTitles.push(text);
104
+ }
105
+ return { title, altTitles };
106
+ };
107
+
108
+ /** MangaDex descriptions are Markdown; this keeps the text and drops the markup. */
109
+ const markdownToText = (markdown: string): string =>
110
+ markdown
111
+ .replace(/\r\n?/g, '\n')
112
+ .replace(/\u00a0/g, ' ')
113
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') // images
114
+ .replace(/\[([^\]]+)\]\(([^()]|\([^)]*\))*\)/g, '$1') // links: keep the text
115
+ .replace(/\[\/?(?:b|i|u|s|spoiler|url)(?:=[^\]]*)?\]/gi, '') // BBCode tags
116
+ .replace(/<\/?[a-z][^>]*>/gi, '') // HTML tags
117
+ .replace(/^ {0,3}([-*_])(?: *\1){2,} *$/gm, '') // horizontal rules
118
+ .replace(/^ {0,3}#{1,6} +/gm, '') // headings
119
+ .replace(/^ {0,3}> ?/gm, '') // block quotes
120
+ .replace(/^( *)[*+] +/gm, '$1- ') // list bullets
121
+ .replace(/(\*\*|__)(?=\S)([^\n]*?\S)\1/g, '$2') // bold
122
+ .replace(/(^|[^\w*])\*(?=\S)([^*\n]*?\S)\*(?!\w)/g, '$1$2') // *italic*
123
+ .replace(/(^|[^\w])_(?=\S)([^_\n]*?\S)_(?!\w)/g, '$1$2') // _italic_
124
+ .replace(/~~([^\n]+?)~~/g, '$1') // strikethrough
125
+ .replace(/\\([\\`*_{}[\]()#+\-.!>~|])/g, '$1') // escaped characters
126
+ .replace(/[ \t]+$/gm, '') // trailing spaces (Markdown line breaks)
127
+ .replace(/\n{3,}/g, '\n\n')
128
+ .trim();
15
129
 
16
130
  export class MangaDex extends MangaParser {
17
131
  override readonly name = 'MangaDex';
@@ -20,73 +134,78 @@ export class MangaDex extends MangaParser {
20
134
  protected override classPath = 'MANGA.MangaDex';
21
135
 
22
136
  private readonly apiUrl = 'https://api.mangadex.org';
137
+ private readonly uploadsUrl = 'https://uploads.mangadex.org';
23
138
 
24
139
  /** @param ctx provider context; requests go through its axios (default: `createProviderContext()`) */
25
140
  constructor(private readonly ctx: ProviderContext = createProviderContext()) {
26
141
  super();
27
142
  }
28
143
 
29
- override fetchMangaInfo = async (mangaId: string): Promise<IMangaInfo> => {
144
+ /**
145
+ * @param mangaId manga id (a UUID, from a search result)
146
+ * @param lang language of the chapters to list, as MangaDex codes it (default: `en`; e.g. `pt-br`, `es-la`)
147
+ */
148
+ override fetchMangaInfo = async (mangaId: string, lang: string = 'en'): Promise<IMangaInfo> => {
30
149
  try {
31
- const { data } = await this.ctx.axios.get(`${this.apiUrl}/manga/${mangaId}`);
32
- const mangaInfo: IMangaInfo = {
33
- id: data.data.id,
34
- title: data.data.attributes.title.en,
35
- altTitles: data.data.attributes.altTitles,
36
- description: data.data.attributes.description,
37
- genres: data.data.attributes.tags
38
- .filter((tag: any) => tag.attributes.group === 'genre')
39
- .map((tag: any) => tag.attributes.name.en),
40
- themes: data.data.attributes.tags
41
- .filter((tag: any) => tag.attributes.group === 'theme')
42
- .map((tag: any) => tag.attributes.name.en),
43
- status: capitalizeFirstLetter(data.data.attributes.status) as MediaStatus,
44
- releaseDate: data.data.attributes.year,
45
- chapters: [],
46
- };
47
-
48
- const allChapters = await this.fetchAllChapters(mangaId, 0);
49
- for (const chapter of allChapters) {
50
- mangaInfo.chapters?.push({
51
- id: chapter.id,
52
- title: chapter.attributes.title ? chapter.attributes.title : chapter.attributes.chapter,
53
- chapterNumber: chapter.attributes.chapter,
54
- volumeNumber: chapter.attributes.volume,
55
- pages: chapter.attributes.pages,
56
- });
57
- }
58
-
59
- const findCoverArt = data.data.relationships.find((rel: any) => rel.type === 'cover_art');
60
- const coverArt = await this.fetchCoverImage(findCoverArt?.id);
61
- mangaInfo.image = `${this.baseUrl}/covers/${mangaInfo.id}/${coverArt}`;
62
-
63
- return mangaInfo;
150
+ const [{ data }, chapters] = await Promise.all([
151
+ this.ctx.axios.get(
152
+ `${this.apiUrl}/manga/${encodeURIComponent(mangaId)}?${queryString([
153
+ ['includes[]', 'cover_art'],
154
+ ['includes[]', 'author'],
155
+ ['includes[]', 'artist'],
156
+ ])}`
157
+ ),
158
+ this.fetchChapters(mangaId, lang),
159
+ ]);
160
+ const manga: MangaEntity = data.data;
161
+ const { attributes } = manga;
162
+
163
+ const info: IMangaInfo = this.toResult(manga, false);
164
+ const authors = this.relatedNames(manga, 'author');
165
+ if (authors.length > 0) info.authors = authors;
166
+ const artists = this.relatedNames(manga, 'artist');
167
+ if (artists.length > 0) info.artists = artists;
168
+ const genres = this.tagNames(manga, 'genre');
169
+ if (genres.length > 0) info.genres = genres;
170
+ const themes = this.tagNames(manga, 'theme');
171
+ if (themes.length > 0) info.themes = themes;
172
+ const malId = attributes.links?.mal;
173
+ if (malId) info.malId = toNumber(malId) ?? malId;
174
+ // Titles whose chapter numbers restart each volume can't be sorted by chapter number alone;
175
+ // the feed's own order (volume, then chapter) is the reading order then.
176
+ info.chapters = attributes.chapterNumbersResetOnNewVolume ? chapters : sortChaptersForReading(chapters);
177
+
178
+ return info;
64
179
  } catch (err) {
65
- if ((err as AxiosError).code === 'ERR_BAD_REQUEST')
66
- throw new Error(`[${this.name}] Bad request. Make sure you have entered a valid query.`);
67
-
68
- throw new Error((err as Error).message);
180
+ throw this.error(err);
69
181
  }
70
182
  };
71
183
 
72
184
  /**
73
- * @currently only supports english
185
+ * The chapter's pages, from the MangaDex@Home server MangaDex assigns to it.
186
+ * @param chapterId chapter id (from `fetchMangaInfo`)
187
+ * @param dataSaver smaller, compressed images (default: `false`)
74
188
  */
75
- override fetchChapterPages = async (chapterId: string): Promise<IMangaChapterPage[]> => {
189
+ override fetchChapterPages = async (chapterId: string, dataSaver: boolean = false): Promise<IMangaChapterPage[]> => {
190
+ let server: { baseUrl: string; chapter: { hash: string; data?: string[]; dataSaver?: string[] } };
76
191
  try {
77
- const res = await this.ctx.axios.get(`${this.apiUrl}/at-home/server/${chapterId}`);
78
- const pages: { img: string; page: number }[] = [];
79
-
80
- for (const id of res.data.chapter.data) {
81
- pages.push({
82
- img: `${res.data.baseUrl}/data/${res.data.chapter.hash}/${id}`,
83
- page: parseInt(substringBefore(id, '-').replace(/[^0-9.]/g, '')),
84
- });
85
- }
86
- return pages;
192
+ ({ data: server } = await this.ctx.axios.get(`${this.apiUrl}/at-home/server/${encodeURIComponent(chapterId)}`));
87
193
  } catch (err) {
88
- throw new Error((err as Error).message);
194
+ throw this.error(err);
89
195
  }
196
+
197
+ const files = (dataSaver ? server.chapter.dataSaver : server.chapter.data) ?? [];
198
+ if (files.length === 0) {
199
+ // Chapters of official publishers link to their site and have no pages on MangaDex.
200
+ throw new Error(
201
+ `[${this.name}] Chapter ${chapterId} has no pages on MangaDex (it may be hosted on another site)`
202
+ );
203
+ }
204
+ const folder = dataSaver ? 'data-saver' : 'data';
205
+ return files.map((file, index) => ({
206
+ img: `${server.baseUrl}/${folder}/${server.chapter.hash}/${file}`,
207
+ page: index + 1,
208
+ }));
90
209
  };
91
210
 
92
211
  /**
@@ -94,258 +213,192 @@ export class MangaDex extends MangaParser {
94
213
  * @param page page number (default: 1)
95
214
  * @param limit limit of results to return (default: 20) (max: 100) (min: 1)
96
215
  */
97
- override search = async (query: string, page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> => {
98
- if (page <= 0) throw new Error('Page number must be greater than 0');
99
- if (limit > 100) throw new Error('Limit must be less than or equal to 100');
100
- if (limit * (page - 1) >= 10000) throw new Error('not enough results');
101
-
102
- try {
103
- const res = await this.ctx.axios.get(
104
- `${this.apiUrl}/manga?limit=${limit}&title=${encode(query)}&limit=${limit}&offset=${
105
- limit * (page - 1)
106
- }&order[relevance]=desc`
107
- );
108
-
109
- if (res.data.result === 'ok') {
110
- const results: ISearch<IMangaResult> = {
111
- currentPage: page,
112
- results: [],
113
- };
114
-
115
- for (const manga of res.data.data) {
116
- const findCoverArt = manga.relationships.find((item: any) => item.type === 'cover_art');
117
- const coverArtId = findCoverArt ? findCoverArt.id : null;
118
- const coverArt = await this.fetchCoverImage(
119
- coverArtId === null || coverArtId === void 0 ? void 0 : coverArtId
120
- );
121
-
122
- results.results.push({
123
- id: manga.id,
124
- title: Object.values(manga.attributes.title)[0] as string,
125
- altTitles: manga.attributes.altTitles,
126
- description: Object.values(manga.attributes.description)[0] as string,
127
- status: manga.attributes.status,
128
- releaseDate: manga.attributes.year,
129
- contentRating: manga.attributes.contentRating,
130
- lastVolume: manga.attributes.lastVolume,
131
- lastChapter: manga.attributes.lastChapter,
132
- image: `${this.baseUrl}/covers/${manga.id}/${coverArt}`,
133
- });
134
- }
135
-
136
- return results;
137
- } else {
138
- throw new Error(res.data.message);
139
- }
140
- } catch (err) {
141
- if ((err as AxiosError).code === 'ERR_BAD_REQUEST') {
142
- throw new Error('Bad request. Make sure you have entered a valid query.');
143
- }
216
+ override search = async (query: string, page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> =>
217
+ this.fetchList(
218
+ [
219
+ ['title', query],
220
+ ['order[relevance]', 'desc'],
221
+ ],
222
+ page,
223
+ limit
224
+ );
144
225
 
145
- throw new Error((err as Error).message);
146
- }
147
- };
148
226
  fetchRandom = async (): Promise<ISearch<IMangaResult>> => {
149
227
  try {
150
- const res = await this.ctx.axios.get(`${this.apiUrl}/manga/random`);
151
-
152
- if (res.data.result === 'ok') {
153
- const results: ISearch<IMangaResult> = {
154
- currentPage: 1,
155
- results: [],
156
- };
157
- const findCoverArt = res.data.data.relationships.find((item: any) => item.type === 'cover_art');
158
- const coverArtId = findCoverArt ? findCoverArt.id : null;
159
- const coverArt = await this.fetchCoverImage(coverArtId === null || coverArtId === void 0 ? void 0 : coverArtId);
160
-
161
- results.results.push({
162
- id: res.data.data.id,
163
- title: Object.values(res.data.data.attributes.title)[0] as string,
164
- altTitles: res.data.data.attributes.altTitles,
165
- description: Object.values(res.data.data.attributes.description)[0] as string,
166
- status: res.data.data.attributes.status,
167
- releaseDate: res.data.data.attributes.year,
168
- contentRating: res.data.data.attributes.contentRating,
169
- lastVolume: res.data.data.attributes.lastVolume,
170
- lastChapter: res.data.data.attributes.lastChapter,
171
- image: `${this.baseUrl}/covers/${res.data.data.id}/${coverArt}`,
172
- });
173
-
174
- return results;
175
- } else {
176
- throw new Error(res.data.message);
177
- }
228
+ const { data } = await this.ctx.axios.get(
229
+ `${this.apiUrl}/manga/random?${queryString([['includes[]', 'cover_art']])}`
230
+ );
231
+ return { currentPage: 1, hasNextPage: false, results: [this.toResult(data.data)] };
178
232
  } catch (err) {
179
- throw new Error((err as Error).message);
233
+ throw this.error(err);
180
234
  }
181
235
  };
182
- fetchRecentlyAdded = async (page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> => {
183
- if (page <= 0) throw new Error('Page number must be greater than 0');
184
- if (limit > 100) throw new Error('Limit must be less than or equal to 100');
185
- if (limit * (page - 1) >= 10000) throw new Error('not enough results');
186
236
 
187
- try {
188
- const res = await this.ctx.axios.get(
189
- `${
190
- this.apiUrl
191
- }/manga?includes[]=cover_art&contentRating[]=safe&contentRating[]=suggestive&contentRating[]=erotica&order[createdAt]=desc&hasAvailableChapters=true&limit=${limit}&offset=${
192
- limit * (page - 1)
193
- }`
194
- );
237
+ fetchRecentlyAdded = async (page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> =>
238
+ this.fetchList(
239
+ [
240
+ ['contentRating[]', 'safe'],
241
+ ['contentRating[]', 'suggestive'],
242
+ ['contentRating[]', 'erotica'],
243
+ ['order[createdAt]', 'desc'],
244
+ ['hasAvailableChapters', 'true'],
245
+ ],
246
+ page,
247
+ limit
248
+ );
195
249
 
196
- if (res.data.result === 'ok') {
197
- const results: ISearch<IMangaResult> = {
198
- currentPage: page,
199
- results: [],
200
- };
201
-
202
- for (const manga of res.data.data) {
203
- const findCoverArt = manga.relationships.find((item: any) => item.type === 'cover_art');
204
- const coverArtId = findCoverArt ? findCoverArt.id : null;
205
- const coverArt = await this.fetchCoverImage(
206
- coverArtId === null || coverArtId === void 0 ? void 0 : coverArtId
207
- );
208
- results.results.push({
209
- id: manga.id,
210
- title: Object.values(manga.attributes.title)[0] as string,
211
- altTitles: manga.attributes.altTitles,
212
- description: Object.values(manga.attributes.description)[0] as string,
213
- status: manga.attributes.status,
214
- releaseDate: manga.attributes.year,
215
- contentRating: manga.attributes.contentRating,
216
- lastVolume: manga.attributes.lastVolume,
217
- lastChapter: manga.attributes.lastChapter,
218
- image: `${this.baseUrl}/covers/${manga.id}/${coverArt}`,
219
- });
220
- }
221
-
222
- return results;
223
- } else {
224
- throw new Error(res.data.message);
225
- }
226
- } catch (err) {
227
- throw new Error((err as Error).message);
228
- }
229
- };
230
- fetchLatestUpdates = async (page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> => {
250
+ fetchLatestUpdates = async (page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> =>
251
+ this.fetchList([['order[latestUploadedChapter]', 'desc']], page, limit);
252
+
253
+ fetchPopular = async (page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> =>
254
+ this.fetchList(
255
+ [
256
+ ['order[followedCount]', 'desc'],
257
+ ['contentRating[]', 'safe'],
258
+ ['contentRating[]', 'suggestive'],
259
+ ['hasAvailableChapters', 'true'],
260
+ ],
261
+ page,
262
+ limit
263
+ );
264
+
265
+ /** One page of `/manga` with the given filters, covers included. */
266
+ private fetchList = async (
267
+ params: [string, string][],
268
+ page: number,
269
+ limit: number
270
+ ): Promise<ISearch<IMangaResult>> => {
231
271
  if (page <= 0) throw new Error('Page number must be greater than 0');
232
272
  if (limit > 100) throw new Error('Limit must be less than or equal to 100');
233
- if (limit * (page - 1) >= 10000) throw new Error('not enough results');
273
+ if (limit * (page - 1) >= MAX_RESULT_WINDOW) throw new Error('not enough results');
234
274
 
275
+ const offset = limit * (page - 1);
235
276
  try {
236
- const res = await this.ctx.axios.get(
237
- `${this.apiUrl}/manga?order[latestUploadedChapter]=desc&limit=${limit}&offset=${limit * (page - 1)}`
277
+ const { data } = await this.ctx.axios.get(
278
+ `${this.apiUrl}/manga?${queryString([...params, ['includes[]', 'cover_art'], ['limit', limit], ['offset', offset]])}`
238
279
  );
239
-
240
- if (res.data.result === 'ok') {
241
- const results: ISearch<IMangaResult> = {
242
- currentPage: page,
243
- results: [],
244
- };
245
-
246
- for (const manga of res.data.data) {
247
- const findCoverArt = manga.relationships.find((item: any) => item.type === 'cover_art');
248
- const coverArtId = findCoverArt ? findCoverArt.id : null;
249
- const coverArt = await this.fetchCoverImage(
250
- coverArtId === null || coverArtId === void 0 ? void 0 : coverArtId
251
- );
252
-
253
- results.results.push({
254
- id: manga.id,
255
- title: Object.values(manga.attributes.title)[0] as string,
256
- altTitles: manga.attributes.altTitles,
257
- description: Object.values(manga.attributes.description)[0] as string,
258
- status: manga.attributes.status,
259
- releaseDate: manga.attributes.year,
260
- contentRating: manga.attributes.contentRating,
261
- lastVolume: manga.attributes.lastVolume,
262
- lastChapter: manga.attributes.lastChapter,
263
- image: `${this.baseUrl}/covers/${manga.id}/${coverArt}`,
264
- });
265
- }
266
-
267
- return results;
268
- } else {
269
- throw new Error(res.data.message);
270
- }
280
+ if (data.result !== 'ok') throw new Error(data.errors?.[0]?.detail ?? data.message);
281
+
282
+ const total: number = data.total ?? 0;
283
+ return {
284
+ currentPage: page,
285
+ hasNextPage: offset + limit < Math.min(total, MAX_RESULT_WINDOW),
286
+ totalResults: total,
287
+ results: (data.data as MangaEntity[]).map((manga) => this.toResult(manga)),
288
+ };
271
289
  } catch (err) {
272
- throw new Error((err as Error).message);
290
+ throw this.error(err);
273
291
  }
274
292
  };
275
- fetchPopular = async (page: number = 1, limit: number = 20): Promise<ISearch<IMangaResult>> => {
276
- if (page <= 0) throw new Error('Page number must be greater than 0');
277
- if (limit > 100) throw new Error('Limit must be less than or equal to 100');
278
- if (limit * (page - 1) >= 10000) throw new Error('not enough results');
279
293
 
280
- try {
281
- const res = await this.ctx.axios.get(
282
- `${
283
- this.apiUrl
284
- }/manga?includes[]=cover_art&includes[]=artist&includes[]=author&order[followedCount]=desc&contentRating[]=safe&contentRating[]=suggestive&hasAvailableChapters=true&limit=${limit}&offset=${
285
- limit * (page - 1)
286
- }`
294
+ /** Every readable chapter in `lang`, in the feed's order (volume, then chapter). */
295
+ private fetchChapters = async (mangaId: string, lang: string): Promise<IMangaChapter[]> => {
296
+ const chapters: IMangaChapter[] = [];
297
+ let offset = 0;
298
+ let total = Infinity;
299
+ while (offset < total && offset < MAX_RESULT_WINDOW) {
300
+ const { data } = await this.ctx.axios.get(
301
+ `${this.apiUrl}/manga/${encodeURIComponent(mangaId)}/feed?${queryString([
302
+ ['translatedLanguage[]', lang],
303
+ // Chapters that only link to a publisher's site, or aren't readable yet, have no pages here.
304
+ ['includeExternalUrl', 0],
305
+ ['includeEmptyPages', 0],
306
+ ['includeFuturePublishAt', 0],
307
+ ['includeUnavailable', 0],
308
+ ...ALL_CONTENT_RATINGS.map((rating): [string, string] => ['contentRating[]', rating]),
309
+ ['includes[]', 'scanlation_group'],
310
+ ['order[volume]', 'asc'],
311
+ ['order[chapter]', 'asc'],
312
+ ['limit', Math.min(FEED_PAGE_SIZE, MAX_RESULT_WINDOW - offset)],
313
+ ['offset', offset],
314
+ ])}`
287
315
  );
288
-
289
- if (res.data.result === 'ok') {
290
- const results: ISearch<IMangaResult> = {
291
- currentPage: page,
292
- results: [],
293
- };
294
-
295
- for (const manga of res.data.data) {
296
- const findCoverArt = manga.relationships.find((item: any) => item.type === 'cover_art');
297
- const coverArtId = findCoverArt ? findCoverArt.id : null;
298
- const coverArt = await this.fetchCoverImage(
299
- coverArtId === null || coverArtId === void 0 ? void 0 : coverArtId
300
- );
301
-
302
- results.results.push({
303
- id: manga.id,
304
- title: Object.values(manga.attributes.title)[0] as string,
305
- altTitles: manga.attributes.altTitles,
306
- description: Object.values(manga.attributes.description)[0] as string,
307
- status: manga.attributes.status,
308
- releaseDate: manga.attributes.year,
309
- contentRating: manga.attributes.contentRating,
310
- lastVolume: manga.attributes.lastVolume,
311
- lastChapter: manga.attributes.lastChapter,
312
- image: `${this.baseUrl}/covers/${manga.id}/${coverArt}`,
313
- });
314
- }
315
-
316
- return results;
317
- } else {
318
- throw new Error(res.data.message);
319
- }
320
- } catch (err) {
321
- throw new Error((err as Error).message);
316
+ const page: ChapterEntity[] = data.data ?? [];
317
+ for (const chapter of page) chapters.push(this.toChapter(chapter));
318
+ total = data.total ?? 0;
319
+ if (page.length === 0) break;
320
+ offset += page.length;
322
321
  }
322
+ return chapters;
323
323
  };
324
- private fetchAllChapters = async (mangaId: string, offset: number, res?: AxiosResponse<any, any>): Promise<any[]> => {
325
- if (res?.data?.offset + 96 >= res?.data?.total) {
326
- return [];
327
- }
328
324
 
329
- const response = await this.ctx.axios.get(
330
- `${this.apiUrl}/manga/${mangaId}/feed?offset=${offset}&limit=96&order[volume]=desc&order[chapter]=desc&translatedLanguage[]=en`
331
- );
332
-
333
- return [...response.data.data, ...(await this.fetchAllChapters(mangaId, offset + 96, response))];
325
+ /** A title from `/manga`; `thumbnail` picks the 512 px cover instead of the full-size one. */
326
+ private toResult = (manga: MangaEntity, thumbnail: boolean = true): IMangaResult => {
327
+ const { attributes } = manga;
328
+ const { title, altTitles } = pickTitles(attributes.title, attributes.altTitles);
329
+ const result: IMangaResult = { id: manga.id, title };
330
+ if (altTitles.length > 0) result.altTitles = altTitles;
331
+
332
+ const cover = manga.relationships?.find((rel) => rel.type === 'cover_art')?.attributes?.fileName;
333
+ if (cover) result.image = `${this.uploadsUrl}/covers/${manga.id}/${cover}${thumbnail ? '.512.jpg' : ''}`;
334
+
335
+ const descriptions = entries(attributes.description);
336
+ const description = (descriptions.find(([lang]) => lang === 'en') ?? descriptions[0])?.[1];
337
+ const text = description ? markdownToText(description) : '';
338
+ if (text) result.description = text;
339
+
340
+ if (attributes.status) result.status = STATUSES[attributes.status] ?? MediaStatus.UNKNOWN;
341
+ if (typeof attributes.year === 'number') result.releaseDate = attributes.year;
342
+ result.url = `${this.baseUrl}/title/${manga.id}`;
343
+ if (attributes.contentRating) result.contentRating = attributes.contentRating;
344
+ const lastVolume = toNumber(attributes.lastVolume);
345
+ if (lastVolume !== undefined) result.lastVolume = lastVolume;
346
+ const lastChapter = toNumber(attributes.lastChapter);
347
+ if (lastChapter !== undefined) result.lastChapter = lastChapter;
348
+ return result;
334
349
  };
335
350
 
336
- private fetchCoverImage = async (coverId: string): Promise<string> => {
337
- const { data } = await this.ctx.axios.get(`${this.apiUrl}/cover/${coverId}`);
351
+ private toChapter = (chapter: ChapterEntity): IMangaChapter => {
352
+ const { attributes } = chapter;
353
+ const chapterNumber = parseChapterNumber(attributes.chapter);
354
+ const volumeNumber = toNumber(attributes.volume);
355
+ const label = attributes.chapter?.trim();
356
+ const result: IMangaChapter = {
357
+ id: chapter.id,
358
+ title:
359
+ attributes.title?.trim() || (chapterNumber !== undefined ? `Chapter ${chapterNumber}` : label || 'Oneshot'),
360
+ };
361
+ if (chapterNumber !== undefined) result.chapterNumber = chapterNumber;
362
+ if (volumeNumber !== undefined) result.volumeNumber = volumeNumber;
363
+ if (typeof attributes.pages === 'number' && attributes.pages > 0) result.pages = attributes.pages;
364
+ const releaseDate = attributes.publishAt ?? attributes.readableAt;
365
+ if (releaseDate) result.releaseDate = releaseDate;
366
+ const groups = (chapter.relationships ?? [])
367
+ .filter((rel) => rel.type === 'scanlation_group')
368
+ .map((rel) => rel.attributes?.name?.trim())
369
+ .filter((name): name is string => Boolean(name));
370
+ if (groups.length > 0) result.scanlator = groups.join(' & ');
371
+ if (attributes.translatedLanguage) result.language = attributes.translatedLanguage;
372
+ result.url = `${this.baseUrl}/chapter/${chapter.id}`;
373
+ return result;
374
+ };
338
375
 
339
- const fileName = data.data.attributes.fileName;
376
+ /** Names of the title's authors or artists (included with the request), without repeats. */
377
+ private relatedNames = (manga: MangaEntity, type: 'author' | 'artist'): string[] => {
378
+ const names: string[] = [];
379
+ for (const rel of manga.relationships ?? []) {
380
+ const name = rel.type === type ? rel.attributes?.name?.trim() : undefined;
381
+ if (name && !names.includes(name)) names.push(name);
382
+ }
383
+ return names;
384
+ };
340
385
 
341
- return fileName;
386
+ private tagNames = (manga: MangaEntity, group: string): string[] =>
387
+ (manga.attributes.tags ?? [])
388
+ .filter((tag) => tag.attributes.group === group)
389
+ .flatMap((tag) => {
390
+ const names = entries(tag.attributes.name);
391
+ const name = (names.find(([lang]) => lang === 'en') ?? names[0])?.[1];
392
+ return name ? [name] : [];
393
+ });
394
+
395
+ /** The API's own error message when it sent one (e.g. `Manga ... not found.`). */
396
+ private error = (err: unknown): Error => {
397
+ const response = (err as AxiosError<{ errors?: { detail?: string }[] }>)?.response;
398
+ const detail = response?.data?.errors?.[0]?.detail;
399
+ if (detail) return new Error(`[${this.name}] ${detail}`);
400
+ if ((err as AxiosError)?.code === 'ERR_BAD_REQUEST')
401
+ return new Error(`[${this.name}] Bad request. Make sure you have entered a valid query.`);
402
+ return new Error(`[${this.name}] ${(err as Error)?.message ?? String(err)}`);
342
403
  };
343
404
  }
344
-
345
- // (async () => {
346
- // const md = new MangaDex();
347
- // const search = await md.search('solo leveling');
348
- // const manga = await md.fetchMangaInfo(search.results[0].id);
349
- // const chapterPages = await md.fetchChapterPages(manga.chapters![0].id);
350
- // console.log(chapterPages);
351
- // })();