-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.ts
756 lines (711 loc) · 18.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/**
* @module @xmcl/curseforge
*/
import { Dispatcher, fetch } from 'undici'
export interface ModAsset {
id: number
modId: number
title: string
description: string
thumbnailUrl: string
url: string
}
export const enum ModStatus {
New = 1,
ChangesRequired = 2,
UnderSoftReview = 3,
Approved = 4,
Rejected = 5,
ChangesMade = 6,
Inactive = 7,
Abandoned = 8,
Deleted = 9,
UnderReview = 10,
}
export const enum FileReleaseType {
Release = 1,
Beta = 2,
Alpha = 3,
}
export const enum FileModLoaderType {
Any = 0,
Forge = 1,
Cauldron = 2,
LiteLoader = 3,
Fabric = 4,
Quilt = 5,
}
export interface FileIndex {
gameVersion: string
fileId: number
filename: string
releaseType: FileReleaseType
gameVersionTypeId: number | null
modLoader: FileModLoaderType
}
export interface Mod {
/**
* The addon id. You can use this in many functions required the `addonID`
*/
id: number
/**
* Game id. Minecraft is 432.
*/
gameId: number
/**
* The display name of the addon
*/
name: string
/**
* The mod slug that would appear in the URL
*/
slug: string
/** Relevant links for the mod such as Issue tracker and Wiki */
links: {
websiteUrl: string
wikiUrl: string
issuesUrl: string
sourceUrl: string
}
/**
* One line summery
*/
summary: string
/**
* Current mod status
*/
status: ModStatus
/**
* Number of downloads for the mod
*/
downloadCount: number
/**
* Whether the mod is included in the featured mods list
*/
isFeatured: boolean
/**
* The main category of the mod as it was chosen by the mod author
*/
primaryCategoryId: number
/**
* List of categories that this mod is related to
*/
categories: ModCategory[]
/**
* The class id this mod belongs to
*/
classId: number | null
/**
* The list of authors
*/
authors: Author[]
logo: ModAsset
screenshots: ModAsset[]
/**
* The id of the main file of the mod
*/
mainFileId: number
latestFiles: File[]
/**
* List of file related details for the latest files of the mod
*/
latestFilesIndexes: FileIndex[]
/**
* The creation date of the mod
*/
dateCreated: string
dateModified: string
dateReleased: string
/**
* Is mod allowed to be distributed
*/
allowModDistribution: boolean | null
/**
* The mod popularity rank for the game
*/
gamePopularityRank: number
/**
* Is the mod available for search. This can be false when a mod is experimental, in a deleted state or has only alpha files
*/
isAvailable: boolean
/**
* The default download file id
*/
defaultFileId: number
/**
* The mod's thumbs up count
*/
thumbsUpCount: number
}
export interface GameVersionLatestFile {
gameVersion: string
projectFileId: number
projectFileName: string
fileType: number
}
export interface CategorySection {
id: number
gameId: number
name: string
packageType: number
path: string
initialInclusionPattern: string
extraIncludePattern?: any
gameCategoryId: number
}
export const enum HashAlgo {
Sha1 = 1,
Md5 = 2,
}
export interface FileHash {
algo: HashAlgo
value: string
}
export const enum FileStatus {
Processing = 1,
ChangesRequired = 2,
UnderReview = 3,
Approved = 4,
Rejected = 5,
MalwareDetected = 6,
Deleted = 7,
Archived = 8,
Testing = 9,
Released = 10,
ReadyForReview = 11,
Deprecated = 12,
Baking = 13,
AwaitingPublishing = 14,
FailedPublishing = 15,
}
export const enum FileRelationType {
EmbeddedLibrary = 1,
OptionalDependency = 2,
RequiredDependency = 3,
Tool = 4,
Incompatible = 5,
Include = 6,
}
export interface FileDependency {
modId: number
relationType: FileRelationType
}
export interface File {
/**
* The fileID
*/
id: number
/**
* The game id related to the mod that this file belongs to
*/
gameId: number
/**
* The projectId (addonId)
*/
modId: number
/**
* Whether the file is available to download
*/
isAvailable: boolean
/**
* Display name
*/
displayName: string
/**
* File name. Might be the same with `displayName`
*/
fileName: string
/**
* Release or type.
* - `1` is the release
* - `2` beta
* - `3` alpha
*/
releaseType: number
fileStatus: FileStatus
hashes: FileHash[]
/**
* The date of this file uploaded
*/
fileDate: string
/**
* # bytes of this file.
*/
fileLength: number
/**
* Number of downloads for the mod
*/
downloadCount: number
/**
* Url to download
*/
downloadUrl?: string
/**
* Game version string array, like `["1.12.2"]`
*/
gameVersions: string[]
/**
* Metadata used for sorting by game versions
*/
isAlternate: boolean
alternateFileId: number
dependencies: FileDependency[]
/**
* What files inside?
*/
modules: Module[]
sortableGameVersions?: SortableGameVersion[]
}
export interface SortableGameVersion {
gameVersionPadded: string
gameVersion: string
gameVersionReleaseDate: string
gameVersionName: string
}
/**
* Represent a file in a `File`.
*/
export interface Module {
/**
* Actually the file name, not the folder
*/
name: string
/**
* A number represent fingerprint
*/
fingerprint: number
type: number
}
/**
* The author info
*/
export interface Author {
/**
* The project id of this query
*/
projectId: number
projectTitleId?: any
projectTitleTitle?: any
/**
* Display name of the author
*/
name: string
/**
* The full url of author homepage in curseforge
*/
url: string
/**
* The id of this author
*/
id: number
userId: number
twitchId: number
}
export interface ModCategory {
/**
* The category id
*/
id: number
gameId: number
name: string
slug: string
url: string
iconUrl: string
dateModified: string
/**
* A top level category for other categories
*/
isClass: boolean | null
/**
* The class id of the category, meaning - the class of which this category is under
*/
classId: number | null
/**
* The parent category for this category
*/
parentCategoryId: number | null
/**
* The display index for this category
*/
displayIndex: number | null
}
/**
* The search options of the search API.
*
* @see {@link searchMods}
*/
export interface SearchOptions {
/**
* The category section id, which is also a category id.
* You can fetch if from `getCategories`.
*
* To get available categories, you can:
*
* ```ts
* const cat = await getCategories();
* const sectionIds = cat
* .filter(c => c.gameId === 432) // 432 is minecraft game id
* .filter(c => c.rootGameCategoryId === null).map(c => c.id);
* // the sectionIds is all normal sections here
* ```
*
* @see {@link getCategories}
*/
classId?: number
/**
* This is actually the sub category id of the `sectionId`. All the numbers for this should also be fetch by `getCategories`.
*
* To get available values, you can:
*
* ```ts
* const cat = await getCategories();
* const sectionId = 6; // the mods
* const categoryIds = cat
* .filter(c => c.gameId === 432) // 432 is minecraft game id
* .filter(c => c.rootGameCategoryId === sectionId) // only under the section id
* .map(c => c.id);
* // Use categoryIds' id to search under the corresponding section id.
* ```
*
* @see {@link getCategories}
*/
categoryId?: number
/**
* The game id. The Minecraft is 432.
*
* @default 432
*/
gameId?: number
/**
* The game version. For Minecraft, it should looks like 1.12.2.
*/
gameVersion?: string
/**
* The index of the addon, NOT the page!
*
* When your page size is 25, if you want to get next page contents, you should have index = 25 to get 2nd page content.
*
* @default 0
*/
index?: number
/**
* Filter by ModsSearchSortField enumeration
*/
sortField?: ModsSearchSortField
/**
* 'asc' if sort is in ascending order, 'desc' if sort is in descending order
*/
sortOrder?: 'asc' | 'desc'
/**
* Filter only mods associated to a given modloader (Forge, Fabric ...). Must be coupled with gameVersion.
*/
modLoaderType?: FileModLoaderType
modLoaderTypes?: string[]
/**
* Filter only mods that contain files tagged with versions of the given gameVersionTypeId
*/
gameVersionTypeId?: number
/**
* Filter by slug (coupled with classId will result in a unique result).
*/
slug?: string
/**
* The page size, or the number of the addons in a page.
*
* @default 25
*/
pageSize?: number
/**
* The keyword of search. If this is absent, it just list out the available addons by `sectionId` and `categoryId`.
*/
searchFilter?: string
}
export const enum ModsSearchSortField {
Featured = 1,
Popularity = 2,
LastUpdated = 3,
Name = 4,
Author = 5,
TotalDownloads = 6,
Category = 7,
GameVersion = 8,
}
/**
* The options to query
*/
export interface QueryOption {
/**
* Additional header
*/
headers?: Record<string, any>
/**
* override the http client
*/
client?: (url: string, options: QueryOption, body?: object, text?: boolean) => Promise<object | string>
}
export interface GetModFilesOptions {
modId: number
gameVersion?: string
modLoaderType?: FileModLoaderType
/**
* Filter only files that are tagged with versions of the given gameVersionTypeId
*/
gameVersionTypeId?: number
index?: number
pageSize?: number
}
export interface Pagination {
/**
* A zero based index of the first item that is included in the response
*/
index: number
/**
* The requested number of items to be included in the response
*/
pageSize: number
/**
* The actual number of items that were included in the response
*/
resultCount: number
/**
* The total number of items available by the fetch
*/
totalCount: number
}
export interface CurseforgeClientOptions {
/**
* Extra headers
*/
headers?: Record<string, string>
/**
* The optional undici dispatcher
*/
dispatcher?: Dispatcher
/**
* The base url, the default is `https://api.curseforge.com`
*/
baseUrl?: string
}
export class CurseforgeApiError extends Error {
constructor(readonly url: string, readonly status: number, readonly body: string) {
super(`Fail to fetch curseforge api ${url}. Status=${status}. ${body}`)
this.name = 'CurseforgeApiError'
}
}
/**
* Reference the https://docs.curseforge.com/#curseforge-core-api-mods
*/
export class CurseforgeV1Client {
headers: Record<string, string>
private dispatcher?: Dispatcher
private baseUrl: string
constructor(private apiKey: string, options?: CurseforgeClientOptions) {
this.headers = {
'x-api-key': this.apiKey,
...(options?.headers || {}),
}
this.baseUrl = options?.baseUrl || 'https://api.curseforge.com'
this.dispatcher = options?.dispatcher
}
/**
* @see https://docs.curseforge.com/#get-categories
*/
async getCategories(signal?: AbortSignal) {
const url = new URL(this.baseUrl + '/v1/categories')
url.searchParams.append('gameId', '432')
const response = await fetch(url, {
headers: {
...this.headers,
accept: 'application/json',
},
signal,
dispatcher: this.dispatcher,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const categories = await response.json() as { data: ModCategory[] }
return categories.data
}
/**
* Get the mod by mod Id.
* @see https://docs.curseforge.com/#get-mod
* @param modId The id of mod
* @param options The query options
*/
async getMod(modId: number, signal?: AbortSignal) {
const url = new URL(this.baseUrl + `/v1/mods/${modId}`)
const response = await fetch(url, {
dispatcher: this.dispatcher,
headers: {
accept: 'application/json',
...this.headers,
},
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: Mod }
return result.data
}
/**
* @see https://docs.curseforge.com/#get-mod-description
*/
async getModDescription(modId: number, signal?: AbortSignal) {
const url = new URL(this.baseUrl + `/v1/mods/${modId}/description`)
const response = await fetch(url, {
dispatcher: this.dispatcher,
headers: {
...this.headers,
accept: 'application/json',
},
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: string }
return result.data
}
/**
* @see https://docs.curseforge.com/#get-mod-files
*/
async getModFiles(options: GetModFilesOptions, signal?: AbortSignal) {
const url = new URL(this.baseUrl + `/v1/mods/${options.modId}/files`)
url.searchParams.append('gameVersion', options.gameVersion ?? '')
if (options.modLoaderType !== undefined) {
url.searchParams.append('modLoaderType', options.modLoaderType?.toString() ?? '')
}
url.searchParams.append('gameVersionTypeId', options.gameVersionTypeId?.toString() ?? '')
url.searchParams.append('index', options.index?.toString() ?? '')
url.searchParams.append('pageSize', options.pageSize?.toString() ?? '')
const response = await fetch(url, {
dispatcher: this.dispatcher,
headers: {
...this.headers,
accept: 'application/json',
},
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: File[]; pagination: Pagination }
return result
}
/**
* @see https://docs.curseforge.com/#curseforge-core-api-files
*/
async getModFile(modId: number, fileId: number, signal?: AbortSignal) {
const url = new URL(this.baseUrl + `/v1/mods/${modId}/files/${fileId}`)
const response = await fetch(url, {
headers: {
...this.headers,
accept: 'application/json',
},
dispatcher: this.dispatcher,
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: File }
return result.data
}
/**
* @see https://docs.curseforge.com/#get-mods
*/
async getMods(modIds: number[], signal?: AbortSignal) {
const url = new URL(this.baseUrl + '/v1/mods')
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify({ modIds }),
dispatcher: this.dispatcher,
headers: {
...this.headers,
'content-type': 'application/json',
accept: 'application/json',
},
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: Mod[] }
return result.data
}
/**
* @see https://docs.curseforge.com/#get-files
*/
async getFiles(fileIds: number[], signal?: AbortSignal) {
const url = new URL(this.baseUrl + '/v1/mods/files')
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify({ fileIds }),
headers: {
...this.headers,
'content-type': 'application/json',
accept: 'application/json',
},
dispatcher: this.dispatcher,
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: File[] }
return result.data
}
/**
* @see https://docs.curseforge.com/#search-mods
*/
async searchMods(options: SearchOptions, signal?: AbortSignal) {
const url = new URL(this.baseUrl + '/v1/mods/search')
url.searchParams.append('gameId', '432')
if (options.classId) { url.searchParams.append('classId', options.classId.toString()) }
if (options.categoryId) { url.searchParams.append('categoryId', options.categoryId.toString()) }
if (options.gameVersion) { url.searchParams.append('gameVersion', options.gameVersion) }
if (options.searchFilter) { url.searchParams.append('searchFilter', options.searchFilter) }
url.searchParams.append('sortField', options.sortField?.toString() ?? ModsSearchSortField.Popularity.toString())
url.searchParams.append('sortOrder', options.sortOrder ?? 'desc')
if (options.modLoaderType) { url.searchParams.append('modLoaderType', options.modLoaderType.toString()) }
if (options.modLoaderTypes) { url.searchParams.append('modLoaderTypes', '[' + options.modLoaderTypes.join(',') + ']') }
if (options.gameVersionTypeId) { url.searchParams.append('gameVersionTypeId', options.gameVersionTypeId.toString()) }
url.searchParams.append('index', options.index?.toString() ?? '0')
url.searchParams.append('pageSize', options.pageSize?.toString() ?? '25')
if (options.slug) { url.searchParams.append('slug', options.slug) }
const response = await fetch(url, {
headers: {
...this.headers,
accept: 'application/json',
},
dispatcher: this.dispatcher,
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: Mod[]; pagination: Pagination }
return result
}
/**
* https://docs.curseforge.com/#get-mod-file-changelog
*/
async getModFileChangelog(modId: number, fileId: number, signal?: AbortSignal) {
const url = new URL(this.baseUrl + `/v1/mods/${modId}/files/${fileId}/changelog`)
const response = await fetch(url, {
headers: {
...this.headers,
accept: 'application/json',
},
dispatcher: this.dispatcher,
signal,
})
if (response.status !== 200) {
throw new CurseforgeApiError(url.toString(), response.status, await response.text())
}
const result = await response.json() as { data: string }
return result.data
}
}