SurviePote 2/4: atlas Nebula (serveur SurviePote-26.3, distribution.json, sans binaires)

This commit is contained in:
kisakay
2026-10-18 18:44:09 +02:00
parent 14355ac2ad
commit ccaee11472
69 changed files with 8289 additions and 0 deletions
@@ -0,0 +1,91 @@
import StreamZip from 'node-stream-zip'
import { Type } from 'helios-distribution-types'
import { capitalize } from '../../../util/StringUtils.js'
import { FabricModJson } from '../../../model/fabric/FabricModJson.js'
import { MinecraftVersion } from '../../../util/MinecraftVersion.js'
import { BaseModStructure } from './Mod.struct.js'
import { UntrackedFilesOption } from '../../../model/nebula/ServerMeta.js'
export class FabricModStructure extends BaseModStructure<FabricModJson> {
constructor(
absoluteRoot: string,
relativeRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
untrackedFiles: UntrackedFilesOption[]
) {
super(absoluteRoot, relativeRoot, 'fabricmods', baseUrl, minecraftVersion, Type.FabricMod, untrackedFiles)
}
public getLoggerName(): string {
return 'FabricModStructure'
}
protected async getModuleId(name: string, path: string): Promise<string> {
const fmData = await this.getModMetadata(name, path)
let group
if (fmData.entrypoints != null) {
for (const t of ['main', 'client', 'server']) {
if (fmData.entrypoints[t] != null && fmData.entrypoints[t].length > 0) {
const entrypoint = fmData.entrypoints[t][0]
group = typeof entrypoint === 'string' ? entrypoint : entrypoint.value
break
}
}
// adapted from https://github.com/dscalzi/Claritas/blob/master/src/main/java/com/dscalzi/claritas/util/DataUtil.java
if (group != null) {
const packageBits = group.split('.')
const blacklist = ['common', 'util', 'internal', 'tweaker', 'tweak', 'client', ...['forge', 'fabric', 'bukkit', 'sponge'].filter(t => t !== fmData.id)]
// Note: Entry point is a fully qualified class name, hence why this adaptation pops immediately (drop class name).
while (packageBits.length > 0) {
packageBits.pop()
const term = packageBits[packageBits.length - 1]
if ((term !== fmData.id && !blacklist.includes(term)) || packageBits.length === 1 || (packageBits.length === 2 && term === fmData.id)) {
break
}
}
group = packageBits.join('.')
}
}
return this.generateMavenIdentifier(group || this.getDefaultGroup(), fmData.id, fmData.version)
}
protected async getModuleName(name: string, path: string): Promise<string> {
const fmData = await this.getModMetadata(name, path)
return capitalize(fmData.name || fmData.id)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected processZip(zip: StreamZip, name: string, path: string): FabricModJson {
let raw: Buffer | undefined
try {
raw = zip.entryDataSync('fabric.mod.json')
} catch(err) {
// ignored
}
if (raw) {
try {
const parsed = JSON.parse(raw.toString()) as FabricModJson
this.modMetadata[name] = parsed
} catch (err) {
this.logger.error(`FabricMod ${name} contains an invalid fabric.mod.json file.`)
}
} else {
this.logger.error(`FabricMod ${name} does not contain fabric.mod.json file.`)
}
const crudeInference = this.attemptCrudeInference(name)
if(this.modMetadata[name] == null) {
this.modMetadata[name] = ({
id: crudeInference.name.toLowerCase(),
name: crudeInference.name,
version: crudeInference.version
})
}
return this.modMetadata[name]
}
}
@@ -0,0 +1,65 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Stats } from 'fs'
import { Type, Module } from 'helios-distribution-types'
import { URL } from 'url'
import { ModuleStructure } from './Module.struct.js'
import { readdir, stat } from 'fs/promises'
import { join, resolve, sep } from 'path'
import { MinecraftVersion } from '../../../util/MinecraftVersion.js'
import { UntrackedFilesOption } from '../../../model/nebula/ServerMeta.js'
export class MiscFileStructure extends ModuleStructure {
constructor(
absoluteRoot: string,
relativeRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
untrackedFiles: UntrackedFilesOption[]
) {
super(absoluteRoot, relativeRoot, 'files', baseUrl, minecraftVersion, Type.File, untrackedFiles)
}
public getLoggerName(): string {
return 'MiscFileStructure'
}
public async getSpecModel(): Promise<Module[]> {
if (this.resolvedModels == null) {
this.resolvedModels = await this.recursiveModuleScan(this.containerDirectory)
}
return this.resolvedModels
}
protected async recursiveModuleScan(dir: string): Promise<Module[]> {
let acc: Module[] = []
const subdirs = await readdir(dir)
for (const file of subdirs) {
const filePath = resolve(dir, file)
const stats = await stat(filePath)
if (stats.isDirectory()) {
acc = acc.concat(await this.recursiveModuleScan(filePath))
} else {
if(!this.FILE_NAME_BLACKLIST.includes(file)) {
acc.push(await this.parseModule(file, filePath, stats))
}
}
}
return acc
}
protected async getModuleId(name: string, path: string): Promise<string> {
return name
}
protected async getModuleName(name: string, path: string): Promise<string> {
return name
}
protected async getModuleUrl(name: string, path: string, stats: Stats): Promise<string> {
return new URL(join(this.relativeRoot, ...path.substr(this.containerDirectory.length+1).split(sep)), this.baseUrl).toString()
}
protected async getModulePath(name: string, path: string, stats: Stats): Promise<string | null> {
return path.substr(this.containerDirectory.length+1).replace(/\\/g, '/')
}
}
@@ -0,0 +1,42 @@
import { Type } from 'helios-distribution-types'
import { VersionSegmented } from '../../../util/VersionSegmented.js'
import { MinecraftVersion } from '../../../util/MinecraftVersion.js'
import { BaseModStructure } from './Mod.struct.js'
import { LibraryType } from '../../../model/claritas/ClaritasLibraryType.js'
import { ClaritasException } from './Module.struct.js'
import { UntrackedFilesOption } from '../../../model/nebula/ServerMeta.js'
export abstract class BaseForgeModStructure<T> extends BaseModStructure<T> implements VersionSegmented {
protected readonly EXAMPLE_MOD_ID = 'examplemod'
constructor(
absoluteRoot: string,
relativeRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
untrackedFiles: UntrackedFilesOption[]
) {
super(absoluteRoot, relativeRoot, 'forgemods', baseUrl, minecraftVersion, Type.ForgeMod, untrackedFiles)
}
public abstract isForVersion(version: MinecraftVersion, libraryVersion: string): boolean
protected getClaritasExceptions(): ClaritasException[] {
return [{
exceptionName: 'optifine',
proxyMetadata: {
group: 'net.optifine'
}
}]
}
protected getClaritasType(): LibraryType {
return LibraryType.FORGE
}
protected discernResult(claritasValue: string | undefined, crudeInference: string): string {
return (claritasValue == null || claritasValue == '') ? crudeInference : claritasValue
}
}
@@ -0,0 +1,46 @@
import { ModuleStructure } from './Module.struct.js'
import { Type, TypeMetadata } from 'helios-distribution-types'
import { Stats } from 'fs'
import { join } from 'path'
import { URL } from 'url'
import { MinecraftVersion } from '../../../util/MinecraftVersion.js'
import { UntrackedFilesOption } from '../../../model/nebula/ServerMeta.js'
export class LibraryStructure extends ModuleStructure {
constructor(
absoluteRoot: string,
relativeRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
untrackedFiles: UntrackedFilesOption[]
) {
super(absoluteRoot, relativeRoot, 'libraries', baseUrl, minecraftVersion, Type.Library, untrackedFiles, (name: string) => {
return name.toLowerCase().endsWith(TypeMetadata[this.type].defaultExtension!)
})
}
public getLoggerName(): string {
return 'LibraryStructure'
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async getModuleId(name: string, path: string): Promise<string> {
const inference = this.attemptCrudeInference(name)
return this.generateMavenIdentifier(this.getDefaultGroup(), inference.name, inference.version)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async getModuleName(name: string, path: string): Promise<string> {
const inference = this.attemptCrudeInference(name)
return inference.name
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async getModuleUrl(name: string, path: string, stats: Stats): Promise<string> {
return new URL(join(this.relativeRoot, name), this.baseUrl).toString()
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async getModulePath(name: string, path: string, stats: Stats): Promise<string | null> {
return null
}
}
@@ -0,0 +1,66 @@
import { Stats } from 'fs'
import { Module } from 'helios-distribution-types'
import StreamZip from 'node-stream-zip'
import { join } from 'path'
import { URL } from 'url'
import { ToggleableModuleStructure } from './ToggleableModule.struct.js'
export abstract class BaseModStructure<T> extends ToggleableModuleStructure {
protected modMetadata: {[property: string]: T | undefined} = {}
public async getSpecModel(): Promise<Module[]> {
// Sort by file name to allow control of load order.
return (await super.getSpecModel()).sort((a, b) => {
const aFileName = a.artifact.url.substring(a.artifact.url.lastIndexOf('/')+1)
const bFileName = b.artifact.url.substring(b.artifact.url.lastIndexOf('/')+1)
return aFileName.localeCompare(bFileName)
})
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async getModuleUrl(name: string, path: string, stats: Stats): Promise<string> {
return new URL(join(this.relativeRoot, this.getActiveNamespace(), name), this.baseUrl).toString()
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async getModulePath(name: string, path: string, stats: Stats): Promise<string | null> {
return null
}
protected getModMetadata(name: string, path: string): Promise<T> {
return new Promise((resolve, reject) => {
if (!Object.prototype.hasOwnProperty.call(this.modMetadata, name)) {
const zip = new StreamZip({
file: path,
storeEntries: true
})
zip.on('error', err => {
this.logger.error(`Failure while processing ${path}`)
reject(err)
})
zip.on('ready', () => {
try {
const res = this.processZip(zip, name, path)
zip.close()
resolve(res)
return
} catch(err) {
zip.close()
reject(err)
return
}
})
} else {
resolve(this.modMetadata[name]!)
return
}
})
}
protected abstract processZip(zip: StreamZip, name: string, path: string): T
}
@@ -0,0 +1,221 @@
import { minimatch } from 'minimatch'
import { createHash } from 'crypto'
import { pathExists } from 'fs-extra/esm'
import { Stats } from 'fs'
import { lstat, readdir, readFile } from 'fs/promises'
import { Artifact, Module, Type, TypeMetadata } from 'helios-distribution-types'
import { resolve } from 'path'
import { BaseModelStructure } from '../BaseModel.struct.js'
import { LibraryType } from '../../../model/claritas/ClaritasLibraryType.js'
import { ClaritasResult, ClaritasModuleMetadata } from '../../../model/claritas/ClaritasResult.js'
import { ClaritasWrapper } from '../../../util/java/ClaritasWrapper.js'
import { MinecraftVersion } from '../../../util/MinecraftVersion.js'
import { UntrackedFilesOption } from '../../../model/nebula/ServerMeta.js'
export interface ModuleCandidate {
file: string
filePath: string
stats: Stats
}
export interface ClaritasException {
exceptionName: string
proxyMetadata: ClaritasModuleMetadata
}
export abstract class ModuleStructure extends BaseModelStructure<Module> {
private readonly crudeRegex = /(.+?)-(.+).[jJ][aA][rR]/
protected readonly DEFAULT_VERSION = '0.0.0'
protected readonly FILE_NAME_BLACKLIST = [
'.gitkeep'
]
protected untrackedFilePatterns: string[] // List of glob patterns.
protected claritasResult!: ClaritasResult
constructor(
absoluteRoot: string,
relativeRoot: string,
structRoot: string,
baseUrl: string,
protected minecraftVersion: MinecraftVersion,
protected type: Type,
untrackedFiles: UntrackedFilesOption[],
protected filter?: ((name: string, path: string, stats: Stats) => boolean)
) {
super(absoluteRoot, relativeRoot, structRoot, baseUrl)
this.untrackedFilePatterns = this.determineUntrackedFiles(structRoot, untrackedFiles)
}
public async getSpecModel(): Promise<Module[]> {
if (this.resolvedModels == null) {
this.resolvedModels = await this._doModuleRetrieval(await this._doModuleDiscovery(this.containerDirectory))
}
return this.resolvedModels
}
protected getDefaultGroup(): string {
return `generated.${this.type.toLowerCase()}`
}
protected generateMavenIdentifier(group: string, id: string, version: string): string {
return `${group}:${id}:${version}@${TypeMetadata[this.type].defaultExtension}`
}
protected attemptCrudeInference(name: string): { name: string, version: string } {
const result = this.crudeRegex.exec(name)
if(result != null) {
return {
name: result[1],
version: result[2]
}
} else {
return {
name: name.substring(0, name.lastIndexOf('.')),
version: this.DEFAULT_VERSION
}
}
}
protected getClaritasGroup(path: string): string {
return this.claritasResult[path]?.group || this.getDefaultGroup()
}
protected getClaritasExceptions(): ClaritasException[] {
return []
}
protected getClaritasType(): LibraryType | null {
return null
}
protected abstract getModuleId(name: string, path: string): Promise<string>
protected abstract getModuleName(name: string, path: string): Promise<string>
protected abstract getModuleUrl(name: string, path: string, stats: Stats): Promise<string>
protected abstract getModulePath(name: string, path: string, stats: Stats): Promise<string | null>
protected async parseModule(file: string, filePath: string, stats: Stats): Promise<Module> {
const artifact: Artifact = {
size: stats.size,
url: await this.getModuleUrl(file, filePath, stats)
}
const relativeToContainer = filePath.substr(this.containerDirectory.length+1)
const untrackedByPattern = this.isFileUntracked(relativeToContainer)
if(!untrackedByPattern) {
const buf = await readFile(filePath)
artifact.MD5 = createHash('md5').update(buf).digest('hex')
} else {
this.logger.debug(`File ${relativeToContainer} is untracked. Matching pattern: ${untrackedByPattern}`)
}
const mdl: Module = {
id: await this.getModuleId(file, filePath),
name: await this.getModuleName(file, filePath),
type: this.type,
artifact
}
const pth = await this.getModulePath(file, filePath, stats)
if (pth) {
mdl.artifact.path = pth
}
return mdl
}
protected async _doModuleDiscovery(scanDirectory: string): Promise<ModuleCandidate[]> {
const moduleCandidates: ModuleCandidate[] = []
if (await pathExists(scanDirectory)) {
const files = await readdir(scanDirectory)
for (const file of files) {
const filePath = resolve(scanDirectory, file)
const stats = await lstat(filePath)
if (stats.isFile()) {
if(!this.FILE_NAME_BLACKLIST.includes(file)) {
if(this.filter == null || this.filter(file, filePath, stats)) {
moduleCandidates.push({file, filePath, stats})
}
}
}
}
}
return moduleCandidates
}
protected async invokeClaritas(moduleCandidates: ModuleCandidate[]): Promise<void> {
if(this.getClaritasType() != null) {
const claritasExecutor = new ClaritasWrapper(this.absoluteRoot)
let claritasCandidates = moduleCandidates
const exceptionCandidates: [ModuleCandidate, ClaritasException][] = []
for(const exception of this.getClaritasExceptions()) {
const exceptionCandidate = moduleCandidates.find((value) => value.file.toLowerCase().includes(exception.exceptionName))
if(exceptionCandidate != null) {
exceptionCandidates.push([exceptionCandidate, exception])
claritasCandidates = claritasCandidates.filter((value) => !value.file.toLowerCase().includes(exception.exceptionName))
}
}
this.claritasResult = await claritasExecutor.execute(
this.getClaritasType()!,
this.minecraftVersion,
claritasCandidates.map(entry => entry.filePath)
)
if(this.claritasResult == null) {
this.logger.error('Failed to process Claritas result!')
} else {
for(const [candidate, exception] of exceptionCandidates) {
this.claritasResult[candidate.filePath] = exception.proxyMetadata
}
}
}
}
protected async _doModuleRetrieval(moduleCandidates: ModuleCandidate[], options?: {
preProcess?: (candidate: ModuleCandidate) => void
postProcess?: (module: Module) => void
}): Promise<Module[]> {
const accumulator: Module[] = []
if(moduleCandidates.length > 0) {
// Invoke Claritas and attach result to class.
await this.invokeClaritas(moduleCandidates)
// Process Modules
for(const candidate of moduleCandidates) {
options?.preProcess?.(candidate)
const mdl = await this.parseModule(candidate.file, candidate.filePath, candidate.stats)
options?.postProcess?.(mdl)
accumulator.push(mdl)
}
}
return accumulator
}
protected determineUntrackedFiles(targetStructRoot: string, untrackedFileOptions?: UntrackedFilesOption[]): string[] {
if(untrackedFileOptions) {
return untrackedFileOptions
.filter(x => x.appliesTo.includes(targetStructRoot))
.reduce((acc, cur) => acc.concat(cur.patterns), [] as string[])
}
return []
}
// Will return the matching pattern, undefined if no match.
protected isFileUntracked(pathRelativeToContainer: string): string | undefined {
return this.untrackedFilePatterns.find(pattern => minimatch(pathRelativeToContainer, pattern))
}
}
@@ -0,0 +1,85 @@
import { ModuleStructure, ModuleCandidate } from './Module.struct.js'
import { Type, Module } from 'helios-distribution-types'
import { mkdirs } from 'fs-extra/esm'
import { Stats } from 'fs'
import { resolve } from 'path'
import { MinecraftVersion } from '../../../util/MinecraftVersion.js'
import { UntrackedFilesOption } from '../../../model/nebula/ServerMeta.js'
export enum ToggleableNamespace {
REQUIRED = 'required',
OPTIONAL_ON = 'optionalon',
OPTIONAL_OFF = 'optionaloff'
}
export interface ToggleableModuleCandidate extends ModuleCandidate {
namespace: ToggleableNamespace
}
export abstract class ToggleableModuleStructure extends ModuleStructure {
private activeNamespace: string | undefined
constructor(
absoluteRoot: string,
relativeRoot: string,
structRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
type: Type,
untrackedFiles: UntrackedFilesOption[],
filter?: ((name: string, path: string, stats: Stats) => boolean)
) {
super(absoluteRoot, relativeRoot, structRoot, baseUrl, minecraftVersion, type, untrackedFiles, filter)
}
public async init(): Promise<void> {
await super.init()
for(const namespace of Object.values(ToggleableNamespace)) {
await mkdirs(resolve(this.containerDirectory, namespace))
}
}
public async getSpecModel(): Promise<Module[]> {
if (this.resolvedModels == null) {
const moduleCandidates: ToggleableModuleCandidate[] = []
for(const value of Object.values(ToggleableNamespace)) {
moduleCandidates.push(...(await super._doModuleDiscovery(resolve(this.containerDirectory, value))).map(val => ({...val, namespace: value})))
}
this.resolvedModels = await this._doModuleRetrieval(moduleCandidates, {
preProcess: (candidate) => {
this.activeNamespace = (candidate as ToggleableModuleCandidate).namespace
},
postProcess: (module) => {
this.getNamespaceMapper(this.activeNamespace as ToggleableNamespace)(module)
}
})
// Cleanup
this.activeNamespace = undefined
}
return this.resolvedModels
}
protected getActiveNamespace(): string {
return this.activeNamespace || ''
}
protected getNamespaceMapper(namespace: ToggleableNamespace): (x: Module) => void {
switch(namespace) {
case ToggleableNamespace.REQUIRED:
return (): void => { /* do nothing */ }
case ToggleableNamespace.OPTIONAL_ON:
return (x): void => { x.required = { value: false } }
case ToggleableNamespace.OPTIONAL_OFF:
return (x): void => { x.required = { value: false, def: false } }
}
}
}
@@ -0,0 +1,153 @@
import StreamZip from 'node-stream-zip'
import toml from 'toml'
import { capitalize } from '../../../../util/StringUtils.js'
import { VersionUtil } from '../../../../util/VersionUtil.js'
import { ModsToml } from '../../../../model/forge/ModsToml.js'
import { BaseForgeModStructure } from '../ForgeMod.struct.js'
import { MinecraftVersion } from '../../../../util/MinecraftVersion.js'
import { UntrackedFilesOption } from '../../../../model/nebula/ServerMeta.js'
export class ForgeModStructure113 extends BaseForgeModStructure<ModsToml> {
public static readonly IMPLEMENTATION_VERSION_REGEX = /^Implementation-Version: (.+)[\r\n]/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public static isForVersion(version: MinecraftVersion, libraryVersion: string): boolean {
return VersionUtil.isVersionAcceptable(version, [13, 14, 15, 16, 17, 18, 19, 20, 21])
}
constructor(
absoluteRoot: string,
relativeRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
untrackedFiles: UntrackedFilesOption[]
) {
super(absoluteRoot, relativeRoot, baseUrl, minecraftVersion, untrackedFiles)
}
public isForVersion(version: MinecraftVersion, libraryVersion: string): boolean {
return ForgeModStructure113.isForVersion(version, libraryVersion)
}
public getLoggerName(): string {
return 'ForgeModStructure (1.13)'
}
protected async getModuleId(name: string, path: string): Promise<string> {
const fmData = await this.getModMetadata(name, path)
return this.generateMavenIdentifier(this.getClaritasGroup(path), fmData.mods[0].modId, fmData.mods[0].version)
}
protected async getModuleName(name: string, path: string): Promise<string> {
return capitalize((await this.getModMetadata(name, path)).mods[0].displayName)
}
protected processZip(zip: StreamZip, name: string, path: string): ModsToml {
// Optifine is a tweak that can be loaded as a forge mod. It does not
// appear to contain a mcmod.info class. This a special case we will
// account for.
if (name.toLowerCase().includes('optifine')) {
// Read zip for changelog.txt
let changelogBuf: Buffer
try {
changelogBuf = zip.entryDataSync('changelog.txt')
} catch(err) {
throw new Error('Failed to read OptiFine changelog.')
}
const info = changelogBuf.toString().split('\n')[0].trim()
const version = info.split(' ')[1]
this.modMetadata[name] = ({
modLoader: 'javafml',
loaderVersion: '',
mods: [{
modId: 'optifine',
version,
displayName: 'OptiFine',
description: `OptiFine is a Minecraft optimization mod.
It allows Minecraft to run faster and look better with full support for shaders, HD textures and many configuration options.`
}]
})
return this.modMetadata[name]
}
let raw: Buffer | undefined
try {
raw = zip.entryDataSync('META-INF/mods.toml')
} catch(err) {
// ignored
}
if (raw) {
try {
const parsed = toml.parse(raw.toString()) as ModsToml
this.modMetadata[name] = parsed
} catch (err) {
this.logger.error(`ForgeMod ${name} contains an invalid mods.toml file.`)
}
} else {
this.logger.error(`ForgeMod ${name} does not contain mods.toml file.`)
}
const cRes = this.claritasResult?.[path]
if(cRes == null) {
this.logger.error(`Claritas failed to yield metadata for ForgeMod ${name}!`)
this.logger.error('Is this mod malformatted or does Claritas need an update?')
}
const claritasId = cRes?.id
const crudeInference = this.attemptCrudeInference(name)
if(this.modMetadata[name] != null) {
const x = this.modMetadata[name]
for(const entry of x.mods) {
if(entry.modId === this.EXAMPLE_MOD_ID) {
entry.modId = this.discernResult(claritasId, crudeInference.name.toLowerCase())
entry.displayName = crudeInference.name
}
if (entry.version === '${file.jarVersion}') {
let version = crudeInference.version
try {
const manifest = zip.entryDataSync('META-INF/MANIFEST.MF')
const keys = manifest.toString().split('\n')
// this.logger.debug(keys)
for (const key of keys) {
const match = ForgeModStructure113.IMPLEMENTATION_VERSION_REGEX.exec(key)
if (match != null) {
version = match[1]
}
}
this.logger.debug(`ForgeMod ${name} contains a version wildcard, inferring ${version}`)
} catch {
this.logger.debug(`ForgeMod ${name} contains a version wildcard yet no MANIFEST.MF.. Defaulting to ${version}`)
}
entry.version = version
}
}
} else {
this.modMetadata[name] = ({
modLoader: 'javafml',
loaderVersion: '',
mods: [{
modId: this.discernResult(claritasId, crudeInference.name.toLowerCase()),
version: crudeInference.version,
displayName: crudeInference.name,
description: ''
}]
})
}
return this.modMetadata[name]
}
}
@@ -0,0 +1,154 @@
import StreamZip from 'node-stream-zip'
import { capitalize } from '../../../../util/StringUtils.js'
import { VersionUtil } from '../../../../util/VersionUtil.js'
import { McModInfo } from '../../../../model/forge/McModInfo.js'
import { McModInfoList } from '../../../../model/forge/McModInfoList.js'
import { BaseForgeModStructure } from '../ForgeMod.struct.js'
import { MinecraftVersion } from '../../../../util/MinecraftVersion.js'
import { ForgeModType_1_7 } from '../../../../model/claritas/ClaritasResult.js'
import { UntrackedFilesOption } from '../../../../model/nebula/ServerMeta.js'
export class ForgeModStructure17 extends BaseForgeModStructure<McModInfo> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public static isForVersion(version: MinecraftVersion, libraryVersion: string): boolean {
return VersionUtil.isVersionAcceptable(version, [7, 8, 9, 10, 11, 12])
}
constructor(
absoluteRoot: string,
relativeRoot: string,
baseUrl: string,
minecraftVersion: MinecraftVersion,
untrackedFiles: UntrackedFilesOption[]
) {
super(absoluteRoot, relativeRoot, baseUrl, minecraftVersion, untrackedFiles)
}
public isForVersion(version: MinecraftVersion, libraryVersion: string): boolean {
return ForgeModStructure17.isForVersion(version, libraryVersion)
}
public getLoggerName(): string {
return 'ForgeModStructure (1.7)'
}
protected async getModuleId(name: string, path: string): Promise<string> {
const fmData = await this.getModMetadata(name, path)
return this.generateMavenIdentifier(this.getClaritasGroup(path), fmData.modid, fmData.version)
}
protected async getModuleName(name: string, path: string): Promise<string> {
return capitalize((await this.getModMetadata(name, path)).name)
}
private isMalformedVersion(version: string): boolean {
// Ex. empty, @VERSION@, ${version}
return version.trim().length === 0 || version.includes('@') || version.includes('$')
}
protected processZip(zip: StreamZip, name: string, path: string): McModInfo {
// Optifine is a tweak that can be loaded as a forge mod. It does not
// appear to contain a mcmod.info class. This a special case we will
// account for.
if (name.toLowerCase().includes('optifine')) {
// Read zip for changelog.txt
let changelogBuf: Buffer
try {
changelogBuf = zip.entryDataSync('changelog.txt')
} catch(err) {
throw new Error('Failed to read OptiFine changelog.')
}
const info = changelogBuf.toString().split('\n')[0].trim()
const version = info.split(' ')[1]
this.modMetadata[name] = ({
modid: 'optifine',
name: info,
version,
mcversion: version.substring(0, version.indexOf('_'))
}) as McModInfo
return this.modMetadata[name]
}
let raw: Buffer | undefined
try {
raw = zip.entryDataSync('mcmod.info')
} catch(err) {
// ignored
}
if (raw) {
// Assuming the main mod will be the first entry in this file.
try {
const resolved = JSON.parse(raw.toString()) as (McModInfoList | McModInfo[])
if (Object.prototype.hasOwnProperty.call(resolved, 'modListVersion')) {
this.modMetadata[name] = (resolved as McModInfoList).modList[0]
} else {
this.modMetadata[name] = (resolved as McModInfo[])[0]
}
} catch (err) {
this.logger.error(`ForgeMod ${name} contains an invalid mcmod.info file.`)
}
} else {
this.logger.warn(`ForgeMod ${name} does not contain mcmod.info file.`)
}
const cRes = this.claritasResult[path]
if(cRes == null) {
this.logger.error(`Claritas failed to yield metadata for ForgeMod ${name}!`)
this.logger.error('Is this mod malformated or does Claritas need an update?')
} else {
switch(cRes.modType!) {
case ForgeModType_1_7.CORE_MOD:
this.logger.info(`CORE_MOD Discovered: ForgeMod ${name} has no @Mod annotation. Metadata inference capabilities are limited.`)
break
case ForgeModType_1_7.TWEAKER:
this.logger.info(`TWEAKER Discovered: ForgeMod ${name} has no @Mod annotation. Metadata inference capabilities may be limited.`)
break
case ForgeModType_1_7.UNKNOWN:
this.logger.error(`Jar file ${name} is not a ForgeMod. Is it a library?`)
break
}
}
const claritasId = cRes?.id
const claritasVersion = cRes?.version
const claritasName = cRes?.name
// Validate
const crudeInference = this.attemptCrudeInference(name)
if(this.modMetadata[name] != null) {
const x = this.modMetadata[name]
if(x.modid == null || x.modid === '' || x.modid === this.EXAMPLE_MOD_ID) {
x.modid = this.discernResult(claritasId, crudeInference.name.toLowerCase())
x.name = this.discernResult(claritasName, crudeInference.name)
}
if(this.modMetadata[name].version != null) {
const isMalformedVersion = this.isMalformedVersion(this.modMetadata[name].version)
if(isMalformedVersion) {
x.version = this.discernResult(claritasVersion, crudeInference.version)
}
} else {
x.version = this.discernResult(claritasVersion, crudeInference.version)
}
} else {
this.modMetadata[name] = ({
modid: this.discernResult(claritasId, crudeInference.name.toLowerCase()),
name: this.discernResult(claritasName, crudeInference.name),
version: this.discernResult(claritasVersion, crudeInference.version)
}) as McModInfo
}
return this.modMetadata[name]
}
}