@mavonengine/cli 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11,10 +11,10 @@ import {
11
11
  MCP_CONFIG_FILE,
12
12
  version,
13
13
  writeMcpConfig
14
- } from "./chunk-TGGH7KA4.js";
14
+ } from "./chunk-7UZYGMGO.js";
15
15
 
16
16
  // src/index.ts
17
- import process11 from "process";
17
+ import process12 from "process";
18
18
 
19
19
  // src/commands/build.ts
20
20
  import { spawn as spawn4 } from "child_process";
@@ -99,6 +99,8 @@ function validateManifest(pkg, value) {
99
99
  if (runsOn(manifest.target, side) && typeof manifest[side] !== "string")
100
100
  throw new PluginConfigError(`${pkg}: "mavonengine.${side}" is required for target "${manifest.target}"`);
101
101
  }
102
+ if (manifest.publish !== void 0 && (typeof manifest.publish !== "string" || !manifest.publish))
103
+ throw new PluginConfigError(`${pkg}: "mavonengine.publish" must be a directory of the package`);
102
104
  return manifest;
103
105
  }
104
106
  function readPluginManifest(root, pkg) {
@@ -287,6 +289,21 @@ function tickSample(t) {
287
289
  maxCommandsPerTick: num(t.maxCommandsPerTick)
288
290
  };
289
291
  }
292
+ function queueSample(q) {
293
+ return {
294
+ timestamp: num(q.timestamp),
295
+ size: num(q.size),
296
+ running: num(q.running),
297
+ processed: num(q.processed),
298
+ retried: num(q.retried),
299
+ failed: num(q.failed)
300
+ };
301
+ }
302
+ function accountFrom(value) {
303
+ if (!isRecord(value) || typeof value.id !== "string" || !value.id)
304
+ return null;
305
+ return { id: value.id, name: strOrNull(value.name), guest: value.guest === true };
306
+ }
290
307
  function normalizeSnapshot(raw) {
291
308
  const s = section(raw);
292
309
  const world = section(s.world);
@@ -296,6 +313,7 @@ function normalizeSnapshot(raw) {
296
313
  const memory = section(s.memory);
297
314
  const physics = isRecord(s.physics) ? s.physics : null;
298
315
  const latency = isRecord(s.latencySimulation) ? s.latencySimulation : null;
316
+ const queue = isRecord(s.queue) ? s.queue : null;
299
317
  return {
300
318
  schemaVersion: num(s.schemaVersion, SUPPORTED_SCHEMA_VERSION),
301
319
  engineVersion: str(s.engineVersion, "unknown"),
@@ -320,7 +338,9 @@ function normalizeSnapshot(raw) {
320
338
  rttMs: numOrNull(connection.rttMs),
321
339
  bytesSent: num(connection.bytesSent),
322
340
  bytesReceived: num(connection.bytesReceived)
323
- } : null
341
+ } : null,
342
+ // Older servers, and servers without an auth plugin, have none
343
+ account: accountFrom(p.account)
324
344
  };
325
345
  }),
326
346
  world: {
@@ -350,7 +370,14 @@ function normalizeSnapshot(raw) {
350
370
  heapTotal: num(memory.heapTotal),
351
371
  external: num(memory.external)
352
372
  },
353
- latencySimulation: latency ? { fixedLatency: num(latency.fixedLatency), jitter: num(latency.jitter), packetLoss: num(latency.packetLoss) } : null
373
+ latencySimulation: latency ? { fixedLatency: num(latency.fixedLatency), jitter: num(latency.jitter), packetLoss: num(latency.packetLoss) } : null,
374
+ // Servers older than the queue have none
375
+ queue: queue ? {
376
+ driver: str(queue.driver, "unknown"),
377
+ working: queue.working !== false,
378
+ latest: isRecord(queue.latest) ? queueSample(queue.latest) : null,
379
+ history: arr(queue.history, queueSample)
380
+ } : null
354
381
  };
355
382
  }
356
383
  function normalizeLogs(raw) {
@@ -412,7 +439,8 @@ function normalizeSync(raw) {
412
439
  displayName: str(p.displayName, str(p.id)),
413
440
  tracked: Array.isArray(p.tracked) ? p.tracked.length : 0,
414
441
  ack: num(p.ack),
415
- lastState: lastState && { tick: num(lastState.tick), bytes: num(lastState.bytes), entities: num(lastState.entities) }
442
+ lastState: lastState && { tick: num(lastState.tick), bytes: num(lastState.bytes), entities: num(lastState.entities) },
443
+ account: accountFrom(p.account)
416
444
  };
417
445
  });
418
446
  const entities = arr(r.entities, (e) => ({ player: e.player === true, trackedBy: num(e.trackedBy) }));
@@ -473,6 +501,7 @@ function normalizePlugins(raw) {
473
501
  enabled: p.enabled !== false,
474
502
  installed: p.installed !== false,
475
503
  runningOnServer: p.runningOnServer === true,
504
+ ...p.database === true ? { database: true } : {},
476
505
  declaredPrefabs: strings(p.declaredPrefabs),
477
506
  usedPrefabs: strings(p.usedPrefabs),
478
507
  ...target ? { target } : {},
@@ -480,11 +509,52 @@ function normalizePlugins(raw) {
480
509
  };
481
510
  });
482
511
  }
512
+ function columns(value) {
513
+ return arr(value, (c) => ({
514
+ name: str(c.name, "?"),
515
+ type: str(c.type),
516
+ nullable: c.nullable !== false,
517
+ autoIncrement: c.autoIncrement === true,
518
+ hasDefault: c.hasDefault === true
519
+ }));
520
+ }
521
+ function normalizeDatabase(raw) {
522
+ const data = section(raw);
523
+ return {
524
+ provider: strOrNull(data.provider),
525
+ tables: arr(data.tables, (t) => ({ name: str(t.name, "?"), plugin: strOrNull(t.plugin), rows: numOrNull(t.rows), columns: columns(t.columns) })),
526
+ migrations: arr(data.migrations, (m) => ({
527
+ plugin: strOrNull(m.plugin),
528
+ table: str(m.table, "?"),
529
+ applied: arr(m.applied, (a) => ({ name: str(a.name, "?"), executedAt: strOrNull(a.executedAt) }))
530
+ }))
531
+ };
532
+ }
533
+ function normalizeTablePage(raw) {
534
+ const data = section(raw);
535
+ const rows = arr(data.rows, (row) => row);
536
+ return {
537
+ table: str(data.table, "?"),
538
+ columns: columns(data.columns),
539
+ rows,
540
+ total: num(data.total, rows.length),
541
+ offset: num(data.offset),
542
+ limit: num(data.limit, rows.length)
543
+ };
544
+ }
483
545
 
484
546
  // src/dashboard/MetricsClient.ts
485
547
  var MAX_LOG_LINES = 1e3;
486
548
  var MAX_REQUEST_LINES = 1e3;
487
549
  var MAX_PACKET_LINES = 2e3;
