Upstream/test/military-helpers.js
jvanvik 249818a7aa Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy
Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 18:32:36 +02:00

108 lines
6.8 KiB
JavaScript

'use strict';
/* Shared fixtures of the military tests: an in-memory (or file) game with a fake clock and hand-placed operators.
* Not a test file itself (node:test finds no tests in it). */
const crypto = require('crypto');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { openDb, migrate } = require('../server/db');
const { FakeClock } = require('../server/clock');
const { Scheduler } = require('../server/scheduler');
const { createCommands } = require('../server/commands');
const { createQueries } = require('../server/queries');
const { createWorld } = require('../server/world');
const { createTown } = require('../server/commands/joinWorld');
const handlers = require('../server/events');
const { createMilitaryQueries } = require('../server/military/views');
const H = D.HOUR_MS;
function setup(o) {
o = o || {};
const clock = o.clock || new FakeClock();
const db = openDb(o.file || ':memory:');
migrate(db);
const row = db.get('SELECT id FROM worlds LIMIT 1');
const worldId = row ? row.id : createWorld(db, clock.now(), { seed: o.seed || 4242, speed: o.speed || 1, mapRadius: o.radius || 50 });
const scheduler = new Scheduler({ db, clock, handlers, autoArm: false, log: o.log || (() => {}) });
const commands = createCommands({ db, clock, scheduler });
const queries = createQueries({ db, clock, scheduler });
const mq = createMilitaryQueries({ db, clock, scheduler });
const world = db.get('SELECT * FROM worlds WHERE id = ?', worldId);
const h = { db, clock, scheduler, commands, queries, mq, worldId, world };
h.run = (name, args) => commands.run(name, args);
h.advance = (ms) => { clock.advance(ms); return scheduler.runDue(); };
h.advanceTo = (t) => { clock.set(t); return scheduler.runDue(); };
h.ctx = () => ({ db, clock, now: clock.now(), scheduler, enqueue: (e) => scheduler.enqueue(e), notify: (u, w, t, p) => scheduler.notify(u, w, t, p) });
return h;
}
// First free land tile at or near (x, y), scanning rightwards.
function landNear(h, x, y) {
for (let i = 0; i < 400; i++) {
const xx = x + i;
if (R.tileAt(h.world.seed, h.world.map_radius, xx, y).type === 'land' && !h.db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', h.worldId, xx, y)) return { x: xx, y };
}
throw new Error('no land near ' + x + ',' + y);
}
// An operator with one capital POP at the first land tile from (x, y). Buildings: the starting POP plus `infra` levels,
// strong power, lots of resources. Beginner protection off unless `protectedUntil`.
function addOperator(h, name, o) {
o = o || {};
const { x, y } = landNear(h, o.x === undefined ? 5 : o.x, o.y === undefined ? 0 : o.y);
const now = h.clock.now();
const u = h.db.run('INSERT INTO users (username, pass_hash, created_at) VALUES (?, ?, ?)', name, 'x', now);
const userId = Number(u.lastInsertRowid);
const op = h.db.run('INSERT INTO operators (world_id, user_id, name, as_number, protection_until, created_at) VALUES (?, ?, ?, ?, ?, ?)', h.worldId, userId, name, D.AS_RANGE.min + (h.asn = (h.asn || 0) + 1), o.protectedUntil || 0, now);
const opId = Number(op.lastInsertRowid);
const townId = createTown(h.db, { worldId: h.worldId, ownerId: opId, name: name + ' POP 1', x, y, isCapital: true, now });
setBuildings(h, townId, Object.assign({ core_router: 10, rack_hall: 10, battery_bank: 10, noc: 5, ops_lab: 5, research_lab: 8, rollout_depot: 5, internet_exchange: 3, firewall: 0 }, o.infra || {}));
for (const k of ['f13', 'f14', 'f15', 'f16']) h.db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', o.power === undefined ? 10 : o.power, townId, k);
const big = o.res || 4000;
h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ? WHERE id = ?', big, big, big, o.battery === undefined ? 1000 : o.battery, o.footprint || 0, townId);
if (o.units) giveUnits(h, townId, o.units);
return { name, userId, opId, townId, x, y };
}
// Another POP for an existing operator.
function addTown(h, op, o) {
o = o || {};
const { x, y } = landNear(h, o.x === undefined ? op.x + 2 : o.x, o.y === undefined ? op.y + 1 : o.y);
const id = createTown(h.db, { worldId: h.worldId, ownerId: op.opId, name: op.name + ' POP ' + (o.n || 2), x, y, isCapital: false, now: h.clock.now() });
setBuildings(h, id, Object.assign({ core_router: 3, rack_hall: 3, battery_bank: 3 }, o.infra || {}));
h.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000, battery = 100 WHERE id = ?', id);
return { townId: id, x, y };
}
function setBuildings(h, townId, levels) {
for (const type of Object.keys(levels)) {
if (h.db.get('SELECT 1 AS x FROM buildings WHERE town_id = ? AND key = ?', townId, type)) h.db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', levels[type], townId, type);
else h.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', townId, type, type, levels[type]);
}
}
function giveUnits(h, townId, units) {
for (const k of Object.keys(units)) {
const cur = h.db.get('SELECT count FROM town_units WHERE town_id = ? AND unit = ?', townId, k);
h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, k, (cur ? cur.count : 0) + units[k]);
}
}
const units = (h, townId) => { const o = {}; for (const r of h.db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) o[r.unit] = r.count; return o; };
const town = (h, id) => h.db.get('SELECT * FROM towns WHERE id = ?', id);
const reportsOf = (h, userId) => h.db.all('SELECT r.id, r.type, r.created_at, r.data, r.summary, rr.role FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? ORDER BY r.id', userId)
.map((r) => Object.assign({}, r, { data: JSON.parse(r.data), summary: JSON.parse(r.summary) }));
const notes = (h, userId, type) => h.db.all('SELECT type, payload FROM notifications WHERE user_id = ? AND type = ? ORDER BY id', userId, type).map((r) => JSON.parse(r.payload));
// All state a battle could touch, as one comparable value (determinism tests).
function snapshot(h) {
const q = (sql) => h.db.all(sql).map((r) => JSON.stringify(r));
return JSON.stringify([
q('SELECT id, owner_id, loyalty, round(fiber, 4) AS fiber, round(hardware, 4) AS hardware, round(capital, 4) AS capital FROM towns ORDER BY id'),
q('SELECT * FROM town_units ORDER BY town_id, unit'), q('SELECT * FROM stationed ORDER BY host_town_id, owner_town_id, unit'),
q('SELECT id, type, status, units, cargo, arrive_at FROM movements ORDER BY id'),
q('SELECT id, type, data FROM reports ORDER BY id'), q('SELECT * FROM operator_stats ORDER BY operator_id'),
q('SELECT id, due_at, type, status FROM events ORDER BY id'),
]);
}
module.exports = { setup, addOperator, addTown, setBuildings, giveUnits, units, town, reportsOf, notes, landNear, snapshot, H, R, D, crypto };