config and plugin
This commit is contained in:
@@ -17,6 +17,13 @@ function num(name: string, fallback: number): number {
|
||||
export const config = {
|
||||
serversRoot: req('SERVERS_ROOT', '/root/zombies/t5'),
|
||||
relDest: req('REL_DEST', 'runtime/plutonium/storage/t5/raw/scripts/sp'),
|
||||
// Per-kind destination sub-paths under each server's directory. `relDest`
|
||||
// above stays as the script fallback so existing deploys keep working.
|
||||
relDestScript: env.REL_DEST_SCRIPT ?? env.REL_DEST ?? 'runtime/plutonium/storage/t5/raw/scripts/sp',
|
||||
relDestConfig: env.REL_DEST_CONFIG ?? 'configs',
|
||||
relDestPlugin: env.REL_DEST_PLUGIN ?? 'runtime/plutonium/plugins',
|
||||
// Filename the baseline+overlays compose into. Same for every scope today.
|
||||
configTargetFile: env.CONFIG_TARGET_FILE ?? 'dedicated_sp.cfg',
|
||||
// Where on-disk copies of active beta files live for operator visibility.
|
||||
// Cleared per-beta on promote/rollback.
|
||||
betaArchiveDir: req('BETA_ARCHIVE_DIR', '/root/zombies/beta-archive'),
|
||||
@@ -48,5 +55,21 @@ export function rconConfigured(): boolean {
|
||||
return !!config.rcon.password;
|
||||
}
|
||||
|
||||
export const destOf = (server: string) => `${config.serversRoot}/${server}/${config.relDest}`;
|
||||
export type ArtifactKind = 'script' | 'config' | 'plugin' | 'baseline';
|
||||
|
||||
export function relDestForKind(kind: ArtifactKind): string {
|
||||
switch (kind) {
|
||||
case 'script': return config.relDestScript;
|
||||
case 'config': return config.relDestConfig;
|
||||
case 'baseline': return config.relDestConfig;
|
||||
case 'plugin': return config.relDestPlugin;
|
||||
}
|
||||
}
|
||||
|
||||
export const destOfKind = (server: string, kind: ArtifactKind) =>
|
||||
`${config.serversRoot}/${server}/${relDestForKind(kind)}`;
|
||||
|
||||
// Back-compat: existing call sites written before the multi-kind refactor
|
||||
// resolve to the script destination.
|
||||
export const destOf = (server: string) => destOfKind(server, 'script');
|
||||
export const betaArchiveOf = (betaId: number) => `${config.betaArchiveDir}/beta-${betaId}`;
|
||||
|
||||
@@ -44,6 +44,10 @@ function migrateServers(handle: Database.Database): void {
|
||||
// Additive columns on tables the script model owns. Same pattern as
|
||||
// migrateServers — CREATE TABLE IF NOT EXISTS won't backfill columns onto
|
||||
// pre-existing tables, so we introspect and ALTER as needed.
|
||||
const SCRIPTS_COLUMNS: Array<{ name: string; ddl: string }> = [
|
||||
{ name: 'kind', ddl: "ALTER TABLE scripts ADD COLUMN kind TEXT NOT NULL DEFAULT 'script'" }
|
||||
];
|
||||
|
||||
const SCRIPT_VERSIONS_COLUMNS: Array<{ name: string; ddl: string }> = [
|
||||
// state was added post-launch to make untested/tested/test-failed visible
|
||||
// in the UI. Existing rows default to 'untested' — this is safe because
|
||||
@@ -51,7 +55,16 @@ const SCRIPT_VERSIONS_COLUMNS: Array<{ name: string; ddl: string }> = [
|
||||
// the authoritative "promoted" signal), and any version already gated
|
||||
// through a ready-promote beta will be re-marked next time that state
|
||||
// machine fires.
|
||||
{ name: 'state', ddl: "ALTER TABLE script_versions ADD COLUMN state TEXT NOT NULL DEFAULT 'untested'" }
|
||||
{ name: 'state', ddl: "ALTER TABLE script_versions ADD COLUMN state TEXT NOT NULL DEFAULT 'untested'" },
|
||||
{ name: 'kind', ddl: "ALTER TABLE script_versions ADD COLUMN kind TEXT NOT NULL DEFAULT 'script'" }
|
||||
];
|
||||
|
||||
const BETA_SCRIPTS_COLUMNS: Array<{ name: string; ddl: string }> = [
|
||||
{ name: 'kind', ddl: "ALTER TABLE beta_scripts ADD COLUMN kind TEXT NOT NULL DEFAULT 'script'" }
|
||||
];
|
||||
|
||||
const DEPLOYMENT_SCRIPTS_COLUMNS: Array<{ name: string; ddl: string }> = [
|
||||
{ name: 'kind', ddl: "ALTER TABLE deployment_scripts ADD COLUMN kind TEXT NOT NULL DEFAULT 'script'" }
|
||||
];
|
||||
|
||||
const DEPLOYMENTS_COLUMNS: Array<{ name: string; ddl: string }> = [
|
||||
@@ -146,8 +159,16 @@ export function db(): Database.Database {
|
||||
dropLegacyBetaTables(_db);
|
||||
_db.exec(schemaSql);
|
||||
migrateServers(_db);
|
||||
migrateTable(_db, 'scripts', SCRIPTS_COLUMNS);
|
||||
migrateTable(_db, 'script_versions', SCRIPT_VERSIONS_COLUMNS);
|
||||
migrateTable(_db, 'beta_scripts', BETA_SCRIPTS_COLUMNS);
|
||||
migrateTable(_db, 'deployment_scripts', DEPLOYMENT_SCRIPTS_COLUMNS);
|
||||
migrateTable(_db, 'deployments', DEPLOYMENTS_COLUMNS);
|
||||
_db.exec(
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS idx_scripts_one_baseline_per_scope
|
||||
ON scripts(scope_type, scope_value) WHERE kind = 'baseline'`
|
||||
);
|
||||
_db.exec(`CREATE INDEX IF NOT EXISTS idx_scripts_kind ON scripts(kind)`);
|
||||
backfillMultiScriptJoins(_db);
|
||||
|
||||
return _db;
|
||||
|
||||
@@ -26,8 +26,14 @@ CREATE TABLE IF NOT EXISTS servers (
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
|
||||
-- One row per script (a logical thing, e.g. "HUD tweaks"). Name is unique and
|
||||
-- doubles as the slug in URLs.
|
||||
-- One row per artifact (a logical thing, e.g. "HUD tweaks"). Name is unique and
|
||||
-- doubles as the slug in URLs. The `kind` column discriminates:
|
||||
-- 'script' — GSC files deployed to runtime/plutonium/storage/t5/raw/scripts/sp
|
||||
-- 'plugin' — .dll files deployed to runtime/plutonium/plugins
|
||||
-- 'config' — cfg overlay (set K "V" lines) layered onto the baseline
|
||||
-- 'baseline' — full dedicated_sp.cfg; exactly one per scope
|
||||
-- Table + column names keep the "scripts" prefix for continuity; treat them
|
||||
-- polymorphically at the app layer.
|
||||
CREATE TABLE IF NOT EXISTS scripts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
@@ -35,9 +41,14 @@ CREATE TABLE IF NOT EXISTS scripts (
|
||||
scope_type TEXT, -- NULL | 'game' | 'map'
|
||||
scope_value TEXT, -- NULL | 't5' | 'zombie_theater'
|
||||
current_version_id INTEGER, -- FK → script_versions(id) after first promote
|
||||
kind TEXT NOT NULL DEFAULT 'script', -- 'script' | 'config' | 'plugin' | 'baseline'
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_scripts_scope ON scripts(scope_type, scope_value);
|
||||
CREATE INDEX IF NOT EXISTS idx_scripts_kind ON scripts(kind);
|
||||
-- At most one baseline per (scope_type, scope_value). Partial unique index.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_scripts_one_baseline_per_scope
|
||||
ON scripts(scope_type, scope_value) WHERE kind = 'baseline';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS script_versions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -48,6 +59,7 @@ CREATE TABLE IF NOT EXISTS script_versions (
|
||||
content BLOB NOT NULL,
|
||||
notes TEXT,
|
||||
state TEXT NOT NULL DEFAULT 'untested', -- 'untested' | 'tested' | 'test-failed'
|
||||
kind TEXT NOT NULL DEFAULT 'script', -- denormalized from scripts.kind for join-free filtering
|
||||
uploaded_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
UNIQUE(script_id, version)
|
||||
);
|
||||
@@ -105,6 +117,7 @@ CREATE TABLE IF NOT EXISTS beta_scripts (
|
||||
beta_id INTEGER NOT NULL REFERENCES betas(id) ON DELETE CASCADE,
|
||||
script_id INTEGER NOT NULL REFERENCES scripts(id) ON DELETE CASCADE,
|
||||
script_version_id INTEGER NOT NULL REFERENCES script_versions(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL DEFAULT 'script', -- denormalized from scripts.kind
|
||||
PRIMARY KEY (beta_id, script_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_beta_scripts_beta ON beta_scripts(beta_id);
|
||||
@@ -175,6 +188,7 @@ CREATE TABLE IF NOT EXISTS deployment_scripts (
|
||||
script_id INTEGER NOT NULL REFERENCES scripts(id) ON DELETE CASCADE,
|
||||
script_version_id INTEGER NOT NULL REFERENCES script_versions(id) ON DELETE CASCADE,
|
||||
prior_version_id INTEGER REFERENCES script_versions(id),
|
||||
kind TEXT NOT NULL DEFAULT 'script', -- denormalized from scripts.kind
|
||||
PRIMARY KEY (deployment_id, script_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_scripts_dep ON deployment_scripts(deployment_id);
|
||||
|
||||
+361
-35
@@ -1,22 +1,121 @@
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join, posix } from 'node:path';
|
||||
import { betaArchiveOf, destOf } from '../config.js';
|
||||
import { betaArchiveOf, config, destOf, destOfKind, type ArtifactKind } from '../config.js';
|
||||
import { db } from '../db/index.js';
|
||||
import { betaFile, oldFile, sha256Buffer } from './files.js';
|
||||
import { ensureDest, getServer, heldByBeta } from './servers.js';
|
||||
import {
|
||||
getBaselineForScope,
|
||||
getScript,
|
||||
getVersion,
|
||||
listPromotedOverlaysForScope,
|
||||
listVersions,
|
||||
serversMatchingScope,
|
||||
type ScopeType,
|
||||
type ScriptRow,
|
||||
type ScriptVersionRow
|
||||
} from './scripts.js';
|
||||
import { composeCfg } from './config-compose.js';
|
||||
import { recordScript, removeScript, getServerScript } from './inventory.js';
|
||||
import { emit } from '../pipeline/bus.js';
|
||||
import type { BetaStage } from '../pipeline/bus.js';
|
||||
|
||||
// Whether an artifact writes a dedicated on-disk file (script/plugin) or
|
||||
// contributes to a composed shared file (config/baseline).
|
||||
function isCollapsingKind(kind: ArtifactKind): boolean {
|
||||
return kind === 'config' || kind === 'baseline';
|
||||
}
|
||||
|
||||
// The path we should write to for the composed cfg on this server.
|
||||
function composedCfgPath(server: string): string {
|
||||
return join(destOfKind(server, 'config'), config.configTargetFile);
|
||||
}
|
||||
|
||||
// Compose the effective dedicated_sp.cfg for a given beta+server, taking
|
||||
// into account:
|
||||
// • baseline: from the beta if present, else the currently-promoted
|
||||
// baseline for the server's scope
|
||||
// • promoted overlays for the server's scope (excluding scripts being
|
||||
// replaced by this beta)
|
||||
// • this beta's overlays whose scope matches the server
|
||||
//
|
||||
// Returns null if no baseline is available (nothing to compose against).
|
||||
interface ComposeInputs {
|
||||
inBetaBaseline?: ScriptVersionRow;
|
||||
inBetaOverlays: Array<{ script: ScriptRow; version: ScriptVersionRow }>;
|
||||
}
|
||||
|
||||
function scopeAppliesToServer(
|
||||
scope: { scope_type: string | null; scope_value: string | null },
|
||||
server: { game: string | null; map: string | null }
|
||||
): boolean {
|
||||
if (!scope.scope_type || !scope.scope_value) return false;
|
||||
const field = scope.scope_type === 'game' ? server.game : server.map;
|
||||
return field === scope.scope_value;
|
||||
}
|
||||
|
||||
function composeCfgForServer(
|
||||
serverName: string,
|
||||
serverGame: string | null,
|
||||
serverMap: string | null,
|
||||
inputs: ComposeInputs
|
||||
): { text: string; baselineScriptId: number | null } | null {
|
||||
// Baseline: prefer the beta's baseline if its scope matches this server.
|
||||
let baselineText: string | null = null;
|
||||
let baselineScriptId: number | null = null;
|
||||
if (inputs.inBetaBaseline) {
|
||||
const s = getScript(inputs.inBetaBaseline.script_id);
|
||||
if (s && scopeAppliesToServer(s, { game: serverGame, map: serverMap })) {
|
||||
baselineText = inputs.inBetaBaseline.content.toString('utf8');
|
||||
baselineScriptId = s.id;
|
||||
}
|
||||
}
|
||||
// Fall back to the currently-promoted baseline for the server's game.
|
||||
if (baselineText === null && serverGame) {
|
||||
const promoted = getBaselineForScope('game', serverGame);
|
||||
if (promoted?.current_version_id) {
|
||||
const ver = getVersion(promoted.current_version_id);
|
||||
if (ver) {
|
||||
baselineText = ver.content.toString('utf8');
|
||||
baselineScriptId = promoted.id;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (baselineText === null) return null;
|
||||
|
||||
// In-beta script ids that are replacing promoted overlays — those get
|
||||
// skipped from the promoted overlay list to avoid double-applying an
|
||||
// older version of the same script.
|
||||
const inBetaScriptIds = new Set(inputs.inBetaOverlays.map((o) => o.script.id));
|
||||
|
||||
// Collect promoted overlays scoped to this server's game AND map.
|
||||
const promotedOverlays: Array<{ id: number; text: string }> = [];
|
||||
const promotedIdsSeen = new Set<number>();
|
||||
const pushIfScoped = (rows: ScriptRow[]) => {
|
||||
for (const s of rows) {
|
||||
if (promotedIdsSeen.has(s.id)) continue;
|
||||
if (inBetaScriptIds.has(s.id)) continue;
|
||||
if (!scopeAppliesToServer(s, { game: serverGame, map: serverMap })) continue;
|
||||
if (!s.current_version_id) continue;
|
||||
const ver = getVersion(s.current_version_id);
|
||||
if (!ver) continue;
|
||||
promotedOverlays.push({ id: s.id, text: ver.content.toString('utf8') });
|
||||
promotedIdsSeen.add(s.id);
|
||||
}
|
||||
};
|
||||
if (serverGame) pushIfScoped(listPromotedOverlaysForScope('game', serverGame));
|
||||
if (serverMap) pushIfScoped(listPromotedOverlaysForScope('map', serverMap));
|
||||
|
||||
// In-beta overlays scoped to this server.
|
||||
const inBetaScopedOverlays = inputs.inBetaOverlays
|
||||
.filter(({ script }) => scopeAppliesToServer(script, { game: serverGame, map: serverMap }))
|
||||
.map(({ script, version }) => ({ id: script.id, text: version.content.toString('utf8') }));
|
||||
|
||||
const composed = composeCfg(baselineText, [...promotedOverlays, ...inBetaScopedOverlays]);
|
||||
return { text: composed, baselineScriptId };
|
||||
}
|
||||
|
||||
export interface BetaRow {
|
||||
id: number;
|
||||
// Deprecated: the columns are still populated (NOT NULL on legacy schemas)
|
||||
@@ -51,6 +150,7 @@ export interface BetaScriptRow {
|
||||
beta_id: number;
|
||||
script_id: number;
|
||||
script_version_id: number;
|
||||
kind: ArtifactKind;
|
||||
}
|
||||
|
||||
export interface BetaServerScriptRow {
|
||||
@@ -168,7 +268,12 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
interface Resolved { script: ScriptRow; version: ScriptVersionRow }
|
||||
const resolved: Resolved[] = [];
|
||||
const seenScriptIds = new Set<number>();
|
||||
// For non-collapsing kinds (script/plugin), two artifacts targeting the
|
||||
// same rel_path within one beta is an internal race — reject up front.
|
||||
// Collapsing kinds (config/baseline) intentionally share a target file
|
||||
// (dedicated_sp.cfg) and compose, so they skip this check.
|
||||
const seenTargets = new Map<string, number>();
|
||||
let baselineInBeta: Resolved | null = null;
|
||||
for (const s of input.scripts) {
|
||||
if (seenScriptIds.has(s.scriptId)) {
|
||||
throw new BetaError(`script ${s.scriptId} listed twice in one beta`, 'duplicate-script');
|
||||
@@ -184,15 +289,25 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
'version-script-mismatch'
|
||||
);
|
||||
}
|
||||
// Two scripts writing to the same target rel_path in one beta is an
|
||||
// internal race — reject up front.
|
||||
if (seenTargets.has(script.target_rel_path)) {
|
||||
throw new BetaError(
|
||||
`scripts ${seenTargets.get(script.target_rel_path)} and ${script.id} share target ${script.target_rel_path}`,
|
||||
'duplicate-target'
|
||||
);
|
||||
if (!isCollapsingKind(script.kind)) {
|
||||
const targetKey = `${script.kind}:${script.target_rel_path}`;
|
||||
if (seenTargets.has(targetKey)) {
|
||||
throw new BetaError(
|
||||
`${script.kind}s ${seenTargets.get(targetKey)} and ${script.id} share target ${script.target_rel_path}`,
|
||||
'duplicate-target'
|
||||
);
|
||||
}
|
||||
seenTargets.set(targetKey, script.id);
|
||||
}
|
||||
if (script.kind === 'baseline') {
|
||||
if (baselineInBeta) {
|
||||
throw new BetaError(
|
||||
`two baselines in one beta (${baselineInBeta.script.id}, ${script.id}) — betas support at most one baseline`,
|
||||
'duplicate-target'
|
||||
);
|
||||
}
|
||||
baselineInBeta = { script, version };
|
||||
}
|
||||
seenTargets.set(script.target_rel_path, script.id);
|
||||
resolved.push({ script, version });
|
||||
}
|
||||
|
||||
@@ -231,7 +346,7 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
for (const { script } of resolved) {
|
||||
const owner = held.get(script.target_rel_path);
|
||||
if (owner) conflicts.push({ server: name, scriptId: script.id, heldByBetaId: owner });
|
||||
const dest = destOf(name);
|
||||
const dest = destOfKind(name, script.kind);
|
||||
const targetPath = join(dest, script.target_rel_path);
|
||||
const backupPath = join(dest, oldFile(script.target_rel_path));
|
||||
if (existsSync(targetPath) && existsSync(backupPath)) {
|
||||
@@ -242,7 +357,9 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
if (conflicts.length > 0) throw new BetaError('target already held by another beta', 'conflict', conflicts);
|
||||
if (blocked.length > 0) throw new BetaError('stale .OLD backups in the way', 'blocked-backup', blocked);
|
||||
|
||||
// Ensure destinations exist (create=true so a fresh server picks up cleanly).
|
||||
// Ensure destinations exist. The `ensureDest` helper covers only the
|
||||
// script destination today; config/plugin destinations are created
|
||||
// on-demand via mkdir during the write loop.
|
||||
for (const name of input.servers) {
|
||||
const ok = await ensureDest(name, true);
|
||||
if (!ok.ok) throw new BetaError(`dest not usable for ${name}: ${ok.reason}`, 'dest-fail');
|
||||
@@ -255,7 +372,7 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
VALUES (?, ?, 'bundle', ?, ?, 'running', ?)`
|
||||
);
|
||||
const insertBetaScript = db().prepare(
|
||||
`INSERT INTO beta_scripts (beta_id, script_id, script_version_id) VALUES (?, ?, ?)`
|
||||
`INSERT INTO beta_scripts (beta_id, script_id, script_version_id, kind) VALUES (?, ?, ?, ?)`
|
||||
);
|
||||
const insertBetaServer = db().prepare(
|
||||
`INSERT INTO beta_servers (beta_id, server, had_original, prior_version_id, stage, updated_at)
|
||||
@@ -277,7 +394,7 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
);
|
||||
betaId = Number(res.lastInsertRowid);
|
||||
for (const r of resolved) {
|
||||
insertBetaScript.run(betaId, r.script.id, r.version.id);
|
||||
insertBetaScript.run(betaId, r.script.id, r.version.id, r.script.kind);
|
||||
}
|
||||
for (const name of input.servers) {
|
||||
insertBetaServer.run(betaId, name, nowIso());
|
||||
@@ -294,17 +411,24 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
}
|
||||
})();
|
||||
|
||||
// Archive: one -beta.gsc per script.
|
||||
// Split resolved artifacts into non-collapsing (each writes its own file)
|
||||
// and collapsing (config/baseline overlay onto one shared dedicated_sp.cfg).
|
||||
const nonCollapsing = resolved.filter((r) => !isCollapsingKind(r.script.kind));
|
||||
const collapsingOverlays = resolved.filter((r) => r.script.kind === 'config');
|
||||
const collapsingBaseline = resolved.find((r) => r.script.kind === 'baseline');
|
||||
|
||||
// Archive: one -beta.gsc per non-collapsing artifact, plus one composed
|
||||
// preview per beta server for the config layer.
|
||||
const archive = betaArchiveOf(betaId);
|
||||
await mkdir(archive, { recursive: true });
|
||||
for (const r of resolved) {
|
||||
for (const r of nonCollapsing) {
|
||||
const bfile = betaFile(r.script.target_rel_path);
|
||||
await writeFile(join(archive, posix.basename(bfile)), r.version.content);
|
||||
}
|
||||
|
||||
// On-disk deploy per (server, script). If any script write fails on a
|
||||
// server, mark the whole server 'failed' — we can't restart a partially
|
||||
// deployed server safely. Remaining scripts on that server are skipped.
|
||||
// On-disk deploy per server. If any write fails on a server, mark the
|
||||
// whole server 'failed' — we can't restart a partially deployed server
|
||||
// safely. Remaining artifacts on that server are skipped.
|
||||
const updateStage = db().prepare(
|
||||
`UPDATE beta_servers
|
||||
SET stage = ?, error = ?, deployed_at = ?, updated_at = ?
|
||||
@@ -312,10 +436,12 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
);
|
||||
|
||||
for (const name of input.servers) {
|
||||
const dest = destOf(name);
|
||||
const serverRow = serverRows.find((r) => r.name === name)!;
|
||||
let firstErr: string | null = null;
|
||||
for (const { script, version } of resolved) {
|
||||
// 1. Non-collapsing artifacts: script/plugin — one file each.
|
||||
for (const { script, version } of nonCollapsing) {
|
||||
if (firstErr) break;
|
||||
const dest = destOfKind(name, script.kind);
|
||||
const bfile = betaFile(script.target_rel_path);
|
||||
const ofile = oldFile(script.target_rel_path);
|
||||
const targetPath = join(dest, script.target_rel_path);
|
||||
@@ -337,6 +463,51 @@ export async function openBeta(input: OpenBetaInput): Promise<OpenBetaResult> {
|
||||
firstErr = `${script.name}: ${(err as Error).message}`;
|
||||
}
|
||||
}
|
||||
// 2. Collapsing layer: compose the effective dedicated_sp.cfg from
|
||||
// baseline + all applicable overlays, write in place (no -beta
|
||||
// suffix — the game reads the exact filename), backup the prior
|
||||
// file as .OLD once.
|
||||
const hasCollapsing = collapsingBaseline || collapsingOverlays.length > 0;
|
||||
if (!firstErr && hasCollapsing) {
|
||||
try {
|
||||
const composedResult = composeCfgForServer(name, serverRow.game, serverRow.map, {
|
||||
inBetaBaseline: collapsingBaseline?.version,
|
||||
inBetaOverlays: collapsingOverlays
|
||||
});
|
||||
if (!composedResult) {
|
||||
throw new Error(
|
||||
`no baseline available for ${name} (game=${serverRow.game ?? '?'}) — upload one before running config overlays`
|
||||
);
|
||||
}
|
||||
const dest = destOfKind(name, 'config');
|
||||
await mkdir(dest, { recursive: true });
|
||||
const targetRel = config.configTargetFile;
|
||||
const targetPath = join(dest, targetRel);
|
||||
const backupPath = join(dest, oldFile(targetRel));
|
||||
if (existsSync(targetPath)) {
|
||||
await rename(targetPath, backupPath);
|
||||
const prior = getServerScript(name, targetRel);
|
||||
removeScript(name, targetRel);
|
||||
if (prior) {
|
||||
recordScript(name, oldFile(targetRel), prior.script_version_id, prior.sha256, prior.size, `beta:${betaId}`);
|
||||
}
|
||||
}
|
||||
const composedBuf = Buffer.from(composedResult.text, 'utf8');
|
||||
await writeFile(targetPath, composedBuf);
|
||||
recordScript(
|
||||
name,
|
||||
targetRel,
|
||||
null,
|
||||
sha256Buffer(composedBuf),
|
||||
composedBuf.byteLength,
|
||||
`beta:${betaId}`
|
||||
);
|
||||
// Archive the composed preview for operator visibility.
|
||||
await writeFile(join(archive, `${name}.${config.configTargetFile}`), composedBuf);
|
||||
} catch (err) {
|
||||
firstErr = `configs: ${(err as Error).message}`;
|
||||
}
|
||||
}
|
||||
const t = nowIso();
|
||||
if (firstErr) {
|
||||
updateStage.run('failed', `deploy: ${firstErr}`, t, t, betaId, name);
|
||||
@@ -390,16 +561,19 @@ export async function rollbackBeta(betaId: number): Promise<RollbackResult> {
|
||||
const dropped = new Set<string>();
|
||||
const warnings: string[] = [];
|
||||
|
||||
const hasCollapsing = bundle.some((b) => isCollapsingKind(b.script.kind));
|
||||
|
||||
for (const bs of servers) {
|
||||
const dest = destOf(bs.server);
|
||||
for (const { script } of bundle) {
|
||||
if (isCollapsingKind(script.kind)) continue; // handled once per server below
|
||||
const dest = destOfKind(bs.server, script.kind);
|
||||
const bfile = betaFile(script.target_rel_path);
|
||||
const ofile = oldFile(script.target_rel_path);
|
||||
const betaPath = join(dest, bfile);
|
||||
const backupPath = join(dest, ofile);
|
||||
const targetPath = join(dest, script.target_rel_path);
|
||||
|
||||
// Remove -beta.gsc regardless of stage.
|
||||
// Remove -beta.<ext> regardless of stage.
|
||||
if (existsSync(betaPath)) await rm(betaPath, { force: true });
|
||||
removeScript(bs.server, bfile);
|
||||
|
||||
@@ -430,6 +604,36 @@ export async function rollbackBeta(betaId: number): Promise<RollbackResult> {
|
||||
dropped.add(bs.server);
|
||||
}
|
||||
}
|
||||
|
||||
// Collapsing config layer: single restore for the shared cfg file.
|
||||
if (hasCollapsing) {
|
||||
const dest = destOfKind(bs.server, 'config');
|
||||
const targetRel = config.configTargetFile;
|
||||
const backupPath = join(dest, oldFile(targetRel));
|
||||
const targetPath = join(dest, targetRel);
|
||||
if (existsSync(backupPath)) {
|
||||
if (existsSync(targetPath)) await rm(targetPath, { force: true });
|
||||
await rename(backupPath, targetPath);
|
||||
removeScript(bs.server, oldFile(targetRel));
|
||||
const buf = await readFile(targetPath);
|
||||
recordScript(
|
||||
bs.server,
|
||||
targetRel,
|
||||
null,
|
||||
sha256Buffer(buf),
|
||||
buf.byteLength,
|
||||
`rollback:${betaId}`
|
||||
);
|
||||
restored.add(bs.server);
|
||||
} else if (existsSync(targetPath)) {
|
||||
// No .OLD ⇒ the beta wrote the cfg into a server that had
|
||||
// no pre-existing file. Remove the beta-written cfg to leave
|
||||
// the server clean.
|
||||
await rm(targetPath, { force: true });
|
||||
removeScript(bs.server, targetRel);
|
||||
dropped.add(bs.server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wipe archive + close out beta.
|
||||
@@ -500,7 +704,13 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
|
||||
const betaServerSet = new Set(listBetaServers(betaId).map((r) => r.server));
|
||||
|
||||
// Build a per-(script, server) plan: prior snapshot + intended write.
|
||||
// Split bundle into non-collapsing (per-file) and collapsing (composed cfg).
|
||||
const nonCollapsing = bundle.filter((b) => !isCollapsingKind(b.script.kind));
|
||||
const collapsing = bundle.filter((b) => isCollapsingKind(b.script.kind));
|
||||
const collapsingBaseline = collapsing.find((b) => b.script.kind === 'baseline');
|
||||
const collapsingOverlays = collapsing.filter((b) => b.script.kind === 'config');
|
||||
|
||||
// Build a per-(script, server) plan for non-collapsing artifacts.
|
||||
interface Plan {
|
||||
script: ScriptRow;
|
||||
version: ScriptVersionRow;
|
||||
@@ -512,18 +722,18 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
}
|
||||
const plans: Plan[] = [];
|
||||
|
||||
for (const { script, version } of bundle) {
|
||||
for (const { script, version } of nonCollapsing) {
|
||||
const scopeServers = script.scope_type && script.scope_value
|
||||
? serversMatchingScope(script.scope_type, script.scope_value)
|
||||
: [];
|
||||
const targets = new Set<string>([...betaServerSet, ...scopeServers]);
|
||||
|
||||
for (const name of targets) {
|
||||
const dest = destOfKind(name, script.kind);
|
||||
let plan: Plan;
|
||||
if (betaServerSet.has(name)) {
|
||||
const bss = getBetaServerScript(betaId, name, script.id);
|
||||
if (bss?.had_original) {
|
||||
const dest = destOf(name);
|
||||
const backupPath = join(dest, oldFile(script.target_rel_path));
|
||||
let priorContent: Buffer | null = null;
|
||||
let priorSha: string | null = null;
|
||||
@@ -544,7 +754,6 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
} else {
|
||||
// Non-beta matching-scope server: current on-disk file (if any)
|
||||
// is the "before" state for a promote-then-rollback round trip.
|
||||
const dest = destOf(name);
|
||||
const targetPath = join(dest, script.target_rel_path);
|
||||
if (existsSync(targetPath)) {
|
||||
const priorContent = await readFile(targetPath);
|
||||
@@ -567,7 +776,7 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
const planWritten = new Map<Plan, boolean>();
|
||||
const serverErr = new Map<string, string>();
|
||||
for (const p of plans) {
|
||||
const dest = destOf(p.server);
|
||||
const dest = destOfKind(p.server, p.script.kind);
|
||||
const bfile = betaFile(p.script.target_rel_path);
|
||||
const ofile = oldFile(p.script.target_rel_path);
|
||||
const targetPath = join(dest, p.script.target_rel_path);
|
||||
@@ -587,6 +796,91 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
}
|
||||
}
|
||||
|
||||
// Collapsing config layer: one composed cfg per server. Union of beta
|
||||
// servers + scope-matching servers for every collapsing artifact.
|
||||
interface CfgPlan {
|
||||
server: string;
|
||||
priorContent: Buffer | null;
|
||||
priorSha: string | null;
|
||||
composedContent: Buffer;
|
||||
composedSha: string;
|
||||
hadFile: boolean;
|
||||
}
|
||||
const cfgPlans: CfgPlan[] = [];
|
||||
if (collapsing.length > 0) {
|
||||
const cfgTargets = new Set<string>(betaServerSet);
|
||||
for (const { script } of collapsing) {
|
||||
if (script.scope_type && script.scope_value) {
|
||||
for (const s of serversMatchingScope(script.scope_type, script.scope_value)) {
|
||||
cfgTargets.add(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const name of cfgTargets) {
|
||||
const srv = getServer(name);
|
||||
if (!srv) {
|
||||
serverErr.set(name, 'unknown server during config promote');
|
||||
continue;
|
||||
}
|
||||
const composedResult = composeCfgForServer(name, srv.game, srv.map, {
|
||||
inBetaBaseline: collapsingBaseline?.version,
|
||||
inBetaOverlays: collapsingOverlays
|
||||
});
|
||||
if (!composedResult) {
|
||||
serverErr.set(name, `no baseline available for ${name} (game=${srv.game ?? '?'})`);
|
||||
continue;
|
||||
}
|
||||
const composedBuf = Buffer.from(composedResult.text, 'utf8');
|
||||
const composedSha = sha256Buffer(composedBuf);
|
||||
const dest = destOfKind(name, 'config');
|
||||
const targetRel = config.configTargetFile;
|
||||
const targetPath = join(dest, targetRel);
|
||||
const backupPath = join(dest, oldFile(targetRel));
|
||||
|
||||
let priorContent: Buffer | null = null;
|
||||
let priorSha: string | null = null;
|
||||
let hadFile = false;
|
||||
// Beta server: prior was the pre-beta content saved as .OLD.
|
||||
if (betaServerSet.has(name) && existsSync(backupPath)) {
|
||||
priorContent = await readFile(backupPath);
|
||||
priorSha = sha256Buffer(priorContent);
|
||||
hadFile = true;
|
||||
} else if (existsSync(targetPath)) {
|
||||
// Scope-expansion server: current on-disk cfg is the "before".
|
||||
priorContent = await readFile(targetPath);
|
||||
priorSha = sha256Buffer(priorContent);
|
||||
hadFile = true;
|
||||
}
|
||||
cfgPlans.push({ server: name, priorContent, priorSha, composedContent: composedBuf, composedSha, hadFile });
|
||||
}
|
||||
}
|
||||
|
||||
// Write composed cfg to each target.
|
||||
const cfgWritten = new Map<CfgPlan, boolean>();
|
||||
for (const cp of cfgPlans) {
|
||||
try {
|
||||
const dest = destOfKind(cp.server, 'config');
|
||||
await mkdir(dest, { recursive: true });
|
||||
const targetRel = config.configTargetFile;
|
||||
const targetPath = join(dest, targetRel);
|
||||
const backupPath = join(dest, oldFile(targetRel));
|
||||
// Beta server already has composed content at targetPath; overwrite
|
||||
// idempotently. Scope-expansion server: write in place. Either way
|
||||
// clear any lingering .OLD from the beta stage.
|
||||
await writeFile(targetPath, cp.composedContent);
|
||||
if (existsSync(backupPath)) {
|
||||
await rm(backupPath, { force: true });
|
||||
removeScript(cp.server, oldFile(targetRel));
|
||||
}
|
||||
cfgWritten.set(cp, true);
|
||||
} catch (err) {
|
||||
cfgWritten.set(cp, false);
|
||||
const msg = `configs: ${(err as Error).message}`;
|
||||
if (!serverErr.has(cp.server)) serverErr.set(cp.server, msg);
|
||||
console.error(`[promote] ${cp.server}/configs failed:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Build the aggregate deployment.
|
||||
const depId = promoteDeploymentId(betaId);
|
||||
const startedAt = nowIso();
|
||||
@@ -597,8 +891,8 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
VALUES (?, 'promote', ?, 'ui', NULL, NULL, NULL, ?)`
|
||||
);
|
||||
const insertDepScript = db().prepare(
|
||||
`INSERT INTO deployment_scripts (deployment_id, script_id, script_version_id, prior_version_id)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
`INSERT INTO deployment_scripts (deployment_id, script_id, script_version_id, prior_version_id, kind)
|
||||
VALUES (?, ?, ?, ?, ?)`
|
||||
);
|
||||
const insertDepServer = db().prepare(
|
||||
`INSERT INTO deployment_servers
|
||||
@@ -611,14 +905,19 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
|
||||
const uniqueServers = Array.from(new Set(plans.map((p) => p.server)));
|
||||
const uniqueServers = Array.from(new Set([
|
||||
...plans.map((p) => p.server),
|
||||
...cfgPlans.map((c) => c.server)
|
||||
]));
|
||||
|
||||
db().transaction(() => {
|
||||
insertDep.run(depId, startedAt, betaId);
|
||||
for (const { script, version } of bundle) {
|
||||
insertDepScript.run(depId, script.id, version.id, script.current_version_id);
|
||||
insertDepScript.run(depId, script.id, version.id, script.current_version_id, script.kind);
|
||||
}
|
||||
// deployment_files — one row per successful (script, server) write.
|
||||
// deployment_files — one row per successful (script, server) write for
|
||||
// non-collapsing artifacts, plus one row per (server, dedicated_sp.cfg)
|
||||
// for the composed config layer.
|
||||
for (const p of plans) {
|
||||
if (!planWritten.get(p)) continue;
|
||||
const verb = p.hadFile ? 'updated' : 'added';
|
||||
@@ -641,6 +940,28 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
`promote:${depId}`
|
||||
);
|
||||
}
|
||||
for (const cp of cfgPlans) {
|
||||
if (!cfgWritten.get(cp)) continue;
|
||||
const verb = cp.hadFile ? 'updated' : 'added';
|
||||
insertDepFile.run(
|
||||
depId,
|
||||
cp.server,
|
||||
verb,
|
||||
config.configTargetFile,
|
||||
cp.priorSha,
|
||||
cp.composedSha,
|
||||
cp.priorContent,
|
||||
cp.composedContent
|
||||
);
|
||||
recordScript(
|
||||
cp.server,
|
||||
config.configTargetFile,
|
||||
null,
|
||||
cp.composedSha,
|
||||
cp.composedContent.byteLength,
|
||||
`promote:${depId}`
|
||||
);
|
||||
}
|
||||
// deployment_servers — one row per unique server. Beta servers are
|
||||
// already restarted; scope-only servers still need the sweep to drain
|
||||
// and restart them.
|
||||
@@ -650,7 +971,9 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
insertDepServer.run(depId, name, 0, 'failed', null, err);
|
||||
continue;
|
||||
}
|
||||
const filesChanged = plans.filter((p) => p.server === name && planWritten.get(p)).length;
|
||||
const filesChanged =
|
||||
plans.filter((p) => p.server === name && planWritten.get(p)).length +
|
||||
cfgPlans.filter((c) => c.server === name && cfgWritten.get(c)).length;
|
||||
if (betaServerSet.has(name)) {
|
||||
const bsRestartedAt = db()
|
||||
.prepare(`SELECT restarted_at FROM beta_servers WHERE beta_id = ? AND server = ?`)
|
||||
@@ -671,7 +994,10 @@ export async function promoteBeta(betaId: number): Promise<PromoteResult> {
|
||||
const archive = betaArchiveOf(betaId);
|
||||
if (existsSync(archive)) await rm(archive, { recursive: true, force: true });
|
||||
|
||||
const landed = Array.from(new Set(plans.filter((p) => planWritten.get(p)).map((p) => p.server))).sort();
|
||||
const landed = Array.from(new Set([
|
||||
...plans.filter((p) => planWritten.get(p)).map((p) => p.server),
|
||||
...cfgPlans.filter((c) => cfgWritten.get(c)).map((c) => c.server)
|
||||
])).sort();
|
||||
|
||||
emit({ type: 'beta-state', betaId, state: 'promoted' });
|
||||
emit({ type: 'deployment-opened', deploymentId: depId, action: 'promote', servers: landed });
|
||||
@@ -706,7 +1032,7 @@ export async function unsetScopeAndCleanup(scriptId: number): Promise<string[]>
|
||||
const matched = serversMatchingScope(script.scope_type, script.scope_value);
|
||||
const cleaned: string[] = [];
|
||||
for (const name of matched) {
|
||||
const dest = destOf(name);
|
||||
const dest = destOfKind(name, script.kind);
|
||||
const targetPath = join(dest, script.target_rel_path);
|
||||
if (existsSync(targetPath)) {
|
||||
await rm(targetPath, { force: true });
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// Kino-style dedicated_sp.cfg files are line-oriented: `set KEY VALUE` lines
|
||||
// interleaved with `//` comments and blank lines. This module parses a
|
||||
// baseline, applies overlays (each a bag of `set KEY ...` lines that should
|
||||
// override the baseline's line for that KEY), and renders the composed file
|
||||
// back to text while preserving structure.
|
||||
//
|
||||
// Semantics:
|
||||
// - Overlays are matched to baseline lines by KEY only. Overlay's full raw
|
||||
// line replaces the baseline's line at that position.
|
||||
// - Overlay KEYs not present in the baseline are appended at the end.
|
||||
// - Multiple overlays apply in the order given. Later overlays override
|
||||
// earlier ones on the same KEY.
|
||||
// - Comments (// ...) and blank lines are preserved as-is.
|
||||
// - Line endings default to \n for the composed output. Baseline CRLF is
|
||||
// preserved if the baseline uses CRLF throughout.
|
||||
|
||||
interface CfgLine {
|
||||
kind: 'set' | 'raw';
|
||||
key?: string;
|
||||
line: string; // full line text without trailing newline
|
||||
}
|
||||
|
||||
interface ParsedCfg {
|
||||
order: CfgLine[];
|
||||
entries: Map<string, number>; // KEY → index in `order`
|
||||
eol: '\n' | '\r\n';
|
||||
}
|
||||
|
||||
// Matches `set KEY <rest of line>`. KEY is any non-whitespace token. Leading
|
||||
// whitespace and inline `//` comments after the value are preserved via the
|
||||
// captured full line.
|
||||
const SET_LINE_RE = /^\s*set\s+(\S+)\s+/;
|
||||
|
||||
export function parseCfg(text: string): ParsedCfg {
|
||||
// Detect CRLF vs LF. If either \r\n appears we treat the file as CRLF.
|
||||
const eol: '\n' | '\r\n' = /\r\n/.test(text) ? '\r\n' : '\n';
|
||||
const rawLines = text.split(/\r?\n/);
|
||||
// Trailing newline in the source produces an empty final split element —
|
||||
// drop it so we don't emit a spurious blank line on the round-trip.
|
||||
if (rawLines.length > 0 && rawLines[rawLines.length - 1] === '') rawLines.pop();
|
||||
|
||||
const order: CfgLine[] = [];
|
||||
const entries = new Map<string, number>();
|
||||
for (const line of rawLines) {
|
||||
const m = SET_LINE_RE.exec(line);
|
||||
if (m) {
|
||||
const key = m[1];
|
||||
// If the same KEY appears twice in the baseline, later occurrence
|
||||
// wins (matches how the Plutonium runtime reads the cfg top-down).
|
||||
entries.set(key, order.length);
|
||||
order.push({ kind: 'set', key, line });
|
||||
} else {
|
||||
order.push({ kind: 'raw', line });
|
||||
}
|
||||
}
|
||||
return { order, entries, eol };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an overlay's text. Returns KEY → full replacement line. Blank/comment
|
||||
* lines are ignored. If the overlay lists the same KEY twice, the last wins.
|
||||
*/
|
||||
export function parseOverlay(text: string): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
const lines = text.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
const m = SET_LINE_RE.exec(line);
|
||||
if (!m) continue;
|
||||
out.set(m[1], line);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface OverlayInput {
|
||||
/** Stable identifier used to determine application order (asc). */
|
||||
id: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compose a baseline cfg with a set of overlays. Overlays apply in `id`
|
||||
* ascending order — deterministic across scopes.
|
||||
*/
|
||||
export function composeCfg(baselineText: string, overlays: OverlayInput[]): string {
|
||||
const parsed = parseCfg(baselineText);
|
||||
|
||||
// Determine application order deterministically.
|
||||
const sorted = [...overlays].sort((a, b) => a.id - b.id);
|
||||
|
||||
// Merge overlay entries: later overlays win per KEY.
|
||||
const merged = new Map<string, string>();
|
||||
for (const overlay of sorted) {
|
||||
const kvs = parseOverlay(overlay.text);
|
||||
for (const [k, line] of kvs) merged.set(k, line);
|
||||
}
|
||||
|
||||
// Apply: replace in-place where the KEY exists in the baseline, else
|
||||
// append. Appended lines preserve overlay order (Map iteration order is
|
||||
// insertion order — which matches overlay id ascending).
|
||||
const appended: string[] = [];
|
||||
for (const [k, line] of merged) {
|
||||
const idx = parsed.entries.get(k);
|
||||
if (idx !== undefined) {
|
||||
parsed.order[idx] = { kind: 'set', key: k, line };
|
||||
} else {
|
||||
appended.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
const bodyLines = parsed.order.map((l) => l.line);
|
||||
if (appended.length > 0) {
|
||||
// Ensure a visual separator before appended lines if the baseline
|
||||
// doesn't already end with a blank line — cheap ergonomics for
|
||||
// operators inspecting the composed file.
|
||||
const last = bodyLines[bodyLines.length - 1];
|
||||
if (last !== undefined && last.trim() !== '') bodyLines.push('');
|
||||
bodyLines.push('// --- appended by electric-cherry overlays ---');
|
||||
for (const line of appended) bodyLines.push(line);
|
||||
}
|
||||
|
||||
// Preserve trailing newline: Plutonium tolerates either, but adding one
|
||||
// matches upstream cfg conventions.
|
||||
return bodyLines.join(parsed.eol) + parsed.eol;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { destOf } from '../config.js';
|
||||
import { destOfKind, type ArtifactKind } from '../config.js';
|
||||
import { db } from '../db/index.js';
|
||||
import { emit } from '../pipeline/bus.js';
|
||||
import { recordScript, removeScript } from './inventory.js';
|
||||
@@ -33,6 +33,7 @@ interface DepScriptRow {
|
||||
script_id: number;
|
||||
script_version_id: number;
|
||||
prior_version_id: number | null;
|
||||
kind: ArtifactKind;
|
||||
}
|
||||
|
||||
interface FileRow {
|
||||
@@ -49,6 +50,7 @@ interface FileRow {
|
||||
interface ScriptTargetRow {
|
||||
id: number;
|
||||
target_rel_path: string;
|
||||
kind: ArtifactKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -91,7 +93,8 @@ export async function rollbackPromoteDeployment(promoteId: string): Promise<Roll
|
||||
deployment_id: promoteId,
|
||||
script_id: dep.script_id,
|
||||
script_version_id: dep.script_version_id,
|
||||
prior_version_id: dep.prior_version_id
|
||||
prior_version_id: dep.prior_version_id,
|
||||
kind: 'script'
|
||||
}];
|
||||
}
|
||||
|
||||
@@ -105,18 +108,32 @@ export async function rollbackPromoteDeployment(promoteId: string): Promise<Roll
|
||||
// Map rel_path → scriptId (and prior_version_id) so we can restore the
|
||||
// inventory row's script_version_id correctly during file restore.
|
||||
const scriptByTarget = new Map<string, DepScriptRow>();
|
||||
const kindByScriptId = new Map<number, ArtifactKind>();
|
||||
if (scripts.length > 0) {
|
||||
const placeholders = scripts.map(() => '?').join(',');
|
||||
const targetRows = db()
|
||||
.prepare(`SELECT id, target_rel_path FROM scripts WHERE id IN (${placeholders})`)
|
||||
.prepare(`SELECT id, target_rel_path, kind FROM scripts WHERE id IN (${placeholders})`)
|
||||
.all(...scripts.map((s) => s.script_id)) as ScriptTargetRow[];
|
||||
const targetById = new Map<number, string>();
|
||||
for (const t of targetRows) targetById.set(t.id, t.target_rel_path);
|
||||
for (const t of targetRows) {
|
||||
targetById.set(t.id, t.target_rel_path);
|
||||
kindByScriptId.set(t.id, t.kind);
|
||||
}
|
||||
for (const s of scripts) {
|
||||
const t = targetById.get(s.script_id);
|
||||
if (t) scriptByTarget.set(t, s);
|
||||
}
|
||||
}
|
||||
const kindForRelPath = (relPath: string): ArtifactKind => {
|
||||
const owner = scriptByTarget.get(relPath);
|
||||
if (owner) return owner.kind ?? kindByScriptId.get(owner.script_id) ?? 'script';
|
||||
// Config/baseline aggregate rows have no per-artifact target_rel_path
|
||||
// mapping — the deployment_files row is keyed on the shared cfg name.
|
||||
// Any script/baseline in this deployment tagged as config/baseline
|
||||
// means the rollback for that path lives under the config destination.
|
||||
for (const s of scripts) if (s.kind === 'config' || s.kind === 'baseline') return 'config';
|
||||
return 'script';
|
||||
};
|
||||
|
||||
const newDepId = rollbackDeploymentId(promoteId);
|
||||
const startedAt = nowIso();
|
||||
@@ -133,9 +150,10 @@ export async function rollbackPromoteDeployment(promoteId: string): Promise<Roll
|
||||
const perServerFailures = new Map<string, string>();
|
||||
|
||||
for (const [server, files] of perServer) {
|
||||
const dest = destOf(server);
|
||||
try {
|
||||
for (const f of files) {
|
||||
const kind = kindForRelPath(f.rel_path);
|
||||
const dest = destOfKind(server, kind);
|
||||
const abs = join(dest, f.rel_path);
|
||||
await mkdir(join(dest, dirname(f.rel_path)), { recursive: true });
|
||||
const owningScript = scriptByTarget.get(f.rel_path);
|
||||
@@ -173,8 +191,8 @@ export async function rollbackPromoteDeployment(promoteId: string): Promise<Roll
|
||||
VALUES (?, 'rollback', ?, 'ui', NULL, NULL, NULL, NULL)`
|
||||
);
|
||||
const insertDepScript = db().prepare(
|
||||
`INSERT INTO deployment_scripts (deployment_id, script_id, script_version_id, prior_version_id)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
`INSERT INTO deployment_scripts (deployment_id, script_id, script_version_id, prior_version_id, kind)
|
||||
VALUES (?, ?, ?, ?, ?)`
|
||||
);
|
||||
const insertDepServer = db().prepare(
|
||||
`INSERT INTO deployment_servers
|
||||
@@ -193,7 +211,13 @@ export async function rollbackPromoteDeployment(promoteId: string): Promise<Roll
|
||||
// after rollback is the promote's prior; the "prior" of the rollback
|
||||
// is what was current up until this call (i.e. the promote's version).
|
||||
for (const s of scripts) {
|
||||
insertDepScript.run(newDepId, s.script_id, s.prior_version_id ?? s.script_version_id, s.script_version_id);
|
||||
insertDepScript.run(
|
||||
newDepId,
|
||||
s.script_id,
|
||||
s.prior_version_id ?? s.script_version_id,
|
||||
s.script_version_id,
|
||||
s.kind ?? 'script'
|
||||
);
|
||||
}
|
||||
for (const [server, files] of perServer) {
|
||||
if (perServerFailures.has(server)) {
|
||||
|
||||
+117
-12
@@ -1,5 +1,14 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { db } from '../db/index.js';
|
||||
import { config, type ArtifactKind } from '../config.js';
|
||||
|
||||
export type { ArtifactKind };
|
||||
|
||||
export const ARTIFACT_KINDS: ReadonlyArray<ArtifactKind> = ['script', 'config', 'plugin', 'baseline'];
|
||||
|
||||
export function isArtifactKind(v: unknown): v is ArtifactKind {
|
||||
return typeof v === 'string' && (ARTIFACT_KINDS as readonly string[]).includes(v);
|
||||
}
|
||||
|
||||
export type ScopeType = 'game' | 'map';
|
||||
|
||||
@@ -10,6 +19,7 @@ export interface ScriptRow {
|
||||
scope_type: ScopeType | null;
|
||||
scope_value: string | null;
|
||||
current_version_id: number | null;
|
||||
kind: ArtifactKind;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -24,6 +34,7 @@ export interface ScriptVersionRow {
|
||||
content: Buffer;
|
||||
notes: string | null;
|
||||
state: ScriptVersionState;
|
||||
kind: ArtifactKind;
|
||||
uploaded_at: string;
|
||||
}
|
||||
|
||||
@@ -51,6 +62,10 @@ export class ScriptError extends Error {
|
||||
| 'in-use-beta'
|
||||
| 'has-scope'
|
||||
| 'has-active-beta'
|
||||
| 'invalid-kind'
|
||||
| 'baseline-requires-scope'
|
||||
| 'baseline-exists'
|
||||
| 'empty-overlay'
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
@@ -68,10 +83,51 @@ export function getScriptByName(name: string): ScriptRow | undefined {
|
||||
return db().prepare('SELECT * FROM scripts WHERE name = ?').get(name) as ScriptRow | undefined;
|
||||
}
|
||||
|
||||
export function listScripts(): ScriptRow[] {
|
||||
export function listScripts(kind?: ArtifactKind): ScriptRow[] {
|
||||
if (kind) {
|
||||
return db().prepare('SELECT * FROM scripts WHERE kind = ? ORDER BY name').all(kind) as ScriptRow[];
|
||||
}
|
||||
return db().prepare('SELECT * FROM scripts ORDER BY name').all() as ScriptRow[];
|
||||
}
|
||||
|
||||
// Look up the current baseline for a given scope. Baselines have exactly one
|
||||
// current_version_id after their first promote; before that they are still
|
||||
// gated through the beta pipeline. `includeUntested` returns the baseline row
|
||||
// even without a promoted version (used at beta-open time when the baseline is
|
||||
// being introduced in the same beta as the overlays).
|
||||
export function getBaselineForScope(scopeType: ScopeType, scopeValue: string): ScriptRow | undefined {
|
||||
return db()
|
||||
.prepare(
|
||||
`SELECT * FROM scripts
|
||||
WHERE kind = 'baseline' AND scope_type = ? AND scope_value = ?
|
||||
LIMIT 1`
|
||||
)
|
||||
.get(scopeType, scopeValue) as ScriptRow | undefined;
|
||||
}
|
||||
|
||||
// All promoted config overlays for a scope. `exceptScriptIds` lets callers
|
||||
// skip overlays whose new version is bundled in a beta — avoids applying the
|
||||
// prior version twice when composing.
|
||||
export function listPromotedOverlaysForScope(
|
||||
scopeType: ScopeType,
|
||||
scopeValue: string,
|
||||
exceptScriptIds: number[] = []
|
||||
): ScriptRow[] {
|
||||
const rows = db()
|
||||
.prepare(
|
||||
`SELECT * FROM scripts
|
||||
WHERE kind = 'config'
|
||||
AND scope_type = ?
|
||||
AND scope_value = ?
|
||||
AND current_version_id IS NOT NULL
|
||||
ORDER BY id`
|
||||
)
|
||||
.all(scopeType, scopeValue) as ScriptRow[];
|
||||
if (exceptScriptIds.length === 0) return rows;
|
||||
const skip = new Set(exceptScriptIds);
|
||||
return rows.filter((r) => !skip.has(r.id));
|
||||
}
|
||||
|
||||
export function listVersions(scriptId: number): ScriptVersionRow[] {
|
||||
return db()
|
||||
.prepare('SELECT * FROM script_versions WHERE script_id = ? ORDER BY version DESC')
|
||||
@@ -94,18 +150,57 @@ export function getLatestVersion(scriptId: number): ScriptVersionRow | undefined
|
||||
|
||||
export interface CreateScriptInput {
|
||||
name: string;
|
||||
targetRelPath: string;
|
||||
/** Optional: defaults to the upload filename for script/plugin, and to
|
||||
* the configured config target file for config/baseline. */
|
||||
targetRelPath?: string;
|
||||
scopeType?: ScopeType | null;
|
||||
scopeValue?: string | null;
|
||||
content: Buffer;
|
||||
notes?: string;
|
||||
/** Defaults to 'script' for back-compat with existing callers. */
|
||||
kind?: ArtifactKind;
|
||||
}
|
||||
|
||||
// Insert script + version 1 in one transaction. Scope may be set at creation
|
||||
// because the script has no current_version_id yet (nothing to gate).
|
||||
export function createScript(input: CreateScriptInput): { script: ScriptRow; version: ScriptVersionRow } {
|
||||
if (!input.name.trim()) throw new ScriptError('script name is required', 'name-empty');
|
||||
if (!input.targetRelPath.trim()) throw new ScriptError('target rel path is required', 'path-empty');
|
||||
const kind: ArtifactKind = input.kind ?? 'script';
|
||||
if (!isArtifactKind(kind)) throw new ScriptError(`invalid kind: ${input.kind}`, 'invalid-kind');
|
||||
|
||||
// Target file defaulting per kind. Configs and baselines all compose into
|
||||
// the same on-disk cfg file, so the operator never picks it.
|
||||
let targetRelPath = input.targetRelPath?.trim() ?? '';
|
||||
if (!targetRelPath && (kind === 'config' || kind === 'baseline')) {
|
||||
targetRelPath = config.configTargetFile;
|
||||
}
|
||||
if (!targetRelPath) throw new ScriptError('target rel path is required', 'path-empty');
|
||||
|
||||
// Kind-specific validation.
|
||||
if (kind === 'baseline') {
|
||||
if (!input.scopeType || !input.scopeValue) {
|
||||
throw new ScriptError('baselines require a scope (game or map)', 'baseline-requires-scope');
|
||||
}
|
||||
if (getBaselineForScope(input.scopeType, input.scopeValue)) {
|
||||
throw new ScriptError(
|
||||
`a baseline already exists for ${input.scopeType}=${input.scopeValue}`,
|
||||
'baseline-exists'
|
||||
);
|
||||
}
|
||||
}
|
||||
if (kind === 'config') {
|
||||
if (!input.scopeType || !input.scopeValue) {
|
||||
throw new ScriptError('config overlays require a scope', 'invalid-scope');
|
||||
}
|
||||
// Reject empty or comment-only overlays — nothing to apply.
|
||||
const text = input.content.toString('utf8');
|
||||
if (!/^\s*set\s+\S+\s+/m.test(text)) {
|
||||
throw new ScriptError(
|
||||
'config overlay must contain at least one `set KEY VALUE` line',
|
||||
'empty-overlay'
|
||||
);
|
||||
}
|
||||
}
|
||||
validateScope(input.scopeType ?? null, input.scopeValue ?? null);
|
||||
if (getScriptByName(input.name)) throw new ScriptError(`script "${input.name}" already exists`, 'name-taken');
|
||||
|
||||
@@ -113,20 +208,20 @@ export function createScript(input: CreateScriptInput): { script: ScriptRow; ver
|
||||
const size = input.content.byteLength;
|
||||
|
||||
const insertScript = db().prepare(
|
||||
`INSERT INTO scripts (name, target_rel_path, scope_type, scope_value)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
`INSERT INTO scripts (name, target_rel_path, scope_type, scope_value, kind)
|
||||
VALUES (?, ?, ?, ?, ?)`
|
||||
);
|
||||
const insertVersion = db().prepare(
|
||||
`INSERT INTO script_versions (script_id, version, sha256, size, content, notes)
|
||||
VALUES (?, 1, ?, ?, ?, ?)`
|
||||
`INSERT INTO script_versions (script_id, version, sha256, size, content, notes, kind)
|
||||
VALUES (?, 1, ?, ?, ?, ?, ?)`
|
||||
);
|
||||
|
||||
let scriptId!: number;
|
||||
let versionId!: number;
|
||||
db().transaction(() => {
|
||||
const s = insertScript.run(input.name, input.targetRelPath, input.scopeType ?? null, input.scopeValue ?? null);
|
||||
const s = insertScript.run(input.name, targetRelPath, input.scopeType ?? null, input.scopeValue ?? null, kind);
|
||||
scriptId = Number(s.lastInsertRowid);
|
||||
const v = insertVersion.run(scriptId, sha, size, input.content, input.notes ?? null);
|
||||
const v = insertVersion.run(scriptId, sha, size, input.content, input.notes ?? null, kind);
|
||||
versionId = Number(v.lastInsertRowid);
|
||||
})();
|
||||
|
||||
@@ -140,16 +235,26 @@ export function uploadNewVersion(scriptId: number, content: Buffer, notes?: stri
|
||||
const script = getScript(scriptId);
|
||||
if (!script) throw new ScriptError(`no such script (id=${scriptId})`, 'no-such-script');
|
||||
|
||||
if (script.kind === 'config') {
|
||||
const text = content.toString('utf8');
|
||||
if (!/^\s*set\s+\S+\s+/m.test(text)) {
|
||||
throw new ScriptError(
|
||||
'config overlay must contain at least one `set KEY VALUE` line',
|
||||
'empty-overlay'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const latest = getLatestVersion(scriptId);
|
||||
const nextVersion = (latest?.version ?? 0) + 1;
|
||||
const sha = sha256(content);
|
||||
|
||||
const res = db()
|
||||
.prepare(
|
||||
`INSERT INTO script_versions (script_id, version, sha256, size, content, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`
|
||||
`INSERT INTO script_versions (script_id, version, sha256, size, content, notes, kind)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(scriptId, nextVersion, sha, content.byteLength, content, notes ?? null);
|
||||
.run(scriptId, nextVersion, sha, content.byteLength, content, notes ?? null, script.kind);
|
||||
return getVersion(Number(res.lastInsertRowid))!;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
<div class="tabs">
|
||||
<a href="/" class:on={$page.url.pathname === '/'}>Fleet</a>
|
||||
<a href="/scripts" class:on={$page.url.pathname.startsWith('/scripts')}>Scripts</a>
|
||||
<a href="/configs" class:on={$page.url.pathname.startsWith('/configs')}>Configs</a>
|
||||
<a href="/plugins" class:on={$page.url.pathname.startsWith('/plugins')}>Plugins</a>
|
||||
<a href="/deployments" class:on={$page.url.pathname.startsWith('/deployments')}>Deployments</a>
|
||||
<a href="/betas" class:on={$page.url.pathname.startsWith('/betas')}>Betas</a>
|
||||
</div>
|
||||
|
||||
@@ -24,6 +24,7 @@ export async function GET({ url }: { url: URL }) {
|
||||
id: bs.script_id,
|
||||
name: script?.name ?? '(deleted)',
|
||||
target_rel_path: script?.target_rel_path ?? '',
|
||||
kind: script?.kind ?? bs.kind ?? 'script',
|
||||
version: version
|
||||
? { id: version.id, version: version.version, sha256: version.sha256 }
|
||||
: null
|
||||
@@ -38,9 +39,13 @@ export async function GET({ url }: { url: URL }) {
|
||||
return json({ betas: rows });
|
||||
}
|
||||
|
||||
// POST body: { scripts: [{ scriptId, scriptVersionId }], servers[], waitForHealth, waitForMatch, notes? }
|
||||
// POST body accepts either:
|
||||
// { artifacts: [{ id, versionId }], ... } — polymorphic (script/config/plugin/baseline)
|
||||
// or the legacy form:
|
||||
// { scripts: [{ scriptId, scriptVersionId }], ... }
|
||||
export async function POST({ request }: { request: Request }) {
|
||||
const body = (await request.json().catch(() => ({}))) as {
|
||||
artifacts?: Array<{ id?: number; versionId?: number }>;
|
||||
scripts?: Array<{ scriptId?: number; scriptVersionId?: number }>;
|
||||
servers?: string[];
|
||||
waitForHealth?: boolean;
|
||||
@@ -48,9 +53,17 @@ export async function POST({ request }: { request: Request }) {
|
||||
notes?: string;
|
||||
};
|
||||
|
||||
if (!Array.isArray(body.scripts) || body.scripts.length === 0 || !Array.isArray(body.servers)) {
|
||||
// Normalize into the openBeta shape. Both fields feed the same list.
|
||||
const rawEntries: Array<{ scriptId?: number; scriptVersionId?: number }> = [];
|
||||
if (Array.isArray(body.artifacts)) {
|
||||
for (const a of body.artifacts) rawEntries.push({ scriptId: a.id, scriptVersionId: a.versionId });
|
||||
}
|
||||
if (Array.isArray(body.scripts)) {
|
||||
for (const s of body.scripts) rawEntries.push({ scriptId: s.scriptId, scriptVersionId: s.scriptVersionId });
|
||||
}
|
||||
if (rawEntries.length === 0 || !Array.isArray(body.servers)) {
|
||||
return json(
|
||||
{ ok: false, error: 'scripts[] (non-empty) and servers[] are required' },
|
||||
{ ok: false, error: 'artifacts[]/scripts[] (non-empty) and servers[] are required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
@@ -58,10 +71,10 @@ export async function POST({ request }: { request: Request }) {
|
||||
return json({ ok: false, error: 'at least one server is required' }, { status: 400 });
|
||||
}
|
||||
const normalized: Array<{ scriptId: number; scriptVersionId: number }> = [];
|
||||
for (const s of body.scripts) {
|
||||
for (const s of rawEntries) {
|
||||
if (typeof s.scriptId !== 'number' || typeof s.scriptVersionId !== 'number') {
|
||||
return json(
|
||||
{ ok: false, error: 'each scripts[] entry needs scriptId and scriptVersionId' },
|
||||
{ ok: false, error: 'each entry needs scriptId/id and scriptVersionId/versionId' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export async function GET({ params }: { params: { id: string } }) {
|
||||
id: bs.script_id,
|
||||
name: script?.name ?? '(deleted)',
|
||||
target_rel_path: script?.target_rel_path ?? '',
|
||||
kind: script?.kind ?? bs.kind ?? 'script',
|
||||
version: version
|
||||
? { id: version.id, version: version.version, sha256: version.sha256 }
|
||||
: null
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Thin wrapper around /api/scripts pinned to config-kind artifacts. Both
|
||||
// overlays (kind='config') and baselines (kind='baseline') share this endpoint
|
||||
// — the caller sets `kind` in the form (defaults to 'config').
|
||||
import { GET as scriptsGET, POST as scriptsPOST } from '../scripts/+server.js';
|
||||
|
||||
function withDefaultKind(url: URL, fallback: string): URL {
|
||||
if (!url.searchParams.has('kind')) {
|
||||
const clone = new URL(url.href);
|
||||
clone.searchParams.set('kind', fallback);
|
||||
return clone;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function GET(event: { url: URL }) {
|
||||
// Default to listing overlays. Baselines live at /api/configs?kind=baseline.
|
||||
return scriptsGET({ url: withDefaultKind(event.url, 'config') });
|
||||
}
|
||||
|
||||
export async function POST(event: { request: Request; url: URL }) {
|
||||
return scriptsPOST({
|
||||
request: event.request,
|
||||
url: withDefaultKind(event.url, 'config')
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Thin wrapper around /api/scripts pinned to plugin-kind artifacts.
|
||||
import { GET as scriptsGET, POST as scriptsPOST } from '../scripts/+server.js';
|
||||
|
||||
function withDefaultKind(url: URL, fallback: string): URL {
|
||||
if (!url.searchParams.has('kind')) {
|
||||
const clone = new URL(url.href);
|
||||
clone.searchParams.set('kind', fallback);
|
||||
return clone;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function GET(event: { url: URL }) {
|
||||
return scriptsGET({ url: withDefaultKind(event.url, 'plugin') });
|
||||
}
|
||||
|
||||
export async function POST(event: { request: Request; url: URL }) {
|
||||
return scriptsPOST({
|
||||
request: event.request,
|
||||
url: withDefaultKind(event.url, 'plugin')
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import {
|
||||
createScript,
|
||||
isArtifactKind,
|
||||
listScripts,
|
||||
listVersions,
|
||||
serversMatchingScope,
|
||||
ScriptError,
|
||||
type ArtifactKind,
|
||||
type ScopeType
|
||||
} from '$lib/server/fleet/scripts.js';
|
||||
import { findRunningBetaForScript } from '$lib/server/fleet/beta.js';
|
||||
@@ -17,8 +19,18 @@ function scopeTypeOrNull(v: FormDataEntryValue | null): ScopeType | null {
|
||||
throw new ScriptError(`invalid scope_type: ${s}`, 'invalid-scope');
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const scripts = listScripts().map((s) => {
|
||||
function kindOrDefault(v: FormDataEntryValue | string | null, fallback: ArtifactKind = 'script'): ArtifactKind {
|
||||
if (v === null || v === undefined || v === '') return fallback;
|
||||
const s = String(v);
|
||||
if (!isArtifactKind(s)) throw new ScriptError(`invalid kind: ${s}`, 'invalid-kind');
|
||||
return s;
|
||||
}
|
||||
|
||||
export async function GET({ url }: { url: URL }) {
|
||||
const kindParam = url.searchParams.get('kind');
|
||||
const kindFilter = kindParam ? (isArtifactKind(kindParam) ? kindParam : null) : null;
|
||||
const rows = kindFilter ? listScripts(kindFilter) : listScripts();
|
||||
const scripts = rows.map((s) => {
|
||||
const versions = listVersions(s.id);
|
||||
const matched = s.scope_type && s.scope_value
|
||||
? serversMatchingScope(s.scope_type as ScopeType, s.scope_value)
|
||||
@@ -44,28 +56,45 @@ export async function GET() {
|
||||
return json({ scripts });
|
||||
}
|
||||
|
||||
// Multipart POST — creates a script + version 1 from a single file upload.
|
||||
// Fields: name (text), scopeType (optional: 'game'|'map'), scopeValue
|
||||
// (optional string), notes (optional), content (file). The target rel path
|
||||
// defaults to the uploaded filename — T5 servers keep all scripts in a flat
|
||||
// sp/ directory, so there's no sub-path to specify.
|
||||
export async function POST({ request }: { request: Request }) {
|
||||
// Multipart POST — creates an artifact + version 1 from either an uploaded
|
||||
// file (script/plugin/baseline) or a text body (config overlay). Fields:
|
||||
// name, scopeType, scopeValue, notes, kind (defaults to 'script'),
|
||||
// content (file). Configs may alternatively send `text` as a form field.
|
||||
export async function POST({ request, url }: { request: Request; url: URL }) {
|
||||
const form = await request.formData();
|
||||
const name = String(form.get('name') ?? '').trim();
|
||||
const notes = form.get('notes') ? String(form.get('notes')) : undefined;
|
||||
let scopeType: ScopeType | null;
|
||||
let kind: ArtifactKind;
|
||||
try {
|
||||
scopeType = scopeTypeOrNull(form.get('scopeType'));
|
||||
// Kind may come from the form or the query string (thin wrappers use ?kind=).
|
||||
const kindRaw = form.get('kind') ?? url.searchParams.get('kind');
|
||||
kind = kindOrDefault(kindRaw);
|
||||
} catch (err) {
|
||||
return json({ ok: false, error: (err as Error).message }, { status: 400 });
|
||||
}
|
||||
const scopeValueRaw = form.get('scopeValue');
|
||||
const scopeValue = scopeValueRaw ? String(scopeValueRaw).trim() : null;
|
||||
const file = form.get('content');
|
||||
if (!(file instanceof File)) return json({ ok: false, error: 'content file is required' }, { status: 400 });
|
||||
|
||||
const targetRelPath = file.name;
|
||||
const content = Buffer.from(await file.arrayBuffer());
|
||||
let content: Buffer;
|
||||
let uploadedFilename: string | null = null;
|
||||
const file = form.get('content');
|
||||
const text = form.get('text');
|
||||
if (file instanceof File && file.size > 0) {
|
||||
content = Buffer.from(await file.arrayBuffer());
|
||||
uploadedFilename = file.name;
|
||||
} else if (typeof text === 'string' && text.length > 0) {
|
||||
content = Buffer.from(text, 'utf8');
|
||||
} else {
|
||||
return json({ ok: false, error: 'content file or text is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Target rel path: for script/plugin, default to the upload filename.
|
||||
// For config/baseline, createScript() defaults to config.configTargetFile.
|
||||
const targetRelPath = kind === 'script' || kind === 'plugin'
|
||||
? uploadedFilename ?? undefined
|
||||
: undefined;
|
||||
|
||||
try {
|
||||
const { script, version } = createScript({
|
||||
@@ -74,7 +103,8 @@ export async function POST({ request }: { request: Request }) {
|
||||
scopeType,
|
||||
scopeValue,
|
||||
content,
|
||||
notes
|
||||
notes,
|
||||
kind
|
||||
});
|
||||
return json({ ok: true, script, versionId: version.id });
|
||||
} catch (err) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
type ArtifactKind = 'script' | 'config' | 'plugin' | 'baseline';
|
||||
interface BetaListRow {
|
||||
id: number;
|
||||
state: 'running' | 'ready-promote' | 'promoted' | 'rolled-back';
|
||||
@@ -13,6 +14,7 @@
|
||||
id: number;
|
||||
name: string;
|
||||
target_rel_path: string;
|
||||
kind: ArtifactKind;
|
||||
version: { id: number; version: number; sha256: string } | null;
|
||||
}>;
|
||||
servers: Array<{ server: string; stage: string; error: string | null }>;
|
||||
@@ -25,6 +27,7 @@
|
||||
scope_type: 'game' | 'map' | null;
|
||||
scope_value: string | null;
|
||||
current_version_id: number | null;
|
||||
kind: ArtifactKind;
|
||||
latestVersion: {
|
||||
id: number;
|
||||
version: number;
|
||||
@@ -229,12 +232,14 @@
|
||||
);
|
||||
|
||||
function summarizeScripts(b: BetaListRow): string {
|
||||
if (b.scripts.length === 0) return '(no scripts)';
|
||||
if (b.scripts.length === 0) return '(no artifacts)';
|
||||
if (b.scripts.length === 1) {
|
||||
const s = b.scripts[0];
|
||||
return `${s.name} · v${s.version?.version ?? '?'}`;
|
||||
return `[${s.kind}] ${s.name} · v${s.version?.version ?? '?'}`;
|
||||
}
|
||||
return `${b.scripts.length} scripts`;
|
||||
const byKind: Record<string, number> = {};
|
||||
for (const s of b.scripts) byKind[s.kind] = (byKind[s.kind] ?? 0) + 1;
|
||||
return Object.entries(byKind).map(([k, n]) => `${n} ${k}${n === 1 ? '' : 's'}`).join(', ');
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -246,7 +251,7 @@
|
||||
<section class="panel">
|
||||
<h2>Open a beta</h2>
|
||||
{#if eligibleScripts.length === 0}
|
||||
<p class="empty">no scripts with untested versions — upload a new version from a script's page</p>
|
||||
<p class="empty">no artifacts with untested versions — upload a new version from a scripts / configs / plugins page</p>
|
||||
{:else}
|
||||
<form onsubmit={openNewBeta} class="new-beta-form">
|
||||
<div class="picks">
|
||||
@@ -256,9 +261,9 @@
|
||||
bind:value={row.scriptId}
|
||||
onchange={() => onPickScript(idx)}
|
||||
>
|
||||
<option value={null}>— pick a script —</option>
|
||||
<option value={null}>— pick an artifact —</option>
|
||||
{#each eligibleForRow(idx) as s (s.id)}
|
||||
<option value={s.id}>{s.name}</option>
|
||||
<option value={s.id}>[{s.kind}] {s.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<select bind:value={row.versionId} disabled={row.scriptId === null}>
|
||||
@@ -280,7 +285,7 @@
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<button type="button" class="add-row" onclick={addRow}>+ add script</button>
|
||||
<button type="button" class="add-row" onclick={addRow}>+ add artifact</button>
|
||||
|
||||
<label>
|
||||
<span class="k">test servers</span>
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
id: number;
|
||||
name: string;
|
||||
target_rel_path: string;
|
||||
kind: 'script' | 'config' | 'plugin' | 'baseline';
|
||||
version: { id: number; version: number; sha256: string } | null;
|
||||
}
|
||||
|
||||
@@ -118,13 +119,14 @@
|
||||
</div>
|
||||
|
||||
<section class="panel">
|
||||
<h2>Scripts · {scripts.length}</h2>
|
||||
<h2>Artifacts · {scripts.length}</h2>
|
||||
{#if scripts.length === 0}
|
||||
<p class="empty">no scripts bundled in this beta</p>
|
||||
<p class="empty">no artifacts bundled in this beta</p>
|
||||
{:else}
|
||||
<div class="script-list">
|
||||
{#each scripts as s (s.id)}
|
||||
<div class="script-row">
|
||||
<span class="s-kind mono">[{s.kind}]</span>
|
||||
<a class="s-name" href="/scripts/{s.id}">{s.name}</a>
|
||||
<span class="s-target mono">{s.target_rel_path}</span>
|
||||
<span class="s-ver mono">v{s.version?.version ?? '?'}</span>
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
type ArtifactKind = 'script' | 'config' | 'plugin' | 'baseline';
|
||||
|
||||
interface ArtifactRow {
|
||||
id: number;
|
||||
name: string;
|
||||
target_rel_path: string;
|
||||
scope_type: 'game' | 'map' | null;
|
||||
scope_value: string | null;
|
||||
current_version_id: number | null;
|
||||
kind: ArtifactKind;
|
||||
latestVersion: {
|
||||
id: number;
|
||||
version: number;
|
||||
sha256: string;
|
||||
size: number;
|
||||
state: 'untested' | 'tested' | 'test-failed';
|
||||
uploaded_at: string;
|
||||
} | null;
|
||||
versionCount: number;
|
||||
servers: string[];
|
||||
runningBetaId: number | null;
|
||||
}
|
||||
|
||||
interface ScopeOptions {
|
||||
games: string[];
|
||||
mapsByGame: Record<string, string[]>;
|
||||
}
|
||||
|
||||
// Two lists: baselines (kind='baseline') and overlays (kind='config').
|
||||
let baselines = $state<ArtifactRow[]>([]);
|
||||
let overlays = $state<ArtifactRow[]>([]);
|
||||
let loading = $state(true);
|
||||
let flash = $state<string | null>(null);
|
||||
let uploading = $state(false);
|
||||
let scopeOptions = $state<ScopeOptions>({ games: [], mapsByGame: {} });
|
||||
let successBanner = $state<{ name: string; artifactId: number; version: number; kind: string } | null>(null);
|
||||
|
||||
// Overlay form state
|
||||
let overlayName = $state('');
|
||||
let overlayScopeType = $state<'game' | 'map'>('game');
|
||||
let overlayScopeGame = $state('');
|
||||
let overlayScopeMap = $state('');
|
||||
let overlayText = $state('');
|
||||
let overlayNotes = $state('');
|
||||
|
||||
// Baseline form state
|
||||
let baselineName = $state('');
|
||||
let baselineScopeGame = $state('');
|
||||
let baselineFile = $state<File | null>(null);
|
||||
let baselineNotes = $state('');
|
||||
|
||||
const overlayScopeValue = $derived.by(() => {
|
||||
if (overlayScopeType === 'game') return overlayScopeGame;
|
||||
return overlayScopeMap;
|
||||
});
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const [baselineRes, overlayRes, scopeRes] = await Promise.all([
|
||||
fetch('/api/configs?kind=baseline'),
|
||||
fetch('/api/configs?kind=config'),
|
||||
fetch('/api/scope-options')
|
||||
]);
|
||||
baselines = (await baselineRes.json()).scripts;
|
||||
overlays = (await overlayRes.json()).scripts;
|
||||
scopeOptions = (await scopeRes.json()) as ScopeOptions;
|
||||
loading = false;
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
|
||||
async function createOverlay(e: Event): Promise<void> {
|
||||
e.preventDefault();
|
||||
if (uploading) return;
|
||||
if (!overlayName.trim()) { flash = 'name is required'; return; }
|
||||
if (!overlayScopeValue) { flash = `pick a ${overlayScopeType}`; return; }
|
||||
if (!/^\s*set\s+\S+\s+/m.test(overlayText)) {
|
||||
flash = 'overlay must contain at least one `set KEY VALUE` line';
|
||||
return;
|
||||
}
|
||||
uploading = true;
|
||||
flash = null;
|
||||
const form = new FormData();
|
||||
form.append('name', overlayName.trim());
|
||||
form.append('kind', 'config');
|
||||
form.append('scopeType', overlayScopeType);
|
||||
form.append('scopeValue', overlayScopeValue);
|
||||
form.append('text', overlayText);
|
||||
if (overlayNotes.trim()) form.append('notes', overlayNotes.trim());
|
||||
try {
|
||||
const res = await fetch('/api/configs', { method: 'POST', body: form });
|
||||
const body = (await res.json()) as { ok: boolean; error?: string; script?: { id: number; name: string } };
|
||||
if (!res.ok || !body.ok) { flash = body.error ?? `HTTP ${res.status}`; return; }
|
||||
successBanner = body.script
|
||||
? { name: body.script.name, artifactId: body.script.id, version: 1, kind: 'config overlay' }
|
||||
: null;
|
||||
overlayName = ''; overlayText = ''; overlayNotes = '';
|
||||
await load();
|
||||
} finally {
|
||||
uploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function pickBaselineFile(e: Event): void {
|
||||
const t = e.target as HTMLInputElement;
|
||||
baselineFile = t.files?.[0] ?? null;
|
||||
if (!baselineName && baselineFile) baselineName = baselineFile.name.replace(/\.[^.]+$/, '');
|
||||
}
|
||||
|
||||
async function createBaseline(e: Event): Promise<void> {
|
||||
e.preventDefault();
|
||||
if (uploading) return;
|
||||
if (!baselineName.trim() || !baselineFile || !baselineScopeGame) {
|
||||
flash = 'name, game, and cfg file are required';
|
||||
return;
|
||||
}
|
||||
uploading = true;
|
||||
flash = null;
|
||||
const form = new FormData();
|
||||
form.append('name', baselineName.trim());
|
||||
form.append('kind', 'baseline');
|
||||
form.append('scopeType', 'game');
|
||||
form.append('scopeValue', baselineScopeGame);
|
||||
form.append('content', baselineFile);
|
||||
if (baselineNotes.trim()) form.append('notes', baselineNotes.trim());
|
||||
try {
|
||||
const res = await fetch('/api/configs', { method: 'POST', body: form });
|
||||
const body = (await res.json()) as { ok: boolean; error?: string; script?: { id: number; name: string } };
|
||||
if (!res.ok || !body.ok) { flash = body.error ?? `HTTP ${res.status}`; return; }
|
||||
successBanner = body.script
|
||||
? { name: body.script.name, artifactId: body.script.id, version: 1, kind: 'baseline' }
|
||||
: null;
|
||||
baselineName = ''; baselineScopeGame = ''; baselineFile = null; baselineNotes = '';
|
||||
await load();
|
||||
} finally {
|
||||
uploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function scopeLabel(a: ArtifactRow): string {
|
||||
if (!a.scope_type) return 'unscoped';
|
||||
return `${a.scope_type}=${a.scope_value ?? '?'}`;
|
||||
}
|
||||
|
||||
function stateTag(a: ArtifactRow): { label: string; cls: string } | null {
|
||||
if (!a.latestVersion) return null;
|
||||
if (a.current_version_id === null) return { label: 'untested', cls: 'state-untested' };
|
||||
if (a.latestVersion.id !== a.current_version_id) {
|
||||
return { label: `v${a.latestVersion.version} ${a.latestVersion.state}`, cls: `state-${a.latestVersion.state}` };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1>Configs</h1>
|
||||
|
||||
<section class="panel">
|
||||
<h2>Upload a baseline (one per game)</h2>
|
||||
{#if successBanner}
|
||||
<div class="banner banner-info">
|
||||
<strong>v{successBanner.version} of "{successBanner.name}" ({successBanner.kind}) uploaded — untested.</strong>
|
||||
<span>Open a beta on <a href="/betas">the betas page</a> to test it before it can be promoted.</span>
|
||||
</div>
|
||||
{/if}
|
||||
<form onsubmit={createBaseline} class="upload-form">
|
||||
<label>
|
||||
<span class="k">name</span>
|
||||
<input type="text" bind:value={baselineName} placeholder="t5 baseline" disabled={uploading} />
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">game</span>
|
||||
<select bind:value={baselineScopeGame} disabled={uploading}>
|
||||
<option value="">— pick a game —</option>
|
||||
{#each scopeOptions.games as g (g)}
|
||||
<option value={g}>{g}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">notes (optional)</span>
|
||||
<input type="text" bind:value={baselineNotes} placeholder="dedicated_sp.cfg baseline" disabled={uploading} />
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">cfg file (dedicated_sp.cfg)</span>
|
||||
<input type="file" accept=".cfg,text/plain" onchange={pickBaselineFile} disabled={uploading} />
|
||||
</label>
|
||||
<button type="submit" class="primary" disabled={uploading || !baselineFile || !baselineName || !baselineScopeGame}>
|
||||
{uploading ? 'uploading…' : 'upload baseline'}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>Create a config overlay</h2>
|
||||
<form onsubmit={createOverlay} class="upload-form">
|
||||
<label>
|
||||
<span class="k">name</span>
|
||||
<input type="text" bind:value={overlayName} placeholder="disable AFK" disabled={uploading} />
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">scope</span>
|
||||
<div class="scope-row">
|
||||
<select bind:value={overlayScopeType} disabled={uploading}>
|
||||
<option value="game">game</option>
|
||||
<option value="map">map</option>
|
||||
</select>
|
||||
{#if overlayScopeType === 'game'}
|
||||
<select bind:value={overlayScopeGame} disabled={uploading}>
|
||||
<option value="">— pick a game —</option>
|
||||
{#each scopeOptions.games as g (g)}
|
||||
<option value={g}>{g}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else}
|
||||
<select bind:value={overlayScopeGame} disabled={uploading}>
|
||||
<option value="">— pick a game —</option>
|
||||
{#each scopeOptions.games as g (g)}
|
||||
<option value={g}>{g}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<select bind:value={overlayScopeMap} disabled={uploading || !overlayScopeGame}>
|
||||
<option value="">— pick a map —</option>
|
||||
{#each (scopeOptions.mapsByGame[overlayScopeGame] ?? []) as m (m)}
|
||||
<option value={m}>{m}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{/if}
|
||||
</div>
|
||||
</label>
|
||||
<label class="full">
|
||||
<span class="k">overlay lines</span>
|
||||
<textarea
|
||||
bind:value={overlayText}
|
||||
rows="4"
|
||||
placeholder={'set g_inactivity "0"'}
|
||||
disabled={uploading}
|
||||
></textarea>
|
||||
<span class="hint">one or more `set KEY "VALUE"` lines. Replaces baseline lines with the same KEY.</span>
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">notes (optional)</span>
|
||||
<input type="text" bind:value={overlayNotes} placeholder="why this change" disabled={uploading} />
|
||||
</label>
|
||||
<button type="submit" class="primary" disabled={uploading || !overlayName || !overlayText || !overlayScopeValue}>
|
||||
{uploading ? 'uploading…' : 'create overlay'}
|
||||
</button>
|
||||
</form>
|
||||
{#if flash}<p class="flash">{flash}</p>{/if}
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>Baselines · {baselines.length}</h2>
|
||||
{#if loading}
|
||||
<p class="empty">loading…</p>
|
||||
{:else if baselines.length === 0}
|
||||
<p class="empty">no baseline yet — upload one above</p>
|
||||
{:else}
|
||||
<div class="artifacts">
|
||||
{#each baselines as a (a.id)}
|
||||
<a class="artifact-row" href="/scripts/{a.id}">
|
||||
<div class="row-top">
|
||||
<span class="artifact-name">{a.name}</span>
|
||||
<span class="scope tag scope-{a.scope_type ?? 'none'}">{scopeLabel(a)}</span>
|
||||
{#if stateTag(a)}
|
||||
{@const t = stateTag(a)!}
|
||||
<span class="tag {t.cls}">{t.label}</span>
|
||||
{/if}
|
||||
{#if a.runningBetaId}
|
||||
<span class="tag beta">beta {a.runningBetaId} running</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="row-meta mono">
|
||||
<span>{a.target_rel_path}</span>
|
||||
<span>v{a.latestVersion?.version ?? '—'} · {a.versionCount} version{a.versionCount === 1 ? '' : 's'}</span>
|
||||
<span>{a.servers.length ? `${a.servers.length} matching server${a.servers.length === 1 ? '' : 's'}` : ''}</span>
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>Overlays · {overlays.length}</h2>
|
||||
{#if loading}
|
||||
<p class="empty">loading…</p>
|
||||
{:else if overlays.length === 0}
|
||||
<p class="empty">no overlays yet — create one above</p>
|
||||
{:else}
|
||||
<div class="artifacts">
|
||||
{#each overlays as a (a.id)}
|
||||
<a class="artifact-row" href="/scripts/{a.id}">
|
||||
<div class="row-top">
|
||||
<span class="artifact-name">{a.name}</span>
|
||||
<span class="scope tag scope-{a.scope_type ?? 'none'}">{scopeLabel(a)}</span>
|
||||
{#if stateTag(a)}
|
||||
{@const t = stateTag(a)!}
|
||||
<span class="tag {t.cls}">{t.label}</span>
|
||||
{/if}
|
||||
{#if a.runningBetaId}
|
||||
<span class="tag beta">beta {a.runningBetaId} running</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="row-meta mono">
|
||||
<span>v{a.latestVersion?.version ?? '—'} · {a.versionCount} version{a.versionCount === 1 ? '' : 's'}</span>
|
||||
<span>{a.servers.length ? `${a.servers.length} matching server${a.servers.length === 1 ? '' : 's'}` : ''}</span>
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
h1 { color: var(--cream); font-family: var(--font-display); font-size: var(--text-3xl); letter-spacing: var(--tracking-display); line-height: var(--leading-tight); margin: 0 0 28px; }
|
||||
.panel { background: var(--bg-nav); border: 1px solid var(--border); border-radius: var(--r-md); padding: var(--pad-panel); margin-bottom: 20px; }
|
||||
h2 { margin: 0 0 14px; font-family: var(--font-body); font-size: var(--text-xs); font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; color: var(--ink-300); }
|
||||
.empty { color: var(--ink-500); font-family: var(--font-mono); font-size: var(--text-mono); margin: 0; }
|
||||
.upload-form { display: grid; gap: 12px; grid-template-columns: 1fr 1fr; }
|
||||
.upload-form label { display: flex; flex-direction: column; gap: 6px; font-size: var(--text-xs); }
|
||||
.upload-form label.full { grid-column: 1 / -1; }
|
||||
.upload-form label .k { color: var(--ink-500); text-transform: uppercase; letter-spacing: 1px; }
|
||||
.upload-form .hint { color: var(--ink-500); font-family: var(--font-mono); font-size: var(--text-mono-sm); }
|
||||
.upload-form input[type=text], .upload-form select, .upload-form input[type=file], .upload-form textarea {
|
||||
background: var(--bg-page);
|
||||
color: var(--ink-100);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--r-sm);
|
||||
padding: 10px 12px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-mono);
|
||||
}
|
||||
.upload-form textarea { min-height: 100px; resize: vertical; }
|
||||
.upload-form input[type=text]:focus, .upload-form select:focus, .upload-form textarea:focus {
|
||||
outline: none; border-color: var(--accent); box-shadow: var(--accent-glow);
|
||||
}
|
||||
.scope-row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.scope-row select:nth-of-type(1) { flex: 0 0 120px; }
|
||||
.scope-row select:nth-of-type(2), .scope-row select:nth-of-type(3) { flex: 1; }
|
||||
.primary {
|
||||
grid-column: 1 / -1;
|
||||
background: linear-gradient(180deg, var(--blue-500), var(--blue-600));
|
||||
border: 1px solid var(--blue-400);
|
||||
border-radius: var(--r-sm);
|
||||
padding: 12px 18px;
|
||||
color: var(--cream);
|
||||
font-family: var(--font-body);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.primary:disabled { opacity: 0.4; cursor: default; }
|
||||
.flash { color: var(--danger-500); font-family: var(--font-mono); font-size: var(--text-mono); margin-top: 12px; }
|
||||
.artifacts { display: flex; flex-direction: column; gap: 8px; }
|
||||
.artifact-row { display: flex; flex-direction: column; gap: 6px; background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 14px 16px; text-decoration: none; color: var(--ink-100); }
|
||||
.artifact-row:hover { border-color: var(--accent); box-shadow: var(--accent-glow); }
|
||||
.row-top { display: flex; gap: 12px; align-items: center; }
|
||||
.artifact-name { color: var(--cream); font-weight: 600; font-size: var(--text-md); }
|
||||
.row-meta { display: flex; gap: 24px; color: var(--ink-500); font-size: var(--text-mono-sm); }
|
||||
.mono { font-family: var(--font-mono); }
|
||||
.tag { font-family: var(--font-mono); font-size: var(--text-xs); padding: 3px 9px; border-radius: var(--r-sm); border: 1px solid transparent; }
|
||||
.scope-none { background: var(--bg-nav); border-color: var(--border); color: var(--ink-500); }
|
||||
.scope-game { background: rgba(124, 212, 255, 0.10); border-color: rgba(124, 212, 255, 0.3); color: var(--spark-500); }
|
||||
.scope-map { background: rgba(255, 176, 32, 0.10); border-color: rgba(255, 176, 32, 0.35); color: var(--amber-500); }
|
||||
.beta { background: rgba(255, 176, 32, 0.10); border-color: rgba(255, 176, 32, 0.3); color: var(--amber-500); }
|
||||
.state-untested { background: var(--bg-nav); border-color: var(--border); color: var(--ink-300); }
|
||||
.state-tested { background: rgba(124, 212, 255, 0.10); border-color: rgba(124, 212, 255, 0.3); color: var(--spark-500); }
|
||||
.state-test-failed { background: rgba(255, 92, 92, 0.10); border-color: rgba(255, 92, 92, 0.4); color: var(--danger-500); }
|
||||
.banner { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 4px; border-radius: var(--r-sm); padding: 12px 14px; margin-bottom: 12px; font-size: var(--text-mono); }
|
||||
.banner-info { background: rgba(124, 212, 255, 0.08); border: 1px solid rgba(124, 212, 255, 0.28); color: var(--ink-100); }
|
||||
.banner-info a { color: var(--spark-500); text-decoration: underline; }
|
||||
</style>
|
||||
@@ -0,0 +1,248 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
type ArtifactKind = 'script' | 'config' | 'plugin' | 'baseline';
|
||||
|
||||
interface ArtifactRow {
|
||||
id: number;
|
||||
name: string;
|
||||
target_rel_path: string;
|
||||
scope_type: 'game' | 'map' | null;
|
||||
scope_value: string | null;
|
||||
current_version_id: number | null;
|
||||
kind: ArtifactKind;
|
||||
latestVersion: {
|
||||
id: number;
|
||||
version: number;
|
||||
sha256: string;
|
||||
size: number;
|
||||
state: 'untested' | 'tested' | 'test-failed';
|
||||
uploaded_at: string;
|
||||
} | null;
|
||||
versionCount: number;
|
||||
servers: string[];
|
||||
runningBetaId: number | null;
|
||||
}
|
||||
|
||||
interface ScopeOptions {
|
||||
games: string[];
|
||||
mapsByGame: Record<string, string[]>;
|
||||
}
|
||||
|
||||
let plugins = $state<ArtifactRow[]>([]);
|
||||
let loading = $state(true);
|
||||
let flash = $state<string | null>(null);
|
||||
let uploading = $state(false);
|
||||
let scopeOptions = $state<ScopeOptions>({ games: [], mapsByGame: {} });
|
||||
let successBanner = $state<{ name: string; artifactId: number; version: number } | null>(null);
|
||||
|
||||
let newName = $state('');
|
||||
let newScopeType = $state<'none' | 'game' | 'map'>('none');
|
||||
let newScopeGame = $state('');
|
||||
let newScopeMap = $state('');
|
||||
let newFile = $state<File | null>(null);
|
||||
let newNotes = $state('');
|
||||
|
||||
const scopeValue = $derived.by(() => {
|
||||
if (newScopeType === 'game') return newScopeGame;
|
||||
if (newScopeType === 'map') return newScopeMap;
|
||||
return '';
|
||||
});
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const [pluginRes, scopeRes] = await Promise.all([
|
||||
fetch('/api/plugins'),
|
||||
fetch('/api/scope-options')
|
||||
]);
|
||||
plugins = (await pluginRes.json()).scripts;
|
||||
scopeOptions = (await scopeRes.json()) as ScopeOptions;
|
||||
loading = false;
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
|
||||
function pickFile(e: Event): void {
|
||||
const t = e.target as HTMLInputElement;
|
||||
newFile = t.files?.[0] ?? null;
|
||||
if (!newName && newFile) newName = newFile.name.replace(/\.[^.]+$/, '');
|
||||
}
|
||||
|
||||
async function createPlugin(e: Event): Promise<void> {
|
||||
e.preventDefault();
|
||||
if (uploading || !newFile || !newName.trim()) return;
|
||||
if (newScopeType !== 'none' && !scopeValue) { flash = `pick a ${newScopeType}`; return; }
|
||||
uploading = true;
|
||||
flash = null;
|
||||
const form = new FormData();
|
||||
form.append('name', newName.trim());
|
||||
form.append('kind', 'plugin');
|
||||
form.append('scopeType', newScopeType);
|
||||
if (scopeValue) form.append('scopeValue', scopeValue);
|
||||
if (newNotes.trim()) form.append('notes', newNotes.trim());
|
||||
form.append('content', newFile);
|
||||
try {
|
||||
const res = await fetch('/api/plugins', { method: 'POST', body: form });
|
||||
const body = (await res.json()) as { ok: boolean; error?: string; script?: { id: number; name: string } };
|
||||
if (!res.ok || !body.ok) { flash = body.error ?? `HTTP ${res.status}`; return; }
|
||||
successBanner = body.script
|
||||
? { name: body.script.name, artifactId: body.script.id, version: 1 }
|
||||
: null;
|
||||
newName = ''; newScopeType = 'none'; newScopeGame = ''; newScopeMap = ''; newNotes = ''; newFile = null;
|
||||
await load();
|
||||
} finally {
|
||||
uploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function scopeLabel(a: ArtifactRow): string {
|
||||
if (!a.scope_type) return 'unscoped';
|
||||
return `${a.scope_type}=${a.scope_value ?? '?'}`;
|
||||
}
|
||||
|
||||
function stateTag(a: ArtifactRow): { label: string; cls: string } | null {
|
||||
if (!a.latestVersion) return null;
|
||||
if (a.current_version_id === null) return { label: 'untested', cls: 'state-untested' };
|
||||
if (a.latestVersion.id !== a.current_version_id) {
|
||||
return { label: `v${a.latestVersion.version} ${a.latestVersion.state}`, cls: `state-${a.latestVersion.state}` };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1>Plugins</h1>
|
||||
|
||||
<section class="panel">
|
||||
<h2>Upload a plugin</h2>
|
||||
{#if successBanner}
|
||||
<div class="banner banner-info">
|
||||
<strong>v{successBanner.version} of "{successBanner.name}" uploaded — untested.</strong>
|
||||
<span>Open a beta on <a href="/betas">the betas page</a> to test it before it can be promoted.</span>
|
||||
</div>
|
||||
{/if}
|
||||
<form onsubmit={createPlugin} class="upload-form">
|
||||
<label>
|
||||
<span class="k">name</span>
|
||||
<input type="text" bind:value={newName} placeholder="my plugin" disabled={uploading} />
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">scope</span>
|
||||
<div class="scope-row">
|
||||
<select bind:value={newScopeType} disabled={uploading}>
|
||||
<option value="none">unscoped</option>
|
||||
<option value="game">game</option>
|
||||
<option value="map">map</option>
|
||||
</select>
|
||||
{#if newScopeType === 'game'}
|
||||
<select bind:value={newScopeGame} disabled={uploading}>
|
||||
<option value="">— pick a game —</option>
|
||||
{#each scopeOptions.games as g (g)}
|
||||
<option value={g}>{g}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else if newScopeType === 'map'}
|
||||
<select bind:value={newScopeGame} disabled={uploading}>
|
||||
<option value="">— pick a game —</option>
|
||||
{#each scopeOptions.games as g (g)}
|
||||
<option value={g}>{g}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<select bind:value={newScopeMap} disabled={uploading || !newScopeGame}>
|
||||
<option value="">— pick a map —</option>
|
||||
{#each (scopeOptions.mapsByGame[newScopeGame] ?? []) as m (m)}
|
||||
<option value={m}>{m}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{/if}
|
||||
</div>
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">notes (optional)</span>
|
||||
<input type="text" bind:value={newNotes} placeholder="what changed" disabled={uploading} />
|
||||
</label>
|
||||
<label>
|
||||
<span class="k">plugin file (.dll)</span>
|
||||
<input type="file" accept=".dll" onchange={pickFile} disabled={uploading} />
|
||||
</label>
|
||||
<button type="submit" class="primary" disabled={uploading || !newFile || !newName}>
|
||||
{uploading ? 'uploading…' : 'upload plugin'}
|
||||
</button>
|
||||
</form>
|
||||
{#if flash}<p class="flash">{flash}</p>{/if}
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<h2>All plugins</h2>
|
||||
{#if loading}
|
||||
<p class="empty">loading…</p>
|
||||
{:else if plugins.length === 0}
|
||||
<p class="empty">no plugins yet — upload one above</p>
|
||||
{:else}
|
||||
<div class="artifacts">
|
||||
{#each plugins as a (a.id)}
|
||||
<a class="artifact-row" href="/scripts/{a.id}">
|
||||
<div class="row-top">
|
||||
<span class="artifact-name">{a.name}</span>
|
||||
<span class="scope tag scope-{a.scope_type ?? 'none'}">{scopeLabel(a)}</span>
|
||||
{#if stateTag(a)}
|
||||
{@const t = stateTag(a)!}
|
||||
<span class="tag {t.cls}">{t.label}</span>
|
||||
{/if}
|
||||
{#if a.runningBetaId}
|
||||
<span class="tag beta">beta {a.runningBetaId} running</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="row-meta mono">
|
||||
<span>{a.target_rel_path}</span>
|
||||
<span>v{a.latestVersion?.version ?? '—'} · {a.versionCount} version{a.versionCount === 1 ? '' : 's'}</span>
|
||||
<span>{a.servers.length ? `${a.servers.length} matching server${a.servers.length === 1 ? '' : 's'}` : ''}</span>
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
h1 { color: var(--cream); font-family: var(--font-display); font-size: var(--text-3xl); letter-spacing: var(--tracking-display); line-height: var(--leading-tight); margin: 0 0 28px; }
|
||||
.panel { background: var(--bg-nav); border: 1px solid var(--border); border-radius: var(--r-md); padding: var(--pad-panel); margin-bottom: 20px; }
|
||||
h2 { margin: 0 0 14px; font-family: var(--font-body); font-size: var(--text-xs); font-weight: 700; text-transform: uppercase; letter-spacing: 1.5px; color: var(--ink-300); }
|
||||
.empty { color: var(--ink-500); font-family: var(--font-mono); font-size: var(--text-mono); margin: 0; }
|
||||
.upload-form { display: grid; gap: 12px; grid-template-columns: 1fr 1fr; }
|
||||
.upload-form label { display: flex; flex-direction: column; gap: 6px; font-size: var(--text-xs); }
|
||||
.upload-form label .k { color: var(--ink-500); text-transform: uppercase; letter-spacing: 1px; }
|
||||
.upload-form input[type=text], .upload-form select, .upload-form input[type=file] {
|
||||
background: var(--bg-page); color: var(--ink-100); border: 1px solid var(--border);
|
||||
border-radius: var(--r-sm); padding: 10px 12px; font-family: var(--font-mono); font-size: var(--text-mono);
|
||||
}
|
||||
.upload-form input[type=text]:focus, .upload-form select:focus {
|
||||
outline: none; border-color: var(--accent); box-shadow: var(--accent-glow);
|
||||
}
|
||||
.scope-row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.scope-row select:nth-of-type(1) { flex: 0 0 120px; }
|
||||
.scope-row select:nth-of-type(2), .scope-row select:nth-of-type(3) { flex: 1; }
|
||||
.primary {
|
||||
grid-column: 1 / -1; background: linear-gradient(180deg, var(--blue-500), var(--blue-600));
|
||||
border: 1px solid var(--blue-400); border-radius: var(--r-sm); padding: 12px 18px;
|
||||
color: var(--cream); font-family: var(--font-body); font-weight: 600; cursor: pointer;
|
||||
}
|
||||
.primary:disabled { opacity: 0.4; cursor: default; }
|
||||
.flash { color: var(--danger-500); font-family: var(--font-mono); font-size: var(--text-mono); margin-top: 12px; }
|
||||
.artifacts { display: flex; flex-direction: column; gap: 8px; }
|
||||
.artifact-row { display: flex; flex-direction: column; gap: 6px; background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 14px 16px; text-decoration: none; color: var(--ink-100); }
|
||||
.artifact-row:hover { border-color: var(--accent); box-shadow: var(--accent-glow); }
|
||||
.row-top { display: flex; gap: 12px; align-items: center; }
|
||||
.artifact-name { color: var(--cream); font-weight: 600; font-size: var(--text-md); }
|
||||
.row-meta { display: flex; gap: 24px; color: var(--ink-500); font-size: var(--text-mono-sm); }
|
||||
.mono { font-family: var(--font-mono); }
|
||||
.tag { font-family: var(--font-mono); font-size: var(--text-xs); padding: 3px 9px; border-radius: var(--r-sm); border: 1px solid transparent; }
|
||||
.scope-none { background: var(--bg-nav); border-color: var(--border); color: var(--ink-500); }
|
||||
.scope-game { background: rgba(124, 212, 255, 0.10); border-color: rgba(124, 212, 255, 0.3); color: var(--spark-500); }
|
||||
.scope-map { background: rgba(255, 176, 32, 0.10); border-color: rgba(255, 176, 32, 0.35); color: var(--amber-500); }
|
||||
.beta { background: rgba(255, 176, 32, 0.10); border-color: rgba(255, 176, 32, 0.3); color: var(--amber-500); }
|
||||
.state-untested { background: var(--bg-nav); border-color: var(--border); color: var(--ink-300); }
|
||||
.state-tested { background: rgba(124, 212, 255, 0.10); border-color: rgba(124, 212, 255, 0.3); color: var(--spark-500); }
|
||||
.state-test-failed { background: rgba(255, 92, 92, 0.10); border-color: rgba(255, 92, 92, 0.4); color: var(--danger-500); }
|
||||
.banner { grid-column: 1 / -1; display: flex; flex-direction: column; gap: 4px; border-radius: var(--r-sm); padding: 12px 14px; margin-bottom: 12px; font-size: var(--text-mono); }
|
||||
.banner-info { background: rgba(124, 212, 255, 0.08); border: 1px solid rgba(124, 212, 255, 0.28); color: var(--ink-100); }
|
||||
.banner-info a { color: var(--spark-500); text-decoration: underline; }
|
||||
</style>
|
||||
Reference in New Issue
Block a user