550
+ var TABLE_PAGE_ROWS = 50;
551
+ function tableError(err) {
552
+ if (err instanceof MetricsSourceError && err.status === "unauthorized")
553
+ return "The database needs the server's admin token: start the dashboard with --token <admin token>";
554
+ if (err instanceof MetricsSourceError && err.status === "forbidden")
555
+ return "The database is only shown on the server's own machine unless the server has an admin token";
556
+ return err.message;
557
+ }
488
558
  var MetricsSourceError = class extends Error {
489
559
  constructor(message, status) {
490
560
  super(message);
@@ -500,6 +570,7 @@ function httpSource({ url, token, timeoutMs = 3e3, fetch = globalThis.fetch }) {
500
570
  const syncUrl = new URL("dev/net/sync", url);
501
571
  const routesUrl = new URL("routes", url);
502
572
  const pluginsUrl = new URL("plugins", url);
573
+ const databaseUrl = new URL("database", url);
503
574
  async function request(target) {
504
575
  let res;
505
576
  try {
@@ -538,7 +609,14 @@ function httpSource({ url, token, timeoutMs = 3e3, fetch = globalThis.fetch }) {
538
609
  fetchSync: () => request(syncUrl.toString()),
539
610
  fetchPacket: (id) => request(new URL(`dev/net/packets/${id}`, url).toString()),
540
611
  fetchRoutes: () => request(routesUrl.toString()),
541
- fetchPlugins: () => request(pluginsUrl.toString())
612
+ fetchPlugins: () => request(pluginsUrl.toString()),
613
+ fetchDatabase: () => request(databaseUrl.toString()),
614
+ fetchTable: (name, offset, limit) => {
615
+ const tableUrl = new URL(`database/tables/${encodeURIComponent(name)}`, url);
616
+ tableUrl.searchParams.set("offset", String(offset));
617
+ tableUrl.searchParams.set("limit", String(limit));
618
+ return request(tableUrl.toString());
619
+ }
542
620
  };
543
621
  }
544
622
  var Feed = class {
@@ -605,7 +683,11 @@ var MetricsClient = class {
605
683
  routes: [],
606
684
  routesAvailable: source.fetchRoutes ? null : false,
607
685
  plugins: [],
608
- pluginsAvailable: source.fetchPlugins ? null : false
686
+ pluginsAvailable: source.fetchPlugins ? null : false,
687
+ database: null,
688
+ databaseAvailable: source.fetchDatabase ? null : false,
689
+ databaseError: null,
690
+ tableDetail: null
609
691
  };
610
692
  }
611
693
  source;
@@ -625,9 +707,42 @@ var MetricsClient = class {
625
707
  * so the dashboard only turns it on while its Network tab is shown.
626
708
  */
627
709
  watchNetwork = false;
710
+ /** Follow the database too. Off by default, as counting every table's rows isn't free: only while the Database tab is shown */
711
+ watchDatabase = false;
712
+ databaseFetchedAt = null;
628
713
  routesIntervalMs;
629
714
  /** Date.now() the endpoints and plugins were last fetched, null to fetch them with the next poll */
630
715
  projectFetchedAt = null;
716
+ /**
717
+ * Load a page of a table's rows into `state.tableDetail`, or close it with null.
718
+ */
719
+ async inspectTable(table, offset = 0, limit = TABLE_PAGE_ROWS) {
720
+ if (table === null) {
721
+ this.state.tableDetail = null;
722
+ this.notify();
723
+ return;
724
+ }
725
+ const previous = this.state.tableDetail?.table === table ? this.state.tableDetail.page : void 0;
726
+ if (!this.source.fetchTable) {
727
+ this.state.tableDetail = { table, offset, status: "error", error: "This source does not serve database tables" };
728
+ this.notify();
729
+ return;
730
+ }
731
+ this.state.tableDetail = { table, offset, status: "loading", page: previous };
732
+ this.notify();
733
+ let detail;
734
+ try {
735
+ detail = { table, offset, status: "ready", page: normalizeTablePage(await this.source.fetchTable(table, offset, limit)) };
736
+ } catch (err) {
737
+ const gone = err instanceof MetricsSourceError && err.status === "disabled";
738
+ detail = { table, offset, status: "error", page: previous, error: gone ? `The database has no table ${table} (any more)` : tableError(err) };
739
+ }
740
+ const current = this.state.tableDetail;
741
+ if (current?.table !== table || current.offset !== offset)
742
+ return;
743
+ this.state.tableDetail = detail;
744
+ this.notify();
745
+ }
631
746
  /**
632
747
  * Load the content of one packet into `state.packetDetail`, or close it with null.
633
748
  */
@@ -682,6 +797,7 @@ var MetricsClient = class {
682
797
  clearTimeout(this.timer);
683
798
  this.timer = null;
684
799
  this.projectFetchedAt = null;
800
+ this.databaseFetchedAt = null;
685
801
  await this.loop();
686
802
  }
687
803
  /**
@@ -705,6 +821,8 @@ var MetricsClient = class {
705
821
  this.state.packets = this.packets.entries;
706
822
  this.state.packetsAvailable = this.packets.available;
707
823
  }
824
+ if (this.watchDatabase)
825
+ await this.pollDatabase();
708
826
  } catch (err) {
709
827
  this.state.status = err instanceof MetricsSourceError ? err.status : "unreachable";
710
828
  this.state.error = err.message;
@@ -724,6 +842,35 @@ var MetricsClient = class {
724
842
  }
725
843
  }
726
844
  }
845
+ /**
846
+ * Fetch the database's tables, and the rows that are open again, unless they were fetched a moment ago.
847
+ * Its own errors stay its own: a dashboard without the admin token still shows everything else.
848
+ */
849
+ async pollDatabase(now = Date.now()) {
850
+ const { source, state } = this;
851
+ if (!source.fetchDatabase || state.databaseAvailable === false)
852
+ return;
853
+ if (this.databaseFetchedAt !== null && now - this.databaseFetchedAt < this.routesIntervalMs)
854
+ return;
855
+ try {
856
+ state.database = normalizeDatabase(await source.fetchDatabase());
857
+ state.databaseAvailable = true;
858
+ state.databaseError = null;
859
+ this.databaseFetchedAt = now;
860
+ } catch (err) {
861
+ if (err instanceof MetricsSourceError && err.status === "disabled") {
862
+ state.databaseAvailable = false;
863
+ return;
864
+ }
865
+ state.databaseError = tableError(err);
866
+ if (err instanceof MetricsSourceError && (err.status === "unauthorized" || err.status === "forbidden"))
867
+ this.databaseFetchedAt = now;
868
+ return;
869
+ }
870
+ const open = state.tableDetail;
871
+ if (open)
872
+ void this.inspectTable(open.table, open.offset);
873
+ }
727
874
  /**
728
875
  * Fetch the server's HTTP endpoints and plugins, unless they were fetched a moment ago
729
876
  */
@@ -813,7 +960,48 @@ var SIMULATED_PLUGINS = [
813
960
  declaredPrefabs: ["Tree", "Rock"],
814
961
  usedPrefabs: ["Tree"]
815
962
  },
816
- { package: "chat", enabled: false, installed: true, runningOnServer: false, version: "1.0.0", target: "both", declaredPrefabs: [], usedPrefabs: [] }
963
+ { package: "chat", enabled: false, installed: true, runningOnServer: false, version: "1.0.0", target: "both", declaredPrefabs: [], usedPrefabs: [] },
964
+ {
965
+ package: "@mavonengine/sqlite",
966
+ enabled: true,
967
+ installed: true,
968
+ runningOnServer: true,
969
+ database: true,
970
+ version: "0.0.1",
971
+ description: "A SQLite database for the game server and its plugins, on Node's built-in node:sqlite",
972
+ license: "MIT",
973
+ target: "server",
974
+ engine: ">=0.0.24",
975
+ declaredPrefabs: [],
976
+ usedPrefabs: []
977
+ }
978
+ ];
979
+ var SIMULATED_TABLES = [
980
+ {
981
+ name: "chat_messages",
982
+ plugin: "@mavonengine/chat",
983
+ columns: [
984
+ { name: "id", type: "INTEGER", nullable: false, autoIncrement: true, hasDefault: false },
985
+ { name: "player", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false },
986
+ { name: "text", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false },
987
+ { name: "sent_at", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false }
988
+ ],
989
+ rows: Array.from({ length: 137 }, (_, i) => ({ id: i + 1, player: `sim-0${i % 3 + 1}`, text: ["gg", "anyone near the tower?", "brb"][i % 3], sent_at: new Date(Date.UTC(2026, 10, 14, 12, 0, i * 7)).toISOString() }))
990
+ },
991
+ {
992
+ name: "game_scores",
993
+ plugin: null,
994
+ columns: [
995
+ { name: "player", type: "TEXT", nullable: false, autoIncrement: false, hasDefault: false },
996
+ { name: "score", type: "INTEGER", nullable: false, autoIncrement: false, hasDefault: true },
997
+ { name: "guild", type: "TEXT", nullable: true, autoIncrement: false, hasDefault: false }
998
+ ],
999
+ rows: [
1000
+ { player: "sim-01", score: 1200, guild: "Wolves" },
1001
+ { player: "sim-02", score: 950, guild: null },
1002
+ { player: "sim-03", score: 400, guild: "Bears" }
1003
+ ]
1004
+ }
817
1005
  ];
818
1006
  var SIMULATED_ROUTES = [
819
1007
  { method: "GET", path: "/api/game/health", source: "engine", params: {}, devOnly: false, summary: "Whether the server is up" },
@@ -851,6 +1039,8 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
851
1039
  const cpuHistory = [];
852
1040
  const bandwidthHistory = [];
853
1041
  const tickHistory = [];
1042
+ const queueHistory = [];
1043
+ let queued = 0;
854
1044
  const logs = [];
855
1045
  let previousPlayers = 0;
856
1046
  const joinedAt = [];
@@ -897,7 +1087,9 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
897
1087
  rttMs: Math.round(20 + i * 8 + random() * 10),
898
1088
  bytesSent: Math.round((now - joinedAt[i]) * (25 + i)),
899
1089
  bytesReceived: Math.round((now - joinedAt[i]) * (4 + i / 2))
900
- }
1090
+ },
1091
+ // As with an auth plugin: most have accounts, some play as guests, one in five got in without either
1092
+ account: i % 5 === 4 ? null : i % 3 === 2 ? { id: `guest-${i + 1}`, name: `Guest-${4800 + i}`, guest: true } : { id: `acc-${(i + 1).toString().padStart(4, "0")}`, name: `player${i + 1}`, guest: false }
901
1093
  }));
