This repository was archived by the owner on May 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathforge.ts
More file actions
662 lines (613 loc) · 18.8 KB
/
Copy pathforge.ts
File metadata and controls
662 lines (613 loc) · 18.8 KB
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
import { LibraryInfo, MinecraftFolder, MinecraftLocation, Version as VersionJson } from '@xmcl/core'
import { download, getDownloadBaseOptions } from '@xmcl/file-transfer'
import { filterEntries, open, openEntryReadStream, readAllEntries, readEntry } from '@xmcl/unzip'
import { createWriteStream } from 'fs'
import { writeFile } from 'fs/promises'
import { dirname, join, relative, sep } from 'path'
import { pipeline } from 'stream/promises'
import { Entry, ZipFile } from 'yauzl'
import { ZipFile as WriteableZipFile } from 'yazl'
import { DEFAULT_FORGE_MAVEN } from './forge.browser'
import { LibraryOptions, LibrariesTrackerEvents, resolveLibraryDownloadUrls } from './libraries'
import {
InstallProfile,
InstallProfileOption,
ProfileTrackerEvents,
installByProfile,
} from './profile'
import { Tracker, onDownloadSingle, onState, WithDownload } from './tracker'
import { InstallOptions as InstallOptionsBase, WithDiagnose, ensureDir, ensureFile } from './utils'
import { joinUrl, normalizeArray } from './utils.browser'
export interface ForgeTrackerEvents extends LibrariesTrackerEvents, ProfileTrackerEvents {
'forge.installer': WithDownload<{ version: string; path: string }>
}
import { diagnoseFile } from './diagnose'
import { InstallError } from './error'
export type { ForgeVersion, ForgeVersionList } from './forge.browser'
export { DEFAULT_FORGE_MAVEN, getForgeVersionList } from './forge.browser'
/**
* All the useful entries in forge installer jar
*/
export interface ForgeInstallerEntries {
/**
* maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}.jar
*/
forgeJar?: Entry
/**
* maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-universal.jar
*/
forgeUniversalJar?: Entry
/**
* data/client.lzma
*/
clientLzma?: Entry
/**
* data/server.lzma
*/
serverLzma?: Entry
/**
* install_profile.json
*/
installProfileJson?: Entry
/**
* version.json
*/
versionJson?: Entry
/**
* forge-${forgeVersion}-universal.jar
*/
legacyUniversalJar?: Entry
/**
* forge-${forgeVersion}-shim.jar
*/
shimJar?: Entry
/**
* data/run.sh
*/
runSh?: Entry
/**
* data/run.bat
*/
runBat?: Entry
/**
* data/unix_args.txt
*/
unixArgs?: Entry
/**
* data/user_jvm_args.txt
*/
userJvmArgs?: Entry
/**
* data/win_args.txt
*/
winArgs?: Entry
}
export type ForgeInstallerEntriesPattern = ForgeInstallerEntries &
Required<Pick<ForgeInstallerEntries, 'versionJson' | 'installProfileJson'>>
export type ForgeLegacyInstallerEntriesPattern = Required<
Pick<ForgeInstallerEntries, 'installProfileJson' | 'legacyUniversalJar'>
>
type RequiredVersion = {
/**
* The installer info.
*
* If this is not presented, it will genreate from mcversion and forge version.
*/
installer?: {
sha1?: string
/**
* The url path to concat with forge maven
*/
path: string
}
/**
* The minecraft version
*/
mcversion: string
/**
* The forge version (without minecraft version)
*/
version: string
}
/**
* The options to install forge.
*/
export interface InstallForgeOptions
extends
Omit<LibraryOptions, 'tracker'>,
InstallOptionsBase,
Omit<InstallProfileOption, 'tracker'>,
WithDiagnose {
side?: 'client' | 'server'
/**
* The tracker to track the install process
*/
tracker?: Tracker<ForgeTrackerEvents>
}
function getLibraryPathWithoutMaven(mc: MinecraftFolder, name: string) {
// remove the maven/ prefix
return mc.getLibraryByPath(name.substring(name.indexOf('/') + 1))
}
function extractEntryTo(zip: ZipFile, e: Entry, dest: string) {
return openEntryReadStream(zip, e).then((stream) => pipeline(stream, createWriteStream(dest)))
}
async function installLegacyForgeFromUniversalZip(
forgeZip: ZipFile,
mc: MinecraftFolder,
forgeVersion: string,
mcVersion: string,
) {
const minecraftZip = await open(mc.getVersionJar(mcVersion), {
lazyEntries: true,
autoClose: false,
})
const forgeEntries = await readAllEntries(forgeZip)
const mcEntries = await readAllEntries(minecraftZip)
const finalZipEntries: Record<string, [Entry, ZipFile]> = {}
// forge entries overwrite mc entries
for (const e of mcEntries) {
if (e.fileName.startsWith('META-INF')) continue
finalZipEntries[e.fileName] = [e, minecraftZip]
}
for (const e of forgeEntries) {
if (e.fileName.startsWith('META-INF')) continue
finalZipEntries[e.fileName] = [e, forgeZip]
}
const finalZip = new WriteableZipFile()
for (const [k, [e, zip]] of Object.entries(finalZipEntries)) {
finalZip.addReadStream(await openEntryReadStream(zip, e), e.fileName)
}
finalZip.end()
const dest = mc.getLibraryByPath(
`net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}.jar`,
)
await ensureDir(dirname(dest))
await pipeline(finalZip.outputStream, createWriteStream(dest))
const versionId = `${mcVersion}-forge-${forgeVersion}`
await ensureDir(mc.getVersionRoot(versionId))
const versionJson: VersionJson = {
id: versionId,
inheritsFrom: mcVersion,
time: new Date().toUTCString(),
type: 'release',
releaseTime: new Date().toUTCString(),
minimumLauncherVersion: 4,
arguments: {
game: [],
// eslint-disable-next-line no-template-curly-in-string
jvm: ['-Dminecraft.applet.TargetDirectory=${game_directory}'],
},
mainClass: 'net.minecraft.launchwrapper.Launch',
libraries: [
{ name: `net.minecraftforge:forge:${forgeVersion}` },
{
downloads: {
artifact: {
path: 'guava-12.0.1.jar',
sha1: 'b8e78b9af7bf45900e14c6f958486b6ca682195f',
size: -1,
url: 'https://files.minecraftforge.net/maven/com/google/guava/guava/12.0.1/guava-12.0.1.jar',
},
},
name: 'com.google.guava:guava:12.0.1',
},
{
downloads: {
artifact: {
path: 'argo-2.25.jar',
sha1: 'bb672829fde76cb163004752b86b0484bd0a7f4b',
size: -1,
url: 'https://files.minecraftforge.net/maven/net/sourceforge/argo/argo/2.25/argo-2.25.jar',
},
},
name: 'net.sourceforge.argo:argo:2.25',
},
{
downloads: {
artifact: {
path: 'asm-all-4.0.jar',
sha1: '98308890597acb64047f7e896638e0d98753ae82',
size: -1,
url: 'https://files.multimc.org/fmllibs/asm-all-4.0.jar',
},
},
name: 'org.ow2.asm:asm-all:4.0',
},
{
downloads: {
artifact: {
path: 'bcprov-jdk15on-147.jar',
sha1: 'b6f5d9926b0afbde9f4dbe3db88c5247be7794bb',
size: -1,
url: 'https://files.multimc.org/fmllibs/bcprov-jdk15on-147.jar',
},
},
name: 'org.bouncycastle:bcprov-jdk15on:1.47',
},
],
}
await writeFile(mc.getVersionJson(versionId), JSON.stringify(versionJson, null, 4))
return versionId
}
async function installLegacyForgeFromZip(
zip: ZipFile,
entries: ForgeLegacyInstallerEntriesPattern,
profile: InstallProfile,
mc: MinecraftFolder,
jarFilePath: string,
options: InstallForgeOptions,
) {
const versionJson = profile.versionInfo
if (!versionJson) {
throw new Error(`Malform legacy installer json ${profile.version}`)
}
// apply override for inheritsFrom
versionJson.id = options.versionId || versionJson.id
versionJson.inheritsFrom = options.inheritsFrom || versionJson.inheritsFrom
const rootPath = mc.getVersionRoot(versionJson.id)
const versionJsonPath = join(rootPath, `${versionJson.id}.json`)
await ensureFile(versionJsonPath)
const forgeLib = versionJson.libraries.find(
(l) =>
l.name.startsWith('net.minecraftforge:forge') ||
l.name.startsWith('net.minecraftforge:minecraftforge'),
)
if (!forgeLib) {
throw new BadForgeInstallerJarError(jarFilePath)
}
const library = LibraryInfo.resolve(forgeLib)
const jarPath = mc.getLibraryByPath(library.path)
await ensureFile(jarPath)
await Promise.all([
writeFile(versionJsonPath, JSON.stringify(versionJson, undefined, 4)),
extractEntryTo(zip, entries.legacyUniversalJar, jarPath),
])
return versionJson.id
}
/**
* Unpack forge installer jar file content to the version library artifact directory.
* @param zip The forge jar file
* @param entries The entries
* @param profile The forge install profile
* @param mc The minecraft location
* @returns The installed version id
*/
export async function unpackForgeInstaller(
zip: ZipFile,
entries: ForgeInstallerEntriesPattern,
profile: InstallProfile,
mc: MinecraftFolder,
jarPath: string,
options: InstallForgeOptions,
) {
const versionJson: VersionJson = await readEntry(zip, entries.versionJson)
.then((b) => b.toString())
.then(JSON.parse)
// apply override for inheritsFrom
versionJson.id = options.versionId || versionJson.id
versionJson.inheritsFrom = options.inheritsFrom || versionJson.inheritsFrom
// resolve all the required paths
const rootPath = mc.getVersionRoot(versionJson.id)
const versionJsonPath = join(rootPath, `${versionJson.id}.json`)
const installJsonPath = join(rootPath, 'install_profile.json')
const mavenLibVersionPath = dirname(jarPath)
const unpackData = (entry: Entry) => {
promises.push(
extractEntryTo(
zip,
entry,
join(mavenLibVersionPath, entry.fileName.substring('data/'.length)),
),
)
}
await ensureFile(versionJsonPath)
const promises: Promise<void>[] = []
if (entries.forgeUniversalJar) {
promises.push(
extractEntryTo(
zip,
entries.forgeUniversalJar,
getLibraryPathWithoutMaven(mc, entries.forgeUniversalJar.fileName),
),
)
}
if (!profile.data) {
profile.data = {}
}
const mavenPaths = relative(mc.libraries, mavenLibVersionPath).split(sep)
const mavenVersion = mavenPaths.pop()
const mavenArtifact = mavenPaths.pop()
const mavenGroup = mavenPaths.join('.')
const mavenPath = `${mavenGroup}:${mavenArtifact}:${mavenVersion}`
const installerMaven = `${mavenPath}:installer`
profile.data.INSTALLER = {
client: `[${installerMaven}]`,
server: `[${installerMaven}]`,
}
if (entries.serverLzma) {
// forge version and mavens, compatible with twitch api
const serverMaven = `${mavenPath}:serverdata@lzma`
// override forge bin patch location
profile.data.BINPATCH.server = `[${serverMaven}]`
const serverBinPath = mc.getLibraryByPath(LibraryInfo.resolve(serverMaven).path)
await ensureFile(serverBinPath)
promises.push(extractEntryTo(zip, entries.serverLzma, serverBinPath))
}
if (entries.clientLzma) {
// forge version and mavens, compatible with twitch api
const clientMaven = `${mavenPath}:clientdata@lzma`
// override forge bin patch location
profile.data.BINPATCH.client = `[${clientMaven}]`
const clientBinPath = mc.getLibraryByPath(LibraryInfo.resolve(clientMaven).path)
await ensureFile(clientBinPath)
promises.push(extractEntryTo(zip, entries.clientLzma, clientBinPath))
}
if (entries.forgeJar) {
promises.push(
extractEntryTo(
zip,
entries.forgeJar,
getLibraryPathWithoutMaven(mc, entries.forgeJar.fileName),
),
)
}
if (entries.runBat) {
unpackData(entries.runBat)
}
if (entries.runSh) {
unpackData(entries.runSh)
}
if (entries.winArgs) {
unpackData(entries.winArgs)
}
if (entries.unixArgs) {
unpackData(entries.unixArgs)
}
if (entries.userJvmArgs) {
unpackData(entries.userJvmArgs)
}
promises.push(
writeFile(installJsonPath, JSON.stringify(profile)),
writeFile(versionJsonPath, JSON.stringify(versionJson)),
)
await Promise.all(promises)
return versionJson.id
}
export function isLegacyForgeInstallerEntries(
entries: ForgeInstallerEntries,
): entries is ForgeLegacyInstallerEntriesPattern {
return !!entries.legacyUniversalJar && !!entries.installProfileJson
}
export function isForgeInstallerEntries(
entries: ForgeInstallerEntries,
): entries is ForgeInstallerEntriesPattern {
return !!entries.installProfileJson && !!entries.versionJson
}
/**
* Walk the forge installer file to find key entries
* @param zip THe forge instal
* @param forgeVersion Forge version to install
*/
export async function walkForgeInstallerEntries(
zip: ZipFile,
forgeVersion: string,
): Promise<ForgeInstallerEntries> {
const [
forgeJar,
forgeUniversalJar,
shimJar,
clientLzma,
serverLzma,
installProfileJson,
versionJson,
legacyUniversalJar,
runSh,
runBat,
unixArgs,
userJvmArgs,
winArgs,
] = await filterEntries(zip, [
`maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}.jar`,
`maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-universal.jar`,
`maven/net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-shim.jar`,
'data/client.lzma',
'data/server.lzma',
'install_profile.json',
'version.json',
(e) =>
e.fileName === `forge-${forgeVersion}-universal.jar` ||
(e.fileName.startsWith('forge-') && e.fileName.endsWith('-universal.jar')) ||
e.fileName.startsWith('minecraftforge-universal-'), // legacy installer format
'data/run.sh',
'data/run.bat',
'data/unix_args.txt',
'data/user_jvm_args.txt',
'data/win_args.txt',
])
return {
forgeJar,
forgeUniversalJar,
shimJar,
clientLzma,
serverLzma,
installProfileJson,
versionJson,
legacyUniversalJar,
runSh,
runBat,
unixArgs,
userJvmArgs,
winArgs,
}
}
export class BadForgeInstallerJarError extends Error {
name = 'BadForgeInstallerJarError'
constructor(
public jarPath: string,
/**
* What entry in jar is missing
*/
public entry?: string,
) {
super(
entry
? `Missing entry ${entry} in forge installer jar: ${jarPath}`
: `Bad forge installer: ${jarPath}`,
)
}
}
async function downloadForgeJar(
forgeVersion: string,
mcVersion: string,
installer: RequiredVersion['installer'],
minecraft: MinecraftFolder,
options: InstallForgeOptions,
legacy?: boolean,
): Promise<string> {
const classifier = legacy ? 'universal' : 'installer'
const ext = legacy ? 'zip' : 'jar'
const path = installer
? installer.path
: `net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-${classifier}.${ext}`
let url: string
if (installer) {
try {
const parsedUrl = new URL(path)
url = parsedUrl.toString()
} catch (e) {
const forgeMavenPath = path.replace('/maven', '').replace('maven', '')
url = joinUrl(DEFAULT_FORGE_MAVEN, forgeMavenPath)
}
} else {
const forgeMavenPath = path.replace('/maven', '').replace('maven', '')
url = joinUrl(DEFAULT_FORGE_MAVEN, forgeMavenPath)
}
const library = VersionJson.resolveLibrary({
name: `net.minecraftforge:forge:${forgeVersion}:${classifier}`,
downloads: {
artifact: {
url,
path: `net/minecraftforge/forge/${forgeVersion}/forge-${forgeVersion}-${classifier}.${ext}`,
size: -1,
sha1: installer?.sha1 || '',
},
},
})!
const mavenHost = options.mavenHost ? normalizeArray(options.mavenHost) : []
if (mavenHost.indexOf(DEFAULT_FORGE_MAVEN) === -1) {
mavenHost.push(DEFAULT_FORGE_MAVEN)
}
const urls = resolveLibraryDownloadUrls(library, { ...options, mavenHost })
const installJarPath = minecraft.getLibraryByPath(library.path)
if (library.download.sha1) {
await diagnoseFile(
{
file: installJarPath,
algorithm: 'sha1',
expectedChecksum: library.download.sha1,
role: 'forgeInstaller',
hint: 'Problem on forge installer jar! Please consider to use Installer.installForge to fix.',
},
{ signal: options.signal, checksum: options.checksum },
).then(async (issue) => {
if (!issue) {
return
}
if (options.diagnose) {
throw new InstallError({
forge: {
minecraft: mcVersion,
version: forgeVersion,
},
})
}
await download({
url: urls,
destination: installJarPath,
...getDownloadBaseOptions(options),
tracker: onDownloadSingle(options.tracker, 'forge.installer', {
version: forgeVersion,
path: url,
}),
signal: options.signal,
})
})
} else {
await download({
url: urls,
destination: installJarPath,
...getDownloadBaseOptions(options),
tracker: onDownloadSingle(options.tracker, 'forge.installer', {
version: forgeVersion,
path: url,
}),
signal: options.signal,
})
}
return installJarPath
}
/**
* Install forge to target location.
* Installation task for forge with mcversion >= 1.13 requires java installed on your pc.
* @param version The forge version meta
* @returns The installed version name.
* @throws {@link BadForgeInstallerJarError}
*/
export async function installForge(
version: RequiredVersion,
minecraft: MinecraftLocation,
options: InstallForgeOptions = {},
): Promise<string> {
function getForgeArtifactVersion() {
const [_, minor] = version.mcversion.split('.')
const minorVersion = Number.parseInt(minor)
if (minorVersion >= 7 && minorVersion <= 8) {
return `${version.mcversion}-${version.version}-${version.mcversion}`
}
if (version.version.startsWith(version.mcversion)) {
return version.version
}
return `${version.mcversion}-${version.version}`
}
const forgeVersion = getForgeArtifactVersion()
const isLegacy = version.mcversion.startsWith('1.4.')
const mc = MinecraftFolder.from(minecraft)
const jarPath: string = await downloadForgeJar(
forgeVersion,
version.mcversion,
version.installer,
mc,
options,
isLegacy,
)
if (isLegacy) {
const forgeZip = await open(jarPath, { lazyEntries: true, autoClose: false })
const versionId = await installLegacyForgeFromUniversalZip(
forgeZip,
mc,
forgeVersion,
version.mcversion,
)
return versionId
}
const zip = await open(jarPath, { lazyEntries: true, autoClose: false })
const entries = await walkForgeInstallerEntries(zip, forgeVersion)
if (!entries.installProfileJson) {
throw new BadForgeInstallerJarError(jarPath, 'install_profile.json')
}
const profile: InstallProfile = await readEntry(zip, entries.installProfileJson)
.then((b) => b.toString())
.then(JSON.parse)
if (isForgeInstallerEntries(entries)) {
// new forge
const versionId = await unpackForgeInstaller(zip, entries, profile, mc, jarPath, options)
await installByProfile(profile, minecraft, options)
return versionId
} else if (isLegacyForgeInstallerEntries(entries)) {
// legacy forge
return installLegacyForgeFromZip(zip, entries, profile, mc, jarPath, options)
} else {
// bad forge
throw new BadForgeInstallerJarError(jarPath)
}
}