`;
}).join('');
}
// Problems we can see from the mod info, plus the image's own startup warnings.
function modProblems() {
const known = knownMods();
const haveInfo = (mm.info.items || []).length > 0;
const enabled = new Set(mm.mods);
const pos = Object.fromEntries(mm.mods.map((m, i) => [m, i]));
const out = [];
const conflicts = new Set();
for (const id of mm.mods) {
const m = known[id];
if (!m) {
if (haveInfo) out.push({ level: 'warning', text: `${id}: not found in any downloaded workshop item.` });
continue;
}
if (m.error) out.push({ level: 'error', text: `${m.name || id}: ${m.error}` });
for (const r of m.require) {
if (!enabled.has(r)) out.push({ level: 'warning', text: `${m.name || id} requires ${r}, which isn't enabled (the server loads it if it's downloaded).` });
else if (pos[r] > pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load after ${r}. Auto-sort fixes this.` });
}
for (const r of m.loadAfter) {
if (enabled.has(r) && pos[r] > pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load after ${r}. Auto-sort fixes this.` });
}
for (const r of m.loadBefore) {
if (enabled.has(r) && pos[r] < pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load before ${r}. Auto-sort fixes this.` });
}
for (const r of m.incompatible) {
// Either mod may declare the conflict; report each pair once.
const pair = [id, r].sort().join('\u0000');
if (enabled.has(r) && !conflicts.has(pair)) {
conflicts.add(pair);
out.push({ level: 'error', text: `${m.name || id} is incompatible with ${known[r]?.name || r}.` });
}
}
}
return out;
}
function renderIssues() {
const fromServer = (mm.state?.issues || []).map((i) => ({ ...i, source: 'server log' }));
const all = [...modProblems(), ...fromServer];
$('#mods-issues-section').classList.toggle('hidden', !all.length);
$('#mods-issues').innerHTML = all.map((i) => `
`).join('');
}
$('#mods-messages').addEventListener('click', (e) => {
if (e.target.dataset.msgAction === 'enable-all') enableAll();
});
// Enable every loadable mod in the listed workshop items the server has read, then auto-sort.
function enableAll() {
let added = 0;
let broken = 0;
const unknown = [];
for (const id of mm.workshopIds) {
const info = itemInfo(id);
if (!info?.downloaded) { unknown.push(id); continue; }
for (const m of info.mods) {
if (m.error) { broken += 1; continue; }
if (!mm.mods.includes(m.id)) { mm.mods.push(m.id); added += 1; }
}
}
autoSort();
const msgs = [];
if (added) msgs.push({ level: 'success', text: `Enabled ${added} mod${added === 1 ? '' : 's'} and sorted the load order. Save to apply.` });
else msgs.push({ level: 'info', text: 'No more mods to enable from the downloaded items.' });
if (broken) msgs.push({ level: 'warning', text: `${broken} mod${broken === 1 ? '' : 's'} left off because the server reports they can't load.` });
if (unknown.length) {
msgs.push({ level: 'warning', text: `${unknown.length} workshop item${unknown.length === 1 ? ' hasn\'t' : 's haven\'t'} been downloaded yet, so `
+ 'their mods aren\'t known. Save, click Fetch mod info while the server is online, then Enable all again.' });
}
showMsgs(msgs);
changed();
}
$('#mods-enable-all').addEventListener('click', enableAll);
// Put each enabled mod after the ones it requires or asks to load after. Returns whether the order changed.
function autoSort() {
const known = knownMods();
const set = new Set(mm.mods);
const after = Object.fromEntries(mm.mods.map((m) => [m, new Set()])); // m loads after these
for (const id of mm.mods) {
const m = known[id];
if (!m) continue;
for (const r of [...m.require, ...m.loadAfter]) if (set.has(r) && r !== id) after[id].add(r);
for (const r of m.loadBefore) if (set.has(r) && r !== id) after[r].add(id);
}
const out = [];
const placed = new Set();
while (out.length < mm.mods.length) {
const next = mm.mods.find((m) => !placed.has(m) && [...after[m]].every((r) => placed.has(r)))
|| mm.mods.find((m) => !placed.has(m)); // a cycle: keep going in the current order
out.push(next); placed.add(next);
}
if (out.join() === mm.mods.join()) return false;
mm.mods = out;
return true;
}
$('#mods-sort').addEventListener('click', () => { if (autoSort()) changed(); });
async function addFromText(text) {
showMsgs([]);
const btn = $('#mods-add-btn');
btn.disabled = true; btn.textContent = 'Looking up…';
try {
const r = await api('/api/workshop/lookup', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }),
});
const skipped = [];
let added = 0;
for (const it of r.items) {
mm.titles[it.id] = it;
if (!it.available || !it.zomboid) { skipped.push(it); continue; }
if (!mm.workshopIds.includes(it.id)) { mm.workshopIds.push(it.id); added += 1; }
}
const msgs = [];
for (const c of r.collections) msgs.push({ level: 'info', text: `Collection "${c.title || c.id}" has ${c.count} items.` });
if (added) msgs.push({ level: 'success', text: `Added ${added} workshop item${added === 1 ? '' : 's'}.` });
else if (!skipped.length) msgs.push({ level: 'info', text: 'Already in the list.' });
if (skipped.length) {
msgs.push({ level: 'error', text: `Skipped items:\n${skipped.map((it) => ` - ${it.id}${it.title ? ` (${it.title})` : ''}`).join('\n')}`
+ '\n\nThese items are either unavailable or not a Project Zomboid item.' });
}
if (added && r.collections.length) {
msgs.push({ level: 'info', action: 'enable-all', text: 'Adding items doesn\'t enable their mods. To enable everything: '
+ 'click Save for next restart, then Fetch mod info while the server is online (it downloads the items and reads '
+ 'their mod IDs), then Enable all, then Save & restart now.' });
}
showMsgs(msgs);
if (added) changed();
return true;
} catch (err) {
showMsgs([{ level: 'error', text: err.message }]);
return false;
} finally {
btn.disabled = false; btn.textContent = 'Add';
}
}
$('#mods-add-btn').addEventListener('click', async () => {
const text = $('#mods-add-input').value.trim();
if (text && await addFromText(text)) $('#mods-add-input').value = '';
});
$('#mods-add-input').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); $('#mods-add-btn').click(); } });
// "WorkshopItems=1;2" and "Mods=\A;\B" lines from a pzserver.ini.
$('#mods-import-btn').addEventListener('click', async () => {
const text = $('#mods-import-text').value;
const items = /^\s*WorkshopItems\s*=(.*)$/mi.exec(text)?.[1] || '';
const mods = /^\s*Mods\s*=(.*)$/mi.exec(text)?.[1] || '';
if (!items.trim() && !mods.trim()) { showMsgs([{ level: 'error', text: 'Paste the WorkshopItems= and Mods= lines.' }]); return; }
for (const m of mods.split(';').map((x) => x.trim().replace(/^\\+/, '')).filter(Boolean)) {
if (!mm.mods.includes(m)) mm.mods.push(m);
}
if (items.trim()) await addFromText(items.replace(/;/g, ' '));
$('#mods-import-text').value = '';
changed();
});
// ---------- saving ----------
async function saveMods(apply) {
if (apply === 'now' && mm.state?.running && !confirm(
'Restart the server now with these mods? Players online get a 60-second warning first; with nobody online it restarts right away.')) return;
showMsgs([]);
try {
const d = await api(`/api/servers/${mm.server.id}/mods`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workshop_ids: mm.workshopIds, mods: mm.mods, auto_update: mm.autoUpdate, apply }),
});
mm.edited = false;
mm.state = d;
renderMods();
refresh();
if (apply === 'now') {
// The container is recreated, so its id changes; follow it by name.
watchForNewContainer();
}
} catch (err) { showMsgs([{ level: 'error', text: err.message }]); }
}
function watchForNewContainer() {
const name = mm.server.container;
const t = setInterval(async () => {
try {
const list = await api('/api/servers');
const s = list.find((x) => x.container === name);
if (s && s.id !== mm.server.id) { mm.server = s; clearInterval(t); }
if (!s || !$('#mods-dialog').open) clearInterval(t);
} catch { clearInterval(t); }
}, 2000);
}
$('#mods-save').addEventListener('click', () => saveMods('later'));
$('#mods-apply').addEventListener('click', () => saveMods('now'));
$('#mods-fetch').addEventListener('click', async () => {
if (mm.edited) { await saveMods('later'); if (mm.edited) return; }
showMsgs([]);
const start = !mm.state?.ready; // also waits for a server that is still starting
try {
await api(`/api/servers/${mm.server.id}/mods/refresh${start ? '?start=true' : ''}`, { method: 'POST' });
if (start) {
showMsgs([{ level: 'info', text: `${mm.state?.running ? 'Waiting for the server to come online.' : 'Starting the server.'} `
+ 'Mod info is fetched automatically once it\'s online. The first start with new mods downloads them first, which '
+ 'can take a while. You can close this window.' }]);
watchForNewContainer(); // starting with saved changes recreates the container under a new id
}
loadMods(false);
} catch (err) { showMsgs([{ level: 'error', text: err.message }]); }
});