902
1094
  for (let i = previousPlayers; i < playerCount; i++) {
903
1095
  const address = players[i].connection.address;
@@ -947,7 +1139,8 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
947
1139
  position: player.position,
948
1140
  ack: player.lastProcessedSequenceId,
949
1141
  tracked: Array.from({ length: player.trackedEntities }, (_, i) => `entity-${i}`),
950
- lastState: lastStates.get(player.id) ?? null
1142
+ lastState: lastStates.get(player.id) ?? null,
1143
+ account: player.account
951
1144
  }));
952
1145
  if (step % 10 === 0)
953
1146
  request("GET", "/api/game/health", 200, 180, "198.51.100.7");
@@ -974,6 +1167,13 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
974
1167
  commandsPerSecond,
975
1168
  maxCommandsPerTick: playerCount + Math.floor(random() * 3)
976
1169
  });
1170
+ const dispatched = Math.round(playerCount * 0.3) + (step % 20 === 0 ? 25 : 0);
1171
+ const processed = Math.min(queued + dispatched, 4 + step % 3);
1172
+ const failed = processed > 0 && step % 13 === 0 ? 1 : 0;
1173
+ queued = queued + dispatched - processed;
1174
+ if (failed)
1175
+ log("error", "Job grant-reward failed all 3 tries: Error: reward service unavailable");
1176
+ push(queueHistory, { timestamp: now, size: queued, running: Math.min(queued, 1), processed: processed - failed, retried: step % 7 === 0 ? 1 : 0, failed });
977
1177
  const average = (ms) => {
978
1178
  const recent = cpuHistory.slice(-Math.max(1, Math.round(ms / sampleIntervalMs)));
979
1179
  return Math.round(recent.reduce((acc, h) => acc + h.cpuPercentage, 0) / recent.length * 100) / 100;
@@ -1012,7 +1212,8 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
1012
1212
  heapTotal: heapUsed + 3e7,
1013
1213
  external: 5e6
1014
1214
  },
1015
- latencySimulation: null
1215
+ latencySimulation: null,
1216
+ queue: { driver: "database", working: true, latest: queueHistory.at(-1), history: [...queueHistory] }
1016
1217
  };
1017
1218
  return snapshot;
1018
1219
  },
@@ -1062,6 +1263,19 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
1062
1263
  },
1063
1264
  async fetchPlugins() {
1064
1265
  return { plugins: SIMULATED_PLUGINS };
1266
+ },
1267
+ async fetchDatabase() {
1268
+ return {
1269
+ provider: "@mavonengine/sqlite",
1270
+ tables: SIMULATED_TABLES.map(({ rows, ...table }) => ({ ...table, rows: rows.length })),
1271
+ migrations: [{ plugin: "@mavonengine/chat", table: "chat__migrations", applied: [{ name: "001_init", executedAt: "2026-11-14T12:00:00.000Z" }] }]
1272
+ };
1273
+ },
1274
+ async fetchTable(name, offset, limit) {
1275
+ const table = SIMULATED_TABLES.find((t) => t.name === name);
1276
+ if (!table)
1277
+ throw new MetricsSourceError(`No table ${name}`, "disabled");
1278
+ return { table: name, columns: table.columns, rows: table.rows.slice(offset, offset + limit), total: table.rows.length, offset, limit };
1065
1279
  }
1066
1280
  };
1067
1281
  }
