Merge pull request #834 from Cooldude2606/fix/mod-dep-parser

Fix mod dependency parser breaking with inconsistent spaces
This commit is contained in:
Daniel authored and GitHub committed 2026-02-10 16:34:10 +01:00
commit dd5e3b876e
10 files changed
+340 -259

No files matched your search

+1 -1
View File
@@ -104,7 +104,7 @@ async function main() {
removeBuildArtifacts(); removeBuildArtifacts();
removeTestArtifacts(); removeTestArtifacts();
}) })
.command("fast", "Remove all build artifacts", () => {}, argv => { .command("$0", "Remove all build artifacts", () => {}, argv => {
DRY = argv.dry; DRY = argv.dry;
removeBuildArtifacts(); removeBuildArtifacts();
}) })
+1 -3
View File
@@ -15,9 +15,7 @@
"ci-cover": "nyc --reporter=lcovonly pnpm run-script test", "ci-cover": "nyc --reporter=lcovonly pnpm run-script test",
"lint": "eslint packages plugins test", "lint": "eslint packages plugins test",
"lint-fix": "eslint --fix packages plugins test", "lint-fix": "eslint --fix packages plugins test",
"clean": "node ./clean.js fast", "clean": "node ./clean.js",
"clean-tests": "node ./clean.js tests",
"clean-all": "node ./clean.js all",
"docs": "typedoc", "docs": "typedoc",
"bundle-dependencies": "bundle-dependencies" "bundle-dependencies": "bundle-dependencies"
}, },
+62 -38
View File
@@ -614,22 +614,21 @@ export default class ControlConnection extends BaseConnection {
return modInfos; return modInfos;
} }
// eslint-disable-next-line complexity
async handleModDependencyResolveRequest(request: lib.ModDependencyResolveRequest) { async handleModDependencyResolveRequest(request: lib.ModDependencyResolveRequest) {
const {factorioVersion, checkForUpdates} = request; const {factorioVersion, checkForUpdates} = request;
const searchQueue = [...request.mods]; const searchQueue = [...request.mods];
const localInfos = [...this._controller.modStore.mods()]; const localInfos = [...this._controller.modStore.mods()];
const _builtInModNames = lib.ModPack.getBuiltinModNames(factorioVersion); const builtInModNames = lib.ModPack.getBuiltinModNames(factorioVersion);
const builtInModNames = new Set(_builtInModNames); const skipSearch = new Set(builtInModNames);
const skipSearch = new Set(_builtInModNames);
type ModPortalModType = InstanceType<typeof lib.ModPortalGetAllRequest.Response>["mods"][number]; type ModPortalModType = InstanceType<typeof lib.ModPortalGetAllRequest.Response>["mods"][number];
type ModPortalReleaseType = NonNullable<ModPortalModType["releases"]>[number]; type ModPortalReleaseType = NonNullable<ModPortalModType["releases"]>[number];
const dependencyRequirements = new Map<string, lib.ModVersionRange>(); const dependencyRequirements = new Map<string, lib.ModVersionRange>();
const optionalRequirements = new Map<string, lib.ModVersionRange>(); const optionalRequirements = new Map<string, lib.ModVersionRange>();
const candidateReleases = new Map<string, lib.ModInfo>(); const candidateReleases = new Map<string, lib.ModInfo>();
const incompatible = new Set<string>(); const errors = new Map<string, lib.ModDependencyResolveErrors>();
const invalid = new Set<string>();
const _modPortalReleases = new Map<string, ModPortalModType | null>(); const _modPortalReleases = new Map<string, ModPortalModType | null>();
async function fetchModReleases(modName: string) { async function fetchModReleases(modName: string) {
@@ -650,10 +649,44 @@ export default class ControlConnection extends BaseConnection {
return releases; return releases;
} }
function selectModRelease(releases: ModPortalModType | null, versionRange: lib.ModVersionRange) {
if (!releases || !releases.releases) {
return null;
}
// Select the latest matching version
const release = releases.releases
.filter(info => versionRange.testVersion(info.version))
.reduce<ModPortalReleaseType | undefined>((max, cur) => (
max && lib.integerFullVersion(max.version) > lib.integerFullVersion(cur.version) ? max : cur
), undefined);
if (!release) {
return null;
}
// Create the mod info class from the selected
try {
return lib.ModInfo.fromJSON({
...release.info_json, // includes dependencies
sha1: release.sha1,
version: release.version,
name: releases.name,
author: releases.owner,
title: releases.title,
});
} catch {
// Can error if there are invalid dependencies
errors.set(releases.name, "invalidDependency");
return null;
}
}
while (searchQueue.length > 0) { while (searchQueue.length > 0) {
// Dequeue the next mod, skip if incompatible
const mod = searchQueue.shift()!; const mod = searchQueue.shift()!;
if (mod.incompatible) { if (mod.incompatible) {
incompatible.add(mod.name); errors.set(mod.name, "incompatible");
continue; continue;
} }
@@ -674,13 +707,13 @@ export default class ControlConnection extends BaseConnection {
versionRange.combineVersion(mod.version); versionRange.combineVersion(mod.version);
if (!versionRange.valid) { if (!versionRange.valid) {
candidateReleases.delete(mod.name); candidateReleases.delete(mod.name);
invalid.add(mod.name); errors.set(mod.name, "unsatisfiable");
} }
} }
// Do not add dependencies for invalids, optionals, skips, or valid candidates // Do not add dependencies for errors, skips, optionals, or valid candidates
const existingCandidate = candidateReleases.get(mod.name); const existingCandidate = candidateReleases.get(mod.name);
if (invalid.has(mod.name) || optionalRequirements.has(mod.name) || skipSearch.has(mod.name) || ( if (errors.has(mod.name) || skipSearch.has(mod.name) || optionalRequirements.has(mod.name) || (
existingCandidate && versionRange.testVersion(existingCandidate.version) existingCandidate && versionRange.testVersion(existingCandidate.version)
)) { )) {
continue; continue;
@@ -695,28 +728,11 @@ export default class ControlConnection extends BaseConnection {
// Check if a mod poral version fits the requirements // Check if a mod poral version fits the requirements
if (!candidate || checkForUpdates) { if (!candidate || checkForUpdates) {
const modReleases = await fetchModReleases(mod.name); const releases = await fetchModReleases(mod.name);
if (modReleases && modReleases.releases) { const release = selectModRelease(releases, versionRange);
const release = modReleases.releases // We only select the mod portal release if it is more recent than the local candidate
.filter(info => ( if (release && (!candidate || release.integerVersion > candidate.integerVersion)) {
info.info_json.factorio_version === factorioVersion candidate = release;
&& versionRange.testVersion(info.version)
))
.reduce<ModPortalReleaseType | undefined>((max, cur) => (
max && lib.integerFullVersion(max.version) > lib.integerFullVersion(cur.version) ? max : cur
), undefined);
// We only select the mod portal release if it is more recent than the local candidate
if (release && (!candidate || lib.integerFullVersion(release.version) > candidate.integerVersion)) {
candidate = lib.ModInfo.fromJSON({
...release.info_json, // Also includes dependences
sha1: release.sha1,
version: release.version,
name: modReleases.name,
author: modReleases.owner,
title: modReleases.title,
});
}
} }
} }
@@ -732,14 +748,22 @@ export default class ControlConnection extends BaseConnection {
} }
} }
// Add the not found dependencies as errors
for (const modName of dependencyRequirements.keys()) {
if (!candidateReleases.has(modName) && !errors.has(modName)) {
errors.set(modName, "notFound");
}
}
// Remove incompatible dependencies if they aren't required by others
for (const [modName, error] of errors) {
if (error === "incompatible" && !dependencyRequirements.has(modName)) {
errors.delete(modName);
}
}
return new lib.ModDependencyResolveRequest.Response( return new lib.ModDependencyResolveRequest.Response(
[...candidateReleases.values()], [...candidateReleases.values()], errors,
[...invalid.values(), ...[...incompatible.values()].filter(mod => (
candidateReleases.has(mod) || builtInModNames.has(mod)
))],
[...dependencyRequirements.keys()].filter(mod => (
!candidateReleases.has(mod) && !incompatible.has(mod) && !invalid.has(mod)
)),
); );
} }
+26 -42
View File
@@ -22,11 +22,12 @@ const UnsatisfiedSeverity: Record<ModDependencyUnsatisfiedReason, number> = {
"incompatible": 1, "missing_dependency": 2, "wrong_version": 3, "incompatible": 1, "missing_dependency": 2, "wrong_version": 3,
}; };
const lettersRegex = /^[a-zA-Z]+$/; const depSpecRegex = /^(?:(\?|\(\?\)|!|~|\+) *)?(.+?)(?: *([<>]=?|=) *([0-9.]+))?$/;
export class ModDependency { export class ModDependency {
public type: ModDependencyType; public spec: string;
public name: string; public name: string;
public type: ModDependencyType;
public version: ModVersionEquality | undefined; public version: ModVersionEquality | undefined;
static getTypeFromPrefix(prefix: string): ModDependencyType { static getTypeFromPrefix(prefix: string): ModDependencyType {
@@ -42,50 +43,27 @@ export class ModDependency {
case "": case "":
return "required"; return "required";
default: default:
throw new Error(`Invalid dependency prefix: ${prefix}`); throw new Error(`Invalid dependency prefix "${prefix}"`);
} }
} }
constructor ( constructor (
public specification: string, specification: string,
) { ) {
const parts = specification.split(" "); const match = depSpecRegex.exec(specification);
if (match === null) {
// Fix mods which include spaces in their name, joins consecutive words together throw new Error(`Invalid dependency specification "${specification}"`);
let index = 0;
while (index < parts.length - 1) {
const current = parts[index];
const next = parts[index + 1];
if (lettersRegex.test(current) && lettersRegex.test(next)) {
parts[index] = `${current} ${next}`;
parts.splice(index + 1, 1);
} else {
index += 1;
}
} }
// Parse the dependency specification // Expand the match to the different parts
switch (parts.length) { const [spec, type, name, equality, version] = match;
case 1: this.type = ModDependency.getTypeFromPrefix(type ?? "");
this.type = "required"; this.spec = spec;
this.name = parts[0]; this.name = name;
break;
case 2: // Parse the equality and version
this.type = ModDependency.getTypeFromPrefix(parts[0]); if ((equality || version) && !this.incompatible) {
this.name = parts[1]; this.version = ModVersionEquality.fromParts(equality, version);
break;
case 3:
this.type = "required";
this.name = parts[0];
this.version = ModVersionEquality.fromParts(parts[1], parts[2]);
break;
case 4:
this.type = ModDependency.getTypeFromPrefix(parts[0]);
this.name = parts[1];
this.version = ModVersionEquality.fromParts(parts[2], parts[3]);
break;
default:
throw new Error(`Invalid dependency specification: ${specification}`);
} }
} }
@@ -124,7 +102,7 @@ export class ModDependency {
} }
toJSON() { toJSON() {
return this.specification; return this.spec;
} }
} }
@@ -218,7 +196,7 @@ export default class ModInfo {
* As they would be represented in info.json. * As they would be represented in info.json.
*/ */
get dependencySpecifications() { get dependencySpecifications() {
return this.dependencies.map(d => d.specification); return this.dependencies.map(d => d.spec);
} }
checkDependencySatisfaction(mods: (ModInfo | ModRecord)[]) { checkDependencySatisfaction(mods: (ModInfo | ModRecord)[]) {
@@ -308,7 +286,13 @@ export default class ModInfo {
if (json.homepage) { modInfo.homepage = json.homepage; } if (json.homepage) { modInfo.homepage = json.homepage; }
if (json.description) { modInfo.description = json.description; } if (json.description) { modInfo.description = json.description; }
if (json.factorio_version) { modInfo.factorioVersion = json.factorio_version; } if (json.factorio_version) { modInfo.factorioVersion = json.factorio_version; }
if (json.dependencies) { modInfo.dependencies = json.dependencies.map(d => new ModDependency(d)); }
// Parse the dependencies
try {
if (json.dependencies) { modInfo.dependencies = json.dependencies.map(d => new ModDependency(d)); }
} catch (err: any) {
throw new Error(`Failed for parse dependencies for ${json.name}: ${err}`);
}
// Additional data // Additional data
if (json.size) { modInfo.size = json.size; } if (json.size) { modInfo.size = json.size; }
+17 -5
View File
@@ -403,6 +403,10 @@ export class ModPortalDownloadRequest {
} }
} }
const ModDependencyResolveErrors = ["incompatible", "unsatisfiable", "invalidDependency", "notFound"] as const;
export const ModDependencyResolveErrorsSchema = Type.Union(ModDependencyResolveErrors.map(v => Type.Literal(v)));
export type ModDependencyResolveErrors = Static<typeof ModDependencyResolveErrorsSchema>;
/** /**
* Request mods dependencies to be resolved using the Factorio mod portal. * Request mods dependencies to be resolved using the Factorio mod portal.
* *
@@ -456,18 +460,26 @@ export class ModDependencyResolveRequest {
static Response = class ModDependencyResolveResponse { static Response = class ModDependencyResolveResponse {
constructor( constructor(
public dependencies: ModInfo[], public dependencies: ModInfo[],
public incompatible: string[], public errors: Map<string, ModDependencyResolveErrors>,
public missing: string[],
) {} ) {}
static jsonSchema = Type.Object({ static jsonSchema = Type.Object({
"dependencies": Type.Array(ModInfo.jsonSchema), "dependencies": Type.Array(ModInfo.jsonSchema),
"incompatible": Type.Array(Type.String()), "errors": Type.Record(Type.String(), ModDependencyResolveErrorsSchema),
"missing": Type.Array(Type.String()),
}); });
static fromJSON(json: Static<typeof this.jsonSchema>) { static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.dependencies.map(d => ModInfo.fromJSON(d)), json.incompatible, json.missing); return new this(
json.dependencies.map(d => ModInfo.fromJSON(d)),
new Map(Object.entries(json.errors))
);
}
toJSON(): Static<typeof ModDependencyResolveResponse.jsonSchema> {
return {
dependencies: this.dependencies.map(d => d.toJSON()),
errors: Object.fromEntries(this.errors),
};
} }
}; };
} }
+2 -2
View File
@@ -151,10 +151,10 @@ export class ModVersionEquality {
static fromParts(equality: string, version: string) { static fromParts(equality: string, version: string) {
if (!isVersionEquality(equality)) { if (!isVersionEquality(equality)) {
throw new Error(`Unknown version equality: ${equality}`); throw new Error(`Invalid version equality "${equality}"`);
} }
if (!isPartialVersion(version)) { if (!isPartialVersion(version)) {
throw new Error(`Malformed version string: ${version}`); throw new Error(`Invalid version string "${version}"`);
} }
return new this(equality, version); return new this(equality, version);
} }
@@ -98,7 +98,7 @@ export default function ModDetails<T extends lib.ModInfo | lib.ModRecord>(props:
{depWarnings.get(e.name) === "wrong_version" && <Tooltip title="Wrong version added."> {depWarnings.get(e.name) === "wrong_version" && <Tooltip title="Wrong version added.">
<FileSyncOutlined style={{ color: "#dd5e14" }} />{" "} <FileSyncOutlined style={{ color: "#dd5e14" }} />{" "}
</Tooltip>} </Tooltip>}
{e.specification} {e.spec}
</Space> </Space>
<br/> <br/>
</Fragment>) </Fragment>)
@@ -268,16 +268,28 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
// State for the modal and dependencies // State for the modal and dependencies
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [missing, setMissing] = useState<string[]>([]);
const [builtins, setBuiltins] = useState<string[]>([]);
const [incompatible, setIncompatible] = useState<string[]>([]);
const [factorioVersion, setFactorioVersion] = useState<lib.ApiVersion | null>(null);
// State for all mods fetched from backend
const [error, setError] = useState<Error | null>(null); const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false);
const [allMods, setAllMods] = useState<lib.ModInfo[]>([]); const [factorioVersion, setFactorioVersion] = useState<lib.ApiVersion | null>(null);
const [mods, setMods] = useState<lib.ModInfo[]>([]);
const [mods, setMods] = useState<lib.ModInfo[]>([]); // All resolved mods and dependencies
const [missing, setMissing] = useState<lib.ModInfo[]>([]); // Missing mods and dependencies, excluding builtin
const [modErrors, setModErrors] = useState({
notFound: new Array<string>(), // Mods which were not found on the mod portal, can include builtins
incompatible: new Array<string>(), // Mods which are required, but are marked incompatible by another
unsatisfiable: new Array<string>(), // Mods which can not have their version range satisfied
invalidDependency: new Array<string>(), // Mods with invalid dependency specs
});
function resetModErrors() {
setModErrors({
notFound: [],
incompatible: [],
unsatisfiable: [],
invalidDependency: [],
});
}
// Get a valid factorio version // Get a valid factorio version
useEffect(() => { useEffect(() => {
@@ -294,10 +306,8 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
if (!open || !factorioVersion) { if (!open || !factorioVersion) {
// Clear if closed or no version // Clear if closed or no version
setMods([]); setMods([]);
setAllMods([]);
setMissing([]); setMissing([]);
setBuiltins([]); resetModErrors();
setIncompatible([]);
return; return;
} }
@@ -309,21 +319,29 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
lib.ModDependencyResolveRequest.fromModPackEnabled(props.modPack, props.checkForUpdates) lib.ModDependencyResolveRequest.fromModPackEnabled(props.modPack, props.checkForUpdates)
).then(response => { ).then(response => {
if (canceled) { return; } if (canceled) { return; }
setMods(response.dependencies.filter(dep => !modInfos.has(`${dep.name}_${dep.version}`)));
setIncompatible(response.incompatible); const newModErrors = [...response.errors.entries()]
setAllMods(response.dependencies); .reduce<typeof modErrors>((acc, [modName, modError]) => {
setMissing(response.missing.filter(name => !props.builtInModNames.includes(name))); acc[modError].push(modName);
setBuiltins(response.missing.filter(name => props.builtInModNames.includes(name))); return acc;
}, {
notFound: [],
incompatible: [],
unsatisfiable: [],
invalidDependency: [],
});
setModErrors(newModErrors);
setMods(response.dependencies);
setMissing(response.dependencies.filter(dep => !modInfos.has(`${dep.name}_${dep.version}`)));
setLoading(false); setLoading(false);
}).catch(err => { }).catch(err => {
if (canceled) { return; } if (canceled) { return; }
notifyErrorHandler("Error fetching mods dependencies")(err); notifyErrorHandler("Error fetching mods dependencies")(err);
setError(err); setError(err);
setMods([]); setMods([]);
setAllMods([]);
setMissing([]); setMissing([]);
setBuiltins([]); resetModErrors();
setIncompatible([]);
setLoading(false); setLoading(false);
}); });
@@ -334,51 +352,56 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
// Re-fetch when modal opens or factorio version changes // Re-fetch when modal opens or factorio version changes
}, [open, factorioVersion, control]); }, [open, factorioVersion, control]);
// Function to handle download from Mod Portal to Controller // Fix any mod errors found after resolving dependencies
function handleControllerDownload() { function fixModErrors() {
if (!factorioVersion || !mods) { if (!factorioVersion) {
return; return;
} }
// Enable any required builtins // Enable any required builtins, they will be within the not found list
for (const name of builtins) { for (const modName of modErrors.notFound) {
props.onChange({ if (props.builtInModNames.includes(modName)) {
type: "mods.set", props.onChange({
name: name, type: "mods.set",
value: { ...props.modPack.mods.get(name)!, enabled: true }, name: modName,
}); value: { ...props.modPack.mods.get(modName)!, enabled: true },
});
}
} }
// Disable any incompatible mods present // Disable any incompatible mods
for (const name of incompatible) { for (const modName of modErrors.incompatible) {
const modRecord = props.modPack.mods.get(name); const modRecord = props.modPack.mods.get(modName);
if (modRecord) { if (modRecord) {
props.onChange({ props.onChange({
type: "mods.set", type: "mods.set",
name: name, name: modName,
value: { ...modRecord, enabled: false }, value: { ...modRecord, enabled: false },
}); });
} }
} }
// Add all dependencies to the mod pack // Add all dependencies to the mod pack
for (const mod of allMods) { for (const mod of mods) {
props.onChange({ const existingMod = props.modPack.mods.get(mod.name);
type: "mods.set", if (!existingMod || existingMod.version !== mod.version) {
name: mod.name, props.onChange({
value: { type: "mods.set",
name: mod.name, name: mod.name,
version: mod.version, value: {
sha1: mod.sha1, name: mod.name,
enabled: true, version: mod.version,
}, sha1: mod.sha1,
}); enabled: true,
},
});
}
} }
// Download the missing dependencies // Download any missing mods
control.send( control.send(
new lib.ModPortalDownloadRequest( new lib.ModPortalDownloadRequest(
mods.map(mod => ({ missing.map(mod => ({
name: mod.name, version: new lib.ModVersionEquality("=", mod.version), name: mod.name, version: new lib.ModVersionEquality("=", mod.version),
})), })),
factorioVersion, factorioVersion,
@@ -386,12 +409,12 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
).then(() => { ).then(() => {
notification.success({ notification.success({
message: "Download complete", message: "Download complete",
description: `${mods.length} mods have been downloaded to the controller.`, description: `${missing.length} mods have been downloaded to the controller.`,
}); });
}).catch( }).catch(
notifyErrorHandler("Error starting mod download") notifyErrorHandler("Error starting mod download")
); );
}; }
return <> return <>
{props.checkForUpdates && <Button {props.checkForUpdates && <Button
@@ -415,8 +438,11 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
<Button <Button
key="start" key="start"
type="primary" type="primary"
disabled={loading || mods.length === 0} disabled={loading || missing.length === 0}
onClick={() => { setOpen(false); handleControllerDownload(); }} onClick={() => {
setOpen(false);
fixModErrors();
}}
>Start Download</Button>, >Start Download</Button>,
]} ]}
> >
@@ -429,30 +455,26 @@ function DownloadDependenciesButton(props: DownloadDependenciesProps) {
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
/>} />}
{/* Display warning message if dependencies could not be found */} {/* Display warning message for mod errors */}
{!loading && missing.length > 0 && <Alert {([
message="Failed to Find Dependencies:" ["notFound", "Failed to find dependencies:"],
description={<ul> ["incompatible", "Dependencies are incompatible:"],
{missing.map(name => <li>{name}</li>)} ["unsatisfiable", "Dependencies could not be satisfied:"],
</ul>} ["invalidDependency", "Dependencies has invalid specifications:"],
type="warning" ] as const).map(([prop, message]) => {
showIcon const modNames = modErrors[prop];
style={{ marginBottom: 16 }} return modNames.length === 0 ? null : <Alert
/>} showIcon
type="warning"
{/* Display warning message if dependencies are incompatible */} message={message}
{!loading && incompatible.length > 0 && <Alert description={<ul>{modNames.map(name => <li>{name}</li>)}</ul>}
message="Incompatible Dependencies Found:" style={{ marginBottom: 14 }}
description={<ul> />;
{incompatible.map(name => <li>{name}</li>)} })}
</ul>}
type="warning"
showIcon
style={{ marginBottom: 16 }}
/>}
{/* Display a table of the missing mods that need to be downloaded */}
<Table <Table
dataSource={mods} dataSource={missing}
rowKey={record => record.name} rowKey={record => record.name}
loading={loading} loading={loading}
pagination={{ pagination={{
+77 -8
View File
@@ -52,20 +52,46 @@ describe("lib/data/ModInfo", function() {
assert.equal(dependency.version.equality, ">="); assert.equal(dependency.version.equality, ">=");
assert.equal(dependency.version.integerVersion, lib.integerFullVersion("1.2.3")); assert.equal(dependency.version.integerVersion, lib.integerFullVersion("1.2.3"));
}); });
it("should ignore the version for incompatible dependencies", function() {
const dependency = new ModDependency("! my-mod >= 1.2.3");
assert.equal(dependency.name, "my-mod");
assert.equal(dependency.type, "incompatible");
assert.equal(dependency.version, undefined);
});
it("should throw on an empty string", function() {
assert.throws(() => new ModDependency(""));
});
it("should throw if no version equality is given", function() { it("should throw if no version equality is given", function() {
this.skip(); // For alignment with factorio, this should be parsed as the mod name
assert.throws(() => new ModDependency("my-mod 1.2.3")); assert.throws(() => new ModDependency("my-mod 1.2.3"));
assert.throws(() => new ModDependency("? my-mod 1.2.3")); assert.throws(() => new ModDependency("? my-mod 1.2.3"));
}); });
it("should parse no version equality as the mod name", function() {
const dependencyReq = new ModDependency("my-mod 1.2.3");
assert.equal(dependencyReq.name, "my-mod 1.2.3");
assert.equal(dependencyReq.type, "required");
assert.equal(dependencyReq.version, undefined);
const dependencyOpt = new ModDependency("? my-mod 1.2.3");
assert.equal(dependencyOpt.name, "my-mod 1.2.3");
assert.equal(dependencyOpt.type, "optional");
assert.equal(dependencyOpt.version, undefined);
});
it("should throw if invalid specification given", function() { it("should throw if invalid specification given", function() {
this.skip(); // For alignment with factorio, this should be parsed as the mod name
assert.throws(() => new ModDependency("& my-mod = 1.2.3"));
assert.throws(() => new ModDependency("? ? my-mod = 1.2.3")); assert.throws(() => new ModDependency("? ? my-mod = 1.2.3"));
}); });
it("should throw if name contains spaces", function() { it("should parse invalid prefix as the mod name", function() {
// Apparently there are some legacy mods which include spaces const dependencyInvalid = new ModDependency("& my-mod = 1.2.3");
// Such as https://mods.factorio.com/mod/Explosive%20Excavation assert.equal(dependencyInvalid.name, "& my-mod");
this.skip(); assert.equal(dependencyInvalid.type, "required");
assert.throws(() => new ModDependency("my mod")); assert.equal(dependencyInvalid.version.version, "1.2.3");
assert.throws(() => new ModDependency("? my mod"));
assert.throws(() => new ModDependency("? my mod >= 1.2.3")); const dependencyDupe = new ModDependency("? ? my-mod = 1.2.3");
assert.equal(dependencyDupe.name, "? my-mod");
assert.equal(dependencyDupe.type, "optional");
assert.equal(dependencyDupe.version.version, "1.2.3");
}); });
it("should not error when the name contains spaces", function() { it("should not error when the name contains spaces", function() {
const dependencyReq = new ModDependency("my mod"); const dependencyReq = new ModDependency("my mod");
@@ -86,6 +112,44 @@ describe("lib/data/ModInfo", function() {
assert.equal(dependencyOptVer.type, "optional"); assert.equal(dependencyOptVer.type, "optional");
assert.equal(dependencyOptVer.version.version, "1.2.3"); assert.equal(dependencyOptVer.version.version, "1.2.3");
}); });
it("should not error when the extra spaces are present", function() {
const dependencyReq = new ModDependency(" my mod ");
assert.equal(dependencyReq.name, " my mod ");
assert.equal(dependencyReq.type, "required");
const dependencyOpt = new ModDependency("? my mod ");
assert.equal(dependencyOpt.name, "my mod ");
assert.equal(dependencyOpt.type, "optional");
const dependencyVer = new ModDependency("my mod >= 1.2.3");
assert.equal(dependencyVer.name, "my mod");
assert.equal(dependencyVer.type, "required");
assert.equal(dependencyVer.version.version, "1.2.3");
const dependencyOptVer = new ModDependency("? my mod >= 1.2.3");
assert.equal(dependencyOptVer.name, "my mod");
assert.equal(dependencyOptVer.type, "optional");
assert.equal(dependencyOptVer.version.version, "1.2.3");
});
it("should not error when there are no spaces present", function() {
const dependencyReq = new ModDependency("my-mod");
assert.equal(dependencyReq.name, "my-mod");
assert.equal(dependencyReq.type, "required");
const dependencyOpt = new ModDependency("?my-mod");
assert.equal(dependencyOpt.name, "my-mod");
assert.equal(dependencyOpt.type, "optional");
const dependencyVer = new ModDependency("my-mod>=1.2.3");
assert.equal(dependencyVer.name, "my-mod");
assert.equal(dependencyVer.type, "required");
assert.equal(dependencyVer.version.version, "1.2.3");
const dependencyOptVer = new ModDependency("?my-mod>=1.2.3");
assert.equal(dependencyOptVer.name, "my-mod");
assert.equal(dependencyOptVer.type, "optional");
assert.equal(dependencyOptVer.version.version, "1.2.3");
});
it("should be round trip json serialisable", function() { it("should be round trip json serialisable", function() {
testRoundTripJsonSerialisable(ModDependency, testMatrix( testRoundTripJsonSerialisable(ModDependency, testMatrix(
["my-mod", "? my-mod", "! my-mod", "my-mod > 1.0.0", "~ my-mod <= 2.0.0"], // Specification ["my-mod", "? my-mod", "! my-mod", "my-mod > 1.0.0", "~ my-mod <= 2.0.0"], // Specification
@@ -271,7 +335,12 @@ describe("lib/data/ModInfo", function() {
is_deleted: true, is_deleted: true,
})); }));
}); });
it("should throw an error if given invalid dependencies", function() {
assert.throws(() => ModInfo.fromJSON({
name: "my-mod",
dependencies: ["base", ""],
}), /my-mod/); // check the mod name is included in the error message
});
it("should sort integer mod versions lexicographically", function() { it("should sort integer mod versions lexicographically", function() {
let unsortedVersions = ["1.0.0", "1.1.0", "0.1.0", "3.0.0", "1.2.0", "0.3.1", "0.3.3", "2.1.1", "0.0.1"]; let unsortedVersions = ["1.0.0", "1.1.0", "0.1.0", "3.0.0", "1.2.0", "0.3.1", "0.3.3", "2.1.1", "0.0.1"];
let sortedVersions = ["0.0.1", "0.1.0", "0.3.1", "0.3.3", "1.0.0", "1.1.0", "1.2.0", "2.1.1", "3.0.0"]; let sortedVersions = ["0.0.1", "0.1.0", "0.3.1", "0.3.3", "1.0.0", "1.1.0", "1.2.0", "2.1.1", "3.0.0"];
+60 -88
View File
@@ -168,19 +168,21 @@ describe("messages/mod", function() {
ModInfo.fromJSON({ name: "bar", version: "2.0.0" }), ModInfo.fromJSON({ name: "bar", version: "2.0.0" }),
], ],
], ],
[[], ["foo-i"], ["foo-i", "bar-i"]], // incompatible [ // errors
[[], ["foo-m"], ["foo-m", "bar-m"]], // missing new Map([]),
new Map([["foo", "notFound"]]),
new Map([["foo", "unsatisfiable"], ["bar", "incompatible"], ["baz", "invalidDependency"]]),
],
); );
it("should be round trip json serialisable", function() { it("should be round trip json serialisable", function() {
testRoundTripJsonSerialisable(ModDependencyResolveRequest.Response, tests); testRoundTripJsonSerialisable(ModDependencyResolveRequest.Response, tests);
}); });
it("should be construable", function() { it("should be construable", function() {
for (const [dependencies, incompatible, missing] of tests) { for (const [dependencies, errors] of tests) {
const test = JSON.stringify([dependencies, missing, incompatible]); const test = JSON.stringify([dependencies, errors]);
const request = new ModDependencyResolveRequest.Response(dependencies, incompatible, missing); const request = new ModDependencyResolveRequest.Response(dependencies, errors);
assert.deepEqual(request.dependencies, dependencies, test); assert.deepEqual(request.dependencies, dependencies, test);
assert.deepEqual(request.incompatible, incompatible, test); assert.deepEqual(request.errors, errors, test);
assert.deepEqual(request.missing, missing, test);
} }
}); });
}); });
@@ -204,19 +206,15 @@ describe("messages/mod", function() {
) )
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
]));
const expectedIds = [
"root_1.0.0", "foo_1.0.0", "foo-dep_1.0.0", "bar_1.0.0",
"root-2_1.0.0", "bar-2_1.0.0",
];
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set([
for (const modId of expectedIds) { "root_1.0.0", "foo_1.0.0", "foo-dep_1.0.0", "bar_1.0.0",
assert(depIds.has(modId), `Missing ${modId}`); "root-2_1.0.0", "bar-2_1.0.0",
} ]));
} }
}); });
it("highlights dependencies with no suitable version", async function() { it("highlights dependencies with no suitable version", async function() {
@@ -228,8 +226,10 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base", "bar"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
["bar", "notFound"],
]));
assert.equal(result.dependencies.length, 1); assert.equal(result.dependencies.length, 1);
assert.equal(result.dependencies[0].id, "root_1.0.0"); assert.equal(result.dependencies[0].id, "root_1.0.0");
@@ -243,8 +243,10 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base", "foo"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
["foo", "notFound"],
]));
assert.equal(result.dependencies.length, 1); assert.equal(result.dependencies.length, 1);
assert.equal(result.dependencies[0].id, "root_1.0.0"); assert.equal(result.dependencies[0].id, "root_1.0.0");
@@ -260,16 +262,13 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, ["foo-dep"]); ["base", "notFound"],
["foo-dep", "incompatible"],
const expectedIds = ["root_1.0.0", "foo_1.0.0", "foo-dep_1.0.0"]; ]));
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_1.0.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("highlights dependencies with conflicting versions", async function() { it("highlights dependencies with conflicting versions", async function() {
@@ -282,16 +281,13 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, ["dep"]); ["base", "notFound"],
["dep", "unsatisfiable"],
const expectedIds = ["root_1.0.0", "foo_1.0.0", "bar_1.0.0"]; ]));
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_1.0.0", "bar_1.0.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("highlights incompatible builtin mods", async function() { it("highlights incompatible builtin mods", async function() {
@@ -303,16 +299,12 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, []); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, ["base"]); ["base", "incompatible"],
]));
const expectedIds = ["root_1.0.0", "foo_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_1.0.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("does not ignore optional dependencies when required by another", async function() { it("does not ignore optional dependencies when required by another", async function() {
@@ -325,16 +317,12 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
]));
const expectedIds = ["root_1.0.0", "foo_1.0.0", "baz_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_1.0.0", "baz_1.0.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("prefers the locally installed version if matching", async function() { it("prefers the locally installed version if matching", async function() {
@@ -347,16 +335,12 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
]));
const expectedIds = ["root_1.0.0", "foo_1.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_1.0.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("prefers the mod portal version when checking for updates", async function() { it("prefers the mod portal version when checking for updates", async function() {
@@ -369,16 +353,12 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion, true) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion, true)
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
]));
const expectedIds = ["root_1.0.0", "foo_2.0.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_2.0.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("prefers the latest mod portal version when using the mod portal", async function() { it("prefers the latest mod portal version when using the mod portal", async function() {
@@ -409,16 +389,12 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion) new lib.ModDependencyResolveRequest([new ModDependency("root")], factorioVersion)
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, []); ["base", "notFound"],
]));
const expectedIds = ["root_1.0.0", "foo_2.0.0", "bar_1.5.0"];
const depIds = new Set(result.dependencies.map(mod => mod.id)); const depIds = new Set(result.dependencies.map(mod => mod.id));
assert.equal(depIds.size, expectedIds.length); assert.deepEqual(depIds, new Set(["root_1.0.0", "foo_2.0.0", "bar_1.5.0"]));
for (const modId of expectedIds) {
assert(depIds.has(modId), `Missing ${modId}`);
}
} }
}); });
it("rejects when a network error occurs", async function() { it("rejects when a network error occurs", async function() {
@@ -440,22 +416,18 @@ describe("messages/mod", function() {
new lib.ModDependencyResolveRequest([new ModDependency("pymodpack = 3.0.0")], "2.0") new lib.ModDependencyResolveRequest([new ModDependency("pymodpack = 3.0.0")], "2.0")
); );
assert.deepEqual(result.missing, ["base"]); assert.deepEqual(result.errors, new Map([
assert.deepEqual(result.incompatible, ["space-age"]); ["base", "notFound"],
]));
const expectedNames = [ // Can't use ids as the versions may change const depNames = new Set(result.dependencies.map(mod => mod.name));
assert.deepEqual(depNames, new Set([ // Can't use ids as the versions may change
"pymodpack", "pypostprocessing", "pyalternativeenergy", "pyalternativeenergygraphics", "pymodpack", "pypostprocessing", "pyalternativeenergy", "pyalternativeenergygraphics",
"pyalienlife", "pyalienlifegraphics", "pyalienlifegraphics2", "pyalienlifegraphics3", "pyalienlife", "pyalienlifegraphics", "pyalienlifegraphics2", "pyalienlifegraphics3",
"pycoalprocessing", "pycoalprocessinggraphics", "pyfusionenergy", "pyfusionenergygraphics", "pycoalprocessing", "pycoalprocessinggraphics", "pyfusionenergy", "pyfusionenergygraphics",
"pypetroleumhandling", "pypetroleumhandlinggraphics", "pyrawores", "pyraworesgraphics", "pypetroleumhandling", "pypetroleumhandlinggraphics", "pyrawores", "pyraworesgraphics",
"pyhightech", "pyhightechgraphics", "pyindustry", "pyindustrygraphics", "pyhightech", "pyhightechgraphics", "pyindustry", "pyindustrygraphics",
]; ]));
const depNames = new Set(result.dependencies.map(mod => mod.name));
assert.equal(depNames.size, expectedNames.length);
for (const modName of expectedNames) {
assert(depNames.has(modName), `Missing ${modName}`);
}
}); });
}); });
}); });