@@ -1228,7 +1442,49 @@ var LOGO_SIZES = [
1228
1442
  function initialViewState() {
1229
1443
  return { tab: 0, playerOffset: 0, logFromEnd: 0, requestTopId: null, selectedPlayerId: null, followSelectedPlayer: true, packetTopId: null, showPings: false, eventsOnly: false, selectedPacketId: null, followSelectedPacket: true, payloadOffset: 0 };
1230
1444
  }
1231
- var DASHBOARD_TABS = ["Overview", "Players", "Logs", "HTTP", "Network", "Routes", "Plugins"];
1445
+ function accountLabel(account) {
1446
+ if (!account)
1447
+ return "\u2014";
1448
+ const name = account.name ?? account.id;
1449
+ return account.guest ? `${name} (guest)` : name;
1450
+ }
1451
+ var DASHBOARD_TABS = ["Overview", "Players", "Logs", "HTTP", "Network", "Routes", "Plugins", "Database"];
1452
+ var DEFAULT_VISIBLE_ROWS = 20;
1453
+ function showsDatabase(view) {
1454
+ return DASHBOARD_TABS[view.tab] === "Database";
1455
+ }
1456
+ function selectedTable(view, database) {
1457
+ const tables = database?.tables ?? [];
1458
+ return tables.find((t) => t.name === view.selectedTable) ?? tables[0];
1459
+ }
1460
+ function handleDatabaseKey(view, database, key, pageRows = view.tableVisibleRows || DEFAULT_VISIBLE_ROWS) {
1461
+ if (!showsDatabase(view))
1462
+ return false;
1463
+ const tables = database?.tables ?? [];
1464
+ const shown = selectedTable(view, database);
1465
+ if (!shown)
1466
+ return false;
1467
+ const delta = key === "down" || key === "j" ? 1 : key === "up" || key === "k" ? -1 : 0;
1468
+ if (delta !== 0) {
1469
+ const next2 = tables[Math.max(0, Math.min(tables.length - 1, tables.indexOf(shown) + delta))];
1470
+ if (next2.name === shown.name)
1471
+ return false;
1472
+ view.selectedTable = next2.name;
1473
+ view.tableOffset = 0;
1474
+ return true;
1475
+ }
1476
+ const page = key === "right" || key === "pagedown" ? 1 : key === "left" || key === "pageup" ? -1 : 0;
1477
+ if (page === 0)
1478
+ return false;
1479
+ const offset = view.tableOffset ?? 0;
1480
+ const last = shown.rows === null ? Infinity : Math.max(0, shown.rows - pageRows);
1481
+ const next = Math.max(0, Math.min(last, offset + page * pageRows));
1482
+ if (next === offset)
1483
+ return false;
1484
+ view.selectedTable = shown.name;
1485
+ view.tableOffset = next;
1486
+ return true;
1487
+ }
1232
1488
  function showsNetwork(view) {
1233
1489
  return DASHBOARD_TABS[view.tab] === "Network";
1234
1490
  }
@@ -1243,9 +1499,12 @@ var STATUS_LABELS = {
1243
1499
  forbidden: "FORBIDDEN",
1244
1500
  disabled: "METRICS DISABLED"
1245
1501
  };
1246
- function tabForKey(key) {
1502
+ function dashboardTabs(state) {
1503
+ return state.plugins.some((plugin) => plugin.database) ? DASHBOARD_TABS : DASHBOARD_TABS.filter((tab) => tab !== "Database");
1504
+ }
1505
+ function tabForKey(key, tabCount = DASHBOARD_TABS.length) {
1247
1506
  const index = Number(key) - 1;
1248
- return Number.isInteger(index) && index >= 0 && index < DASHBOARD_TABS.length ? index : null;
1507
+ return Number.isInteger(index) && index >= 0 && index < Math.min(tabCount, DASHBOARD_TABS.length) ? index : null;
1249
1508
  }
1250
1509
  function sortedPlayers(players) {
1251
1510
  return [...players].sort((a, b) => a.id.localeCompare(b.id));
@@ -1395,6 +1654,7 @@ function statusColor(status, theme) {
1395
1654
  function renderDashboard(ui, theme, state, view, { transparent = false, startup, openKey = false, available, installer } = {}) {
1396
1655
  const { snapshot } = state;
1397
1656
  const starting = !snapshot && !!startup && (state.status === "connecting" || state.status === "unreachable");
1657
+ const tabs = dashboardTabs(state);
1398
1658
  ui.column({}, (root) => {
1399
1659
  header(root, theme, state);
1400
1660
  if (snapshot?.latencySimulation)
@@ -1406,8 +1666,10 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1406
1666
  } else if (!snapshot) {
1407
1667
  waiting(root, theme, state);
1408
1668
  } else {
1669
+ if (view.tab >= tabs.length)
1670
+ view.tab = 0;
1409
1671
  root.tabs({
1410
- tabs: DASHBOARD_TABS.map((name, i) => `${i + 1} ${name}`),
1672
+ tabs: tabs.map((name, i) => `${i + 1} ${name}`),
1411
1673
  active: view.tab,
1412
1674
  size: 1,
1413
1675
  onSelect: (index) => {
@@ -1428,6 +1690,8 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1428
1690
  routesPanel(root, theme, state, view, transparent);
1429
1691
  } else if (tab === "Plugins") {
1430
1692
  pluginsTab(root, theme, state, view, transparent, available, installer);
1693
+ } else if (tab === "Database") {
1694
+ databaseTab(root, theme, state, view, transparent);
1431
1695
  } else {
1432
1696
  root.responsive({
1433
1697
  [WIDE_LAYOUT]: (c) => wideLayout(c, theme, state, snapshot, view, transparent),
@@ -1441,7 +1705,7 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1441
1705
  items: [
1442
1706
  { key: "q", label: "Quit" },
1443
1707
  { key: "r", label: "Refresh" },
1444
- { key: `1-${DASHBOARD_TABS.length}`, label: "Tabs" },
1708
+ { key: `1-${tabs.length}`, label: "Tabs" },
1445
1709
  ...openKey && snapshot ? [{ key: "o", label: "Open game" }] : [],
1446
1710
  ...snapshot && DASHBOARD_TABS[view.tab] === "Players" ? [{ key: "\u2191\u2193", label: "Select player" }, ...view.selectedPlayerId ? [{ key: "esc", label: "Close" }] : []] : [],
1447
1711
  ...snapshot && showsNetwork(view) ? [
@@ -1450,7 +1714,8 @@ function renderDashboard(ui, theme, state, view, { transparent = false, startup,
1450
1714
  { key: "\u2191\u2193", label: "Open packet" },
1451
1715
  ...view.selectedPacketId !== null ? [{ key: "esc", label: "Close" }] : []
1452
1716
  ] : [],
1453
- ...snapshot && DASHBOARD_TABS[view.tab] === "Plugins" ? pluginKeys(state, view, available, installer) : []
1717
+ ...snapshot && DASHBOARD_TABS[view.tab] === "Plugins" ? pluginKeys(state, view, available, installer) : [],
1718
+ ...snapshot && showsDatabase(view) && state.database?.tables.length ? [...state.database.tables.length > 1 ? [{ key: "\u2191\u2193", label: "Select table" }] : [], { key: "\u2190\u2192", label: "Page rows" }] : []
1454
1719
  ],
1455
1720
  right: [starting ? { label: "STARTING", color: statusColor("connecting", theme) } : { label: STATUS_LABELS[state.status], color: statusColor(state.status, theme), active: state.status === "live" }]
1456
1721
  });
@@ -1547,12 +1812,22 @@ function waiting(ui, theme, state) {
1547
1812
  });
1548
1813
  }
1549
1814
  function wideLayout(ui, theme, state, snapshot, view, transparent) {
1550
- ui.grid({ columns: ["1fr", "1fr"], rows: [11, 11], size: 22 }, (grid) => {
1551
- grid.panel({ title: "CPU" }, (p) => cpuPanel(p, theme, snapshot));
1552
- grid.panel({ title: "Network" }, (p) => networkPanel(p, theme, snapshot));
1553
- grid.panel({ title: "Tick" }, (p) => tickPanel(p, theme, snapshot));
1554
- grid.panel({ title: "World" }, (p) => worldPanel(p, theme, snapshot));
1555
- });
1815
+ if (snapshot.queue) {
1816
+ ui.grid({ columns: ["1fr", "1fr", "1fr"], rows: [11, 11], size: 22 }, (grid) => {
1817
+ grid.panel({ title: "CPU" }, (p) => cpuPanel(p, theme, snapshot));
1818
+ grid.panel({ title: "Network" }, (p) => networkPanel(p, theme, snapshot));
1819
+ grid.panel({ title: "Tick" }, (p) => tickPanel(p, theme, snapshot));
1820
+ grid.panel({ title: queueTitle(snapshot.queue), colSpan: 2 }, (p) => queuePanel(p, theme, snapshot.queue));
1821
+ grid.panel({ title: "World" }, (p) => worldPanel(p, theme, snapshot));
1822
+ });
1823
+ } else {
1824
+ ui.grid({ columns: ["1fr", "1fr"], rows: [11, 11], size: 22 }, (grid) => {
1825
+ grid.panel({ title: "CPU" }, (p) => cpuPanel(p, theme, snapshot));
1826
+ grid.panel({ title: "Network" }, (p) => networkPanel(p, theme, snapshot));
1827
+ grid.panel({ title: "Tick" }, (p) => tickPanel(p, theme, snapshot));
1828
+ grid.panel({ title: "World" }, (p) => worldPanel(p, theme, snapshot));
1829
+ });
1830
+ }
1556
1831
  ui.row({ size: "1fr" }, (row) => {
1557
1832
  playersPanel(row, theme, snapshot, view, transparent);
1558
1833
  logsPanel(row, theme, state, view);
@@ -1562,6 +1837,8 @@ function narrowLayout(ui, theme, state, snapshot, view, transparent) {
1562
1837
  ui.panel({ title: "CPU", size: 9 }, (p) => cpuPanel(p, theme, snapshot));
1563
1838
  ui.panel({ title: "Network", size: 9 }, (p) => networkPanel(p, theme, snapshot));
1564
1839
  ui.panel({ title: "Tick", size: 9 }, (p) => tickPanel(p, theme, snapshot));
1840
+ if (snapshot.queue)
1841
+ ui.panel({ title: queueTitle(snapshot.queue), size: 9 }, (p) => queuePanel(p, theme, snapshot.queue));
1565
1842
  ui.panel({ title: "World", size: 11 }, (p) => worldPanel(p, theme, snapshot));
1566
1843
  playersPanel(ui, theme, snapshot, view, transparent);
1567
1844
  logsPanel(ui, theme, state, view);
@@ -1629,6 +1906,38 @@ function tickPanel(ui, theme, { tick, tickRate }) {
1629
1906
  { label: "Commands/s", value: `${latest?.commandsPerSecond ?? 0} (max ${latest?.maxCommandsPerTick ?? 0}/tick)` }
1630
1907
  ], { spread: true });
1631
1908
  }
1909
+ function queueTitle(queue) {
1910
+ return `Queue (${queue.driver}${queue.working ? "" : ", not worked here"})`;
1911
+ }
1912
+ function queueTotals(queue) {
1913
+ return queue.history.reduce((sum, s) => ({ processed: sum.processed + s.processed, failed: sum.failed + s.failed, retried: sum.retried + s.retried }), { processed: 0, failed: 0, retried: 0 });
1914
+ }
1915
+ function queuePanel(ui, theme, queue) {
1916
+ const latest = queue.latest;
1917
+ const totals = queueTotals(queue);
1918
+ const seconds = Math.round(queue.history.length > 1 ? (queue.history.at(-1).timestamp - queue.history[0].timestamp) / 1e3 : 0);
1919
+ const window = seconds >= 60 ? `${Math.round(seconds / 60)}m` : `${seconds}s`;
1920
+ ui.multiGraph([
1921
+ { label: "queued", values: queue.history.map((s) => s.size), color: theme.graph[0] },
1922
+ { label: "processed", values: queue.history.map((s) => s.processed), color: theme.graph[1] },
1923
+ { label: "failed", values: queue.history.map((s) => s.failed), color: theme.danger }
1924
+ ], {
1925
+ min: 0,
1926
+ max: Math.max(4, ...queue.history.map((s) => Math.max(s.size, s.processed, s.failed))),
1927
+ axis: true,
1928
+ axisFormat: (v) => String(Math.round(v)),
1929
+ legend: true,
1930
+ legendAlign: "right",
1931
+ size: "1fr"
1932
+ });
1933
+ ui.keyValues([
1934
+ { label: "Queued", value: String(latest?.size ?? 0), color: theme.graph[0] },
1935
+ { label: "Running", value: String(latest?.running ?? 0) },
1936
+ { label: `Processed ${window}`, value: String(totals.processed), color: theme.graph[1] },
1937
+ { label: `Retried ${window}`, value: String(totals.retried), color: totals.retried ? theme.warning : void 0 },
1938
+ { label: `Failed ${window}`, value: String(totals.failed), color: totals.failed ? theme.danger : void 0 }
1939
+ ], { spread: true });
1940
+ }
1632
1941
  function worldPanel(ui, theme, { players, world, physics, memory }) {
1633
1942
  ui.keyValues([
1634
1943
  { label: "Players", value: String(players.length), color: theme.primary },
@@ -1669,6 +1978,7 @@ function playerDetails(ui, theme, player, size) {
1669
1978
  ui.panel({ title: player.displayName, size }, (panel) => {
1670
1979
  panel.keyValues([
1671
1980
  { label: "ID", value: player.id },
1981
+ { label: "Account", value: player.account ? `${accountLabel(player.account)} \xB7 ${player.account.id}` : "none", color: player.account?.guest ? theme.warning : void 0 },
1672
1982
  { label: "Connected", value: formatDuration(player.connectedFor) },
1673
1983
  { label: "IP", value: connection ? connection.address ?? "pending" : "\u2014", color: theme.primary },
1674
1984
  { label: "RTT", value: connection?.rttMs != null ? formatMs(connection.rttMs) : "\u2014" },
@@ -1687,6 +1997,7 @@ function playersPanel(ui, theme, { players }, view, transparent, selectable = fa
1687
1997
  const maxOffset = Math.max(0, rows.length - 1);
1688
1998
  view.playerOffset = Math.min(view.playerOffset, maxOffset);
1689
1999
  const showNames = rows.some((p) => p.displayName !== p.id);
2000
+ const showAccounts = rows.some((p) => p.account);
1690
2001
  ui.panel({ title: `Players (${rows.length})`, size: "1fr" }, (panel) => {
1691
2002
  if (rows.length === 0) {
1692
2003
  panel.label("No players connected");
@@ -1720,6 +2031,7 @@ function playersPanel(ui, theme, { players }, view, transparent, selectable = fa
1720
2031
  },
1721
2032
  columns: [
1722
2033
  ...showNames ? [{ key: "displayName", title: "Name" }] : [],
2034
+ ...showAccounts ? [{ key: "account", title: "Account", render: (p) => accountLabel(p.account), color: (p) => p.account?.guest ? theme.warning : void 0 }] : [],
1723
2035
  { key: "id", title: "ID" },
1724
2036
  { key: "x", title: "X", width: 9, align: "right", render: (p) => p.position.x.toFixed(2) },
1725
2037
  { key: "y", title: "Y", width: 9, align: "right", render: (p) => p.position.y.toFixed(2) },
@@ -1932,6 +2244,7 @@ function syncPanel(ui, theme, { sync }, transparent, size = "1fr") {
1932
2244
  size: "1fr",
1933
2245
  columns: [
1934
2246
  { key: "displayName", title: "Player" },
2247
+ ...sync.players.some((p) => p.account) ? [{ key: "account", title: "Account", render: (p) => accountLabel(p.account) }] : [],
1935
2248
  { key: "tracked", title: "Tracked", width: 8, align: "right" },
1936
2249
  { key: "ack", title: "Ack", width: 9, align: "right" },
1937
2250
  { key: "bytes", title: "State", width: 10, align: "right", render: (p) => p.lastState ? formatBytes(p.lastState.bytes) : "\u2014" },
@@ -2306,6 +2619,117 @@ function pluginDetails(ui, theme, state, plugin, endpoints, size, transparent) {
2306
2619
  });
2307
2620
  });
2308
2621
  }
2622
+ var MAX_CELL_CHARS = 60;
2623
+ var LINE_BREAKS_RE = /\r?\n/g;
2624
+ function formatCell(value) {
2625
+ let text;
2626
+ if (value === null || value === void 0)
2627
+ text = "NULL";
2628
+ else if (typeof value === "object")
2629
+ text = JSON.stringify(value);
2630
+ else
2631
+ text = String(value).replace(LINE_BREAKS_RE, " \u23CE ");
2632
+ return text.length > MAX_CELL_CHARS ? `${text.slice(0, MAX_CELL_CHARS - 1)}\u2026` : text;
2633
+ }
2634
+ function tableOwner(table) {
2635
+ return table.plugin ?? "game";
2636
+ }
2637
+ function databaseTab(ui, theme, state, view, transparent) {
2638
+ const { database } = state;
2639
+ const notice = state.databaseAvailable === false ? "Not available: the server runs a @mavonengine/core release without GET /api/game/database" : !database ? state.databaseError ?? "Asking the server for its database\u2026" : !database.provider ? "The project has no database plugin. Add one with: mavonengine install @mavonengine/sqlite" : database.tables.length === 0 ? `No tables yet in the database of ${database.provider}` : null;
2640
+ if (notice) {
2641
+ ui.panel({ title: "Database", size: "1fr" }, (panel) => {
2642
+ panel.text([{ text: notice, fg: state.databaseError && !database ? theme.danger : theme.muted }]);
2643
+ });
2644
+ return;
2645
+ }
2646
+ const { tables, migrations } = database;
2647
+ const shown = selectedTable(view, database);
2648
+ let top = 0;
2649
+ if (state.databaseError)
2650
+ ui.text([{ text: ` ${state.databaseError} \u2014 showing what was read last`, fg: theme.danger }], { size: 1 });
2651
+ ui.panel({ title: `Tables in ${database.provider} (${tables.length})`, size: Math.min(tables.length, 8) + 3 }, (panel) => {
2652
+ panel.table({
2653
+ rows: tables,
2654
+ selected: tables.indexOf(shown),
2655
+ followSelection: true,
2656
+ onRow: (_row, index, y) => {
2657
+ if (y === 1)
2658
+ top = index;
2659
+ },
2660
+ onSelectRow: (visibleRow) => {
2661
+ const row = tables[top + visibleRow];
2662
+ if (!row)
2663
+ return;
2664
+ view.selectedTable = row.name;
2665
+ view.tableOffset = 0;
2666
+ ui.ctx.invalidate();
2667
+ },
2668
+ scrollbar: true,
2669
+ // Zebra stripes are solid fills, which would break transparency
2670
+ zebra: !transparent,
2671
+ size: "1fr",
2672
+ columns: [
2673
+ { key: "name", title: "Table" },
2674
+ { key: "plugin", title: "Plugin", color: (t) => t.plugin ? theme.primary : theme.muted, render: tableOwner },
2675
+ { key: "rows", title: "Rows", width: 10, align: "right", render: (t) => t.rows === null ? "?" : t.rows.toLocaleString("en-US") },
2676
+ { key: "columns", title: "Columns", width: 7, align: "right", render: (t) => String(t.columns.length) }
2677
+ ]
2678
+ });
2679
+ });
2680
+ tableRowsPanel(ui, theme, state, view, shown, transparent);
2681
+ if (migrations.length) {
2682
+ ui.panel({ title: "Migrations", size: Math.min(migrations.length, 4) + 2 }, (panel) => {
2683
+ for (const m of migrations.slice(0, 4)) {
2684
+ const names = m.applied.map((a) => a.name).join(", ") || "none";
2685
+ panel.text([
2686
+ { text: `${m.plugin ?? m.table} `, fg: m.plugin ? theme.primary : theme.muted },
2687
+ { text: `${m.applied.length} ran: `, fg: theme.muted },
2688
+ { text: names }
2689
+ ]);
2690
+ }
2691
+ });
2692
+ }
2693
+ }
2694
+ function tableRowsPanel(ui, theme, state, view, table, transparent) {
2695
+ const detail = state.tableDetail?.table === table.name ? state.tableDetail : null;
2696
+ const page = detail?.page;
2697
+ const total = page?.total ?? table.rows ?? 0;
2698
+ const shownRows = page ? Math.min(page.rows.length, view.tableVisibleRows || page.rows.length) : 0;
2699
+ const range = page && shownRows ? `rows ${(page.offset + 1).toLocaleString("en-US")}\u2013${(page.offset + shownRows).toLocaleString("en-US")} of ${total.toLocaleString("en-US")}` : `${total.toLocaleString("en-US")} rows`;
2700
+ ui.panel({ title: `${table.name} \xB7 ${range}${detail?.status === "loading" ? " \xB7 loading\u2026" : ""}`, size: "1fr" }, (panel) => {
2701
+ if (detail?.status === "error")
2702
+ panel.text([{ text: detail.error ?? "Could not load the rows", fg: theme.danger }], { size: 1 });
2703
+ if (!page) {
2704
+ if (detail?.status !== "error")
2705
+ panel.label("Loading the rows\u2026");
2706
+ return;
2707
+ }
2708
+ if (page.rows.length === 0) {
2709
+ panel.label("The table is empty");
2710
+ return;
2711
+ }
2712
+ const columns2 = page.columns.length ? page.columns.map((c) => c.name) : Object.keys(page.rows[0]);
2713
+ let visible = 0;
2714
+ panel.table({
2715
+ rows: page.rows,
2716
+ // Counts the rows that fit, so paging moves by a screenful
2717
+ onRow: (_row, _index, y) => {
2718
+ visible = Math.max(visible, y);
2719
+ view.tableVisibleRows = visible;
2720
+ },
2721
+ scrollbar: true,
2722
+ zebra: !transparent,
2723
+ size: "1fr",
2724
+ columns: columns2.map((name) => ({
2725
+ key: name,
2726
+ title: name,
2727
+ color: (row) => row[name] === null || row[name] === void 0 ? theme.muted : void 0,
2728
+ render: (row) => formatCell(row[name])
2729
+ }))
2730
+ });
2731
+ });
2732
+ }
2309
2733
 
2310
2734
  // src/commands/dashboard.ts
2311
2735
  var DASHBOARD_HELP = `Usage: mavonengine dashboard [options]
@@ -2399,6 +2823,16 @@ async function runDashboard(options, signal) {
2399
2823
  void client.refresh();
2400
2824
  }
2401
2825
  client.watchNetwork = watch;
2826
+ const watchDatabase = showsDatabase(view);
2827
+ if (watchDatabase && !client.watchDatabase) {
2828
+ client.watchDatabase = true;
2829
+ void client.refresh();
2830
+ }
2831
+ client.watchDatabase = watchDatabase;
2832
+ const table = watchDatabase ? selectedTable(view, client.state.database) : void 0;
2833
+ const detail = client.state.tableDetail;
2834
+ if (table && (detail?.table !== table.name || detail.offset !== (view.tableOffset ?? 0)))
2835
+ void client.inspectTable(table.name, view.tableOffset ?? 0);
2402
2836
  if ((client.state.packetDetail?.id ?? null) !== view.selectedPacketId)
2403
2837
  void client.inspectPacket(view.selectedPacketId);
2404
2838
  });
@@ -2428,12 +2862,12 @@ async function runDashboard(options, signal) {
2428
2862
  }
2429
2863
  if (event.key === "o" && options.clientUrl)
2430
2864
  openBrowser(options.clientUrl);
2431
- const tab = tabForKey(event.key);
2865
+ const tab = tabForKey(event.key, dashboardTabs(client.state).length);
2432
2866
  if (tab !== null) {
2433
2867
  view.tab = tab;
2434
2868
  app.invalidate();
2435
2869
  }
2436
- if (handlePlayersKey(view, client.state.snapshot, event.key) || handleNetworkKey(view, event.key, client.state.packets) || handlePluginsKey(view, client.state.plugins, event.key, installable2()))
2870
+ if (handlePlayersKey(view, client.state.snapshot, event.key) || handleNetworkKey(view, event.key, client.state.packets) || handlePluginsKey(view, client.state.plugins, event.key, installable2()) || handleDatabaseKey(view, client.state.database, event.key))
2437
2871
  app.invalidate();
2438
2872
  });
2439
2873
  app.on("exit", () => client.stop());
@@ -2495,9 +2929,15 @@ import process4 from "process";
2495
2929
  import { Readable, Transform } from "stream";
2496
2930
  import { pipeline } from "stream/promises";
2497
2931
  import AdmZip from "adm-zip";
2498
- var TEMPLATE_URL = "https://github.com/MavonEngine/Core/archive/refs/tags/0.0.18-alpha.zip";
2932
+ var TEMPLATE_URL = "https://github.com/MavonEngine/Core/archive/refs/tags/0.0.20-alpha.zip";
2499
2933
  var TEMPLATE_SUBPATH = "packages/multiplayer-template";
2500
2934
  var PROJECT_NAME_RE = /^[\w@./-][\w@./\- ]*$/;
2935
+ var NAME_SEPARATORS_RE = /[-_\s]+/;
2936
+ var PATH_SEPARATORS_RE = /[\\/]/;
2937
+ function appNameFor(projectName) {
2938
+ const words = projectName.split(PATH_SEPARATORS_RE).at(-1).split(NAME_SEPARATORS_RE).filter(Boolean);
2939
+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ") || projectName;
2940
+ }
2501
2941
  function projectDirFor(projectName, parentDir) {
2502
2942
  return resolve2(parentDir, projectName);
2503
2943
  }
@@ -2600,6 +3040,12 @@ async function createProject({ projectName, parentDir, report, signal, templateU
2600
3040
  writeFileSync2(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}
2601
3041
  `);
2602
3042
  }
3043
+ updateConfig(projectDir, (config) => {
3044
+ if (typeof config.appName === "string" && config.appName.trim())
3045
+ return false;
3046
+ config.appName = appNameFor(projectName);
3047
+ return true;
3048
+ });
2603
3049
  if (writeMcpConfig(projectDir))
2604
3050
  report.output(`Wrote ${MCP_CONFIG_FILE} so AI assistants with MCP support can inspect the running game server
2605
3051
  `);
@@ -2855,7 +3301,7 @@ var PluginInstaller = class {
2855
3301
  // src/dev/control.ts
2856
3302
  var MAX_BODY_BYTES = 8192;
2857
3303
  function readBody(req) {
2858
- return new Promise((resolve7, reject) => {
3304
+ return new Promise((resolve8, reject) => {
2859
3305
  let body = "";
2860
3306
  req.setEncoding("utf8");
2861
3307
  req.on("data", (chunk) => {
@@ -2865,7 +3311,7 @@ function readBody(req) {
2865
3311
  req.destroy();
2866
3312
  }
2867
3313
  });
2868
- req.on("end", () => resolve7(body));
3314
+ req.on("end", () => resolve8(body));
2869
3315
  req.on("error", reject);
2870
3316
  });
2871
3317
  }
@@ -2917,11 +3363,11 @@ function startDevControl(installer) {
2917
3363
  res.end(JSON.stringify({ error: err.message }));
2918
3364
  });
2919
3365
  });
2920
- return new Promise((resolve7, reject) => {
3366
+ return new Promise((resolve8, reject) => {
2921
3367
  server.once("error", reject);
2922
3368
  server.listen(0, "127.0.0.1", () => {
2923
3369
  const url = `http://127.0.0.1:${server.address().port}`;
2924
- resolve7({
3370
+ resolve8({
2925
3371
  url,
2926
3372
  token,
2927
3373
  env: { [DEV_CONTROL_URL_ENV]: url, [DEV_CONTROL_TOKEN_ENV]: token },
@@ -3170,7 +3616,7 @@ function startDevSession(root, options = {}) {
3170
3616
  let dev = startDev(root, options);
3171
3617
  let restarting = false;
3172
3618
  let settle;
3173
- const exited = new Promise((resolve7, reject) => settle = { resolve: resolve7, reject });
3619
+ const exited = new Promise((resolve8, reject) => settle = { resolve: resolve8, reject });
3174
3620
  const watch = (current) => {
3175
3621
  current.exited.then((code) => {
3176
3622
  if (current === dev && !restarting)
@@ -3484,6 +3930,8 @@ var NET_UNAVAILABLE = "The network debug endpoints are not available: the game s
3484
3930
  function packetParams(query) {
3485
3931
  return Object.fromEntries(Object.entries(query).filter(([, value]) => value !== void 0 && value !== "").map(([key, value]) => [key, String(value)]));
3486
3932
  }
3933
+ var DATABASE_UNAVAILABLE = "The game server doesn't show its database: it runs a @mavonengine/core release without GET /api/game/database";
3934
+ var DATABASE_DENIED = "The database is only shown with the server's admin token, since it holds what players did: pass it with --token (or MAVONENGINE_METRICS_TOKEN), or run the server on this machine without one";
3487
3935
  var DEV_UNAVAILABLE = "The dev endpoints are not available: the game server runs with NODE_ENV=production (they are never served there), or it uses a @mavonengine/core release without them";
3488
3936
  var GameServerClient = class {
3489
3937
  url;
@@ -3540,6 +3988,14 @@ var GameServerClient = class {
3540
3988
  routes() {
3541
3989
  return this.get("api/game/routes", {}, "The game server doesn't list its endpoints: it runs a @mavonengine/core release without GET /api/game/routes, or its metrics endpoints are off");
3542
3990
  }
3991
+ /** The database plugin, the tables with whose they are, their columns and row counts, and the migrations that ran */
3992
+ database() {
3993
+ return this.get("api/game/database", {}, DATABASE_UNAVAILABLE, DATABASE_DENIED);
3994
+ }
3995
+ /** A page of a table's rows */
3996
+ tableRows(table, offset = 0, limit = 50) {
3997
+ return this.get(`api/game/database/tables/${encodeURIComponent(table)}`, { offset: String(offset), limit: String(limit) }, `There is no table "${table}". database_overview lists them`, DATABASE_DENIED);
3998
+ }
3543
3999
  /** Packets and network events the server recorded, oldest first */
3544
4000
  packets(query = {}) {
3545
4001
  return this.get("api/game/dev/net/packets", packetParams(query), NET_UNAVAILABLE);
@@ -3588,7 +4044,7 @@ var GameServerClient = class {
3588
4044
  throw new GameServerError(body?.error ?? `Client dev server responded ${res.status} ${res.statusText}`);
3589
4045
  return body;
3590
4046
  }
3591
- async get(path, params = {}, notFound) {
4047
+ async get(path, params = {}, notFound, denied) {
3592
4048
  const target = new URL(path, this.base);
3593
4049
  for (const [key, value] of Object.entries(params))
3594
4050
  target.searchParams.set(key, value);
@@ -3601,10 +4057,16 @@ var GameServerClient = class {
3601
4057
  } catch (err) {
3602
4058
  throw new GameServerError(`Can't reach the game server at ${this.url}: ${err.message}. Is it running?`);
3603
4059
  }
4060
+ if (denied && (res.status === 401 || res.status === 403))
4061
+ throw new GameServerError(denied);
3604
4062
  if (res.status === 401)
3605
4063
  throw new GameServerError("Metrics token missing or wrong: pass --token or set MAVONENGINE_METRICS_TOKEN");
3606
4064
  if (res.status === 403)
3607
4065
  throw new GameServerError("The game server only answers localhost without a token: pass --token or set MAVONENGINE_METRICS_TOKEN");
4066
+ if (res.status === 500 && denied) {
4067
+ const body = await res.json().catch(() => null);
4068
+ throw new GameServerError(body?.error ?? "The game server could not read its database");
4069
+ }
3608
4070
  if (res.status === 404)
3609
4071
  throw new GameServerError(notFound ?? "Metrics endpoints not found: they are turned off in the server options, or it runs in production without a metrics token");
3610
4072
  if (res.status === 400)
@@ -3697,15 +4159,15 @@ function parseMcpArgs(args, env = process9.env) {
3697
4159
  async function runMcpCommand({ client, docsUrl, pluginsUrl }) {
3698
4160
  const [{ StdioServerTransport }, { createMcpServer }, { DocsClient }] = await Promise.all([
3699
4161
  import("@modelcontextprotocol/sdk/server/stdio.js"),
3700
- import("./server-QSZHAYK2.js"),
3701
- import("./docs-QCI5VKET.js")
4162
+ import("./server-AC5LBJ6A.js"),
4163
+ import("./docs-S2SWFUIL.js")
3702
4164
  ]);
3703
4165
  const docs = docsUrl ? new DocsClient(docsUrl) : void 0;
3704
4166
  const server = createMcpServer(client, docs, pluginsUrl ? { url: pluginsUrl } : void 0);
3705
4167
  const transport = new StdioServerTransport();
3706
- const closed = new Promise((resolve7) => {
3707
- transport.onclose = resolve7;
3708
- process9.stdin.on("end", resolve7);
4168
+ const closed = new Promise((resolve8) => {
4169
+ transport.onclose = resolve8;
4170
+ process9.stdin.on("end", resolve8);
3709
4171
  });
3710
4172
  await server.connect(transport);
3711
4173
  process9.stderr.write(`mavonengine mcp: reading the game server at ${client.url}
@@ -3809,17 +4271,152 @@ async function runPluginsCommand(options, io = { write: (text) => process10.stdo
3809
4271
  return 0;
3810
4272
  }
3811
4273
 
4274
+ // src/commands/publish.ts
4275
+ import { relative as relative4, resolve as resolve7 } from "path";
4276
+ import process11 from "process";
4277
+ import { parseArgs as parseArgs8 } from "util";
4278
+
4279
+ // ../core/dist/Plugins/publish.js
4280
+ import { copyFileSync, existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync as readdirSync2, statSync } from "fs";
4281
+ import { dirname as dirname4, join as join6, relative as relative3, sep } from "path";
4282
+ var PUBLISHED_DIR = "resources";
4283
+ function publishedDir(root, pkg) {
4284
+ return join6(root, PUBLISHED_DIR, ...pkg.split("/"));
4285
+ }
4286
+ function publishSourceDir(plugin) {
4287
+ const dir = plugin.manifest.publish;
4288
+ if (dir === void 0)
4289
+ return void 0;
4290
+ const full = resolveInside(plugin.dir, dir);
4291
+ if (!full)
4292
+ throw new PluginConfigError(`${plugin.package}: "mavonengine.publish" must be inside the package`);
4293
+ return full;
4294
+ }
4295
+ function filesIn(dir) {
4296
+ const files = [];
4297
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
4298
+ const path = join6(dir, entry.name);
4299
+ if (entry.isDirectory())
4300
+ files.push(...filesIn(path));
4301
+ else if (entry.isFile())
4302
+ files.push(path);
4303
+ }
4304
+ return files.sort();
4305
+ }
4306
+ function publishFiles(root, plugin, { force = false } = {}) {
4307
+ const source = publishSourceDir(plugin);
4308
+ if (!source)
4309
+ throw new PluginConfigError(`${plugin.package} has no files to publish`);
4310
+ if (!existsSync7(source) || !statSync(source).isDirectory())
4311
+ throw new PluginConfigError(`${plugin.package}: its publish directory ${relative3(plugin.dir, source)} is missing`);
4312
+ const target = publishedDir(root, plugin.package);
4313
+ return filesIn(source).map((from) => {
4314
+ const path = relative3(source, from).split(sep).join("/");
4315
+ const to = join6(target, ...path.split("/"));
4316
+ const existed = existsSync7(to);
4317
+ if (existed && !force)
4318
+ return { path, to, status: "kept" };
4319
+ mkdirSync2(dirname4(to), { recursive: true });
4320
+ copyFileSync(from, to);
4321
+ return { path, to, status: existed ? "replaced" : "published" };
4322
+ });
4323
+ }
4324
+
4325
+ // src/commands/publish.ts
4326
+ var PUBLISH_HELP = `Usage: mavonengine asset:publish <package...> [options]
4327
+
4328
+ Copy the files a plugin lets you change, like the mail plugin's layout, into the project's
4329
+ ${PUBLISHED_DIR}/<package>/. The plugin uses your copy from then on, so change it there.
4330
+
4331
+ Files you have already are kept, so publishing again only adds the plugin's new files.
4332
+
4333
+ Options:
4334
+ --force Replace the files you have with the plugin's
4335
+ --cwd <dir> Start looking for the project here (default: current directory)
4336
+ -h, --help Show this help
4337
+ `;
4338
+ function parsePublishArgs(args, cwd = process11.cwd()) {
4339
+ const { values, positionals } = parseArgs8({
4340
+ args,
4341
+ options: {
4342
+ force: { type: "boolean", default: false },
4343
+ cwd: { type: "string" },
4344
+ help: { type: "boolean", short: "h", default: false }
4345
+ },
4346
+ strict: true,
4347
+ allowPositionals: true
4348
+ });
4349
+ if (values.help)
4350
+ return "help";
4351
+ if (positionals.length === 0)
4352
+ throw new UsageError(`name the plugin to publish, e.g. mavonengine asset:publish @mavonengine/mail
4353
+
4354
+ ${PUBLISH_HELP}`);
4355
+ return { cwd: resolve7(cwd, values.cwd ?? "."), packages: positionals, force: values.force };
4356
+ }
4357
+ async function runPublishCommand(options, io = { write: (text) => void process11.stdout.write(text) }) {
4358
+ const root = findProjectRoot(options.cwd);
4359
+ if (!root) {
4360
+ io.write(`No MavonEngine project found from ${options.cwd}. Run this inside one.
4361
+ `);
4362
+ return 1;
4363
+ }
4364
+ let failed = false;
4365
+ for (const pkg of options.packages) {
4366
+ const plugin = (() => {
4367
+ try {
4368
+ return readPluginManifest(root, pkg);
4369
+ } catch (err) {
4370
+ io.write(`${pkg}: ${err.message}
4371
+ `);
4372
+ return null;
4373
+ }
4374
+ })();
4375
+ if (plugin === null) {
4376
+ failed = true;
4377
+ continue;
4378
+ }
4379
+ if (!plugin) {
4380
+ io.write(`${pkg} isn't installed, or is no MavonEngine plugin. Install it with: mavonengine install ${pkg}
4381
+ `);
4382
+ failed = true;
4383
+ continue;
4384
+ }
4385
+ try {
4386
+ const files = publishFiles(root, plugin, { force: options.force });
4387
+ io.write(`${pkg}:
4388
+ `);
4389
+ for (const file of files) {
4390
+ const shown = relative4(root, file.to).split("\\").join("/");
4391
+ io.write(file.status === "kept" ? ` kept ${shown} (you have it already, --force replaces it)
4392
+ ` : ` ${file.status.padEnd(10)} ${shown}
4393
+ `);
4394
+ }
4395
+ if (files.length === 0)
4396
+ io.write(" nothing to publish\n");
4397
+ } catch (err) {
4398
+ if (!(err instanceof PluginConfigError))
4399
+ throw err;
4400
+ io.write(`${err.message}
4401
+ `);
4402
+ failed = true;
4403
+ }
4404
+ }
4405
+ return failed ? 1 : 0;
4406
+ }
4407
+
3812
4408
  // src/index.ts
3813
4409
  var HELP = `Usage: mavonengine <command> [options]
3814
4410
 
3815
4411
  Commands:
3816
- create Create a project from the multiplayer template and start it
3817
- dashboard Live terminal dashboard for a running game server
3818
- dev Run the project's dev servers (game server and client)
3819
- install Install packages and register engine plugins in mavonengine.json
3820
- plugins List the plugins that are available to install
3821
- build Build the project for release, with the plugin assets it uses
3822
- mcp MCP server so AI assistants (any MCP client) can inspect a running game server
4412
+ create Create a project from the multiplayer template and start it
4413
+ dashboard Live terminal dashboard for a running game server
4414
+ dev Run the project's dev servers (game server and client)
4415
+ install Install packages and register engine plugins in mavonengine.json
4416
+ plugins List the plugins that are available to install
4417
+ asset:publish Copy a plugin's files you may change, like the mail layout, into the project
4418
+ build Build the project for release, with the plugin assets it uses
4419
+ mcp MCP server so AI assistants (any MCP client) can inspect a running game server
3823
4420
 
3824
4421
  Options:
3825
4422
  -h, --help Show help
@@ -3830,18 +4427,18 @@ Run 'mavonengine <command> --help' for command options.
3830
4427
  async function main(argv) {
3831
4428
  const [command, ...args] = argv;
3832
4429
  if (!command || command === "-h" || command === "--help" || command === "help") {
3833
- process11.stdout.write(HELP);
4430
+ process12.stdout.write(HELP);
3834
4431
  return 0;
3835
4432
  }
3836
4433
  if (command === "-v" || command === "--version") {
3837
- process11.stdout.write(`${version}
4434
+ process12.stdout.write(`${version}
3838
4435
  `);
3839
4436
  return 0;
3840
4437
  }
3841
4438
  if (command === "create") {
3842
4439
  const options = parseCreateArgs(args);
3843
4440
  if (options === "help") {
3844
- process11.stdout.write(CREATE_HELP);
4441
+ process12.stdout.write(CREATE_HELP);
3845
4442
  return 0;
3846
4443
  }
3847
4444
  return runCreateCommand(options);
@@ -3849,11 +4446,11 @@ async function main(argv) {
3849
4446
  if (command === "dashboard") {
3850
4447
  const options = parseDashboardArgs(args);
3851
4448
  if (options === "help") {
3852
- process11.stdout.write(DASHBOARD_HELP);
4449
+ process12.stdout.write(DASHBOARD_HELP);
3853
4450
  return 0;
3854
4451
  }
3855
- if (!process11.stdout.isTTY || !process11.stdin.isTTY) {
3856
- process11.stderr.write("mavonengine dashboard needs an interactive terminal\n");
4452
+ if (!process12.stdout.isTTY || !process12.stdin.isTTY) {
4453
+ process12.stderr.write("mavonengine dashboard needs an interactive terminal\n");
3857
4454
  return 1;
3858
4455
  }
3859
4456
  await runDashboard(options);
@@ -3862,7 +4459,7 @@ async function main(argv) {
3862
4459
  if (command === "dev") {
3863
4460
  const options = parseDevArgs(args);
3864
4461
  if (options === "help") {
3865
- process11.stdout.write(DEV_HELP);
4462
+ process12.stdout.write(DEV_HELP);
3866
4463
  return 0;
3867
4464
  }
3868
4465
  return runDevCommand(options);
@@ -3870,7 +4467,7 @@ async function main(argv) {
3870
4467
  if (command === "install" || command === "i" || command === "add") {
3871
4468
  const options = parseInstallArgs(args);
3872
4469
  if (options === "help") {
3873
- process11.stdout.write(INSTALL_HELP);
4470
+ process12.stdout.write(INSTALL_HELP);
3874
4471
  return 0;
3875
4472
  }
3876
4473
  return runInstallCommand(options);
@@ -3878,15 +4475,23 @@ async function main(argv) {
3878
4475
  if (command === "plugins") {
3879
4476
  const options = parsePluginsArgs(args);
3880
4477
  if (options === "help") {
3881
- process11.stdout.write(PLUGINS_HELP);
4478
+ process12.stdout.write(PLUGINS_HELP);
3882
4479
  return 0;
3883
4480
  }
3884
4481
  return runPluginsCommand(options);
3885
4482
  }
4483
+ if (command === "asset:publish") {
4484
+ const options = parsePublishArgs(args);
4485
+ if (options === "help") {
4486
+ process12.stdout.write(PUBLISH_HELP);
4487
+ return 0;
4488
+ }
4489
+ return runPublishCommand(options);
4490
+ }
3886
4491
  if (command === "mcp") {
3887
4492
  const options = parseMcpArgs(args);
3888
4493
  if (options === "help") {
3889
- process11.stdout.write(MCP_HELP);
4494
+ process12.stdout.write(MCP_HELP);
3890
4495
  return 0;
3891
4496
  }
3892
4497
  return runMcpCommand(options);
@@ -3894,7 +4499,7 @@ async function main(argv) {
3894
4499
  if (command === "build") {
3895
4500
  const options = parseBuildArgs(args);
3896
4501
  if (options === "help") {
3897
- process11.stdout.write(BUILD_HELP);
4502
+ process12.stdout.write(BUILD_HELP);
3898
4503
  return 0;
3899
4504
  }
3900
4505
  return runBuildCommand(options);
@@ -3903,9 +4508,9 @@ async function main(argv) {
3903
4508
 
3904
4509
  ${HELP}`);
3905
4510
  }
3906
- main(process11.argv.slice(2)).then((code) => process11.exit(code)).catch((err) => {
4511
+ main(process12.argv.slice(2)).then((code) => process12.exit(code)).catch((err) => {
3907
4512
  const isUsage = err instanceof UsageError || err.code?.startsWith("ERR_PARSE_ARGS");
3908
- process11.stderr.write(`mavonengine: ${err.message}
4513
+ process12.stderr.write(`mavonengine: ${err.message}
3909
4514
  `);
3910
- process11.exit(isUsage ? 2 : 1);
4515
+ process12.exit(isUsage ? 2 : 1);
3911
4516
  });