1
0
Fork 0
polaris-task-force/src/lib/arma-import/catalog.ts

667 lines
26 KiB
TypeScript

/**
* Arma catalog import: planning + upsert logic for the in-game export catalog.
*
* Record contract (the in-game ptf_export addon emits a JSON array of these):
*
* { classname: string, type: AssetType | "vehicle", displayName: string,
* picture: string (.paa ref, may be ""), mod: string, description: string,
* mass: number, extra: number | string }
*
* - `type` is trusted when it is a known Assets.assetType value or "vehicle";
* unknown/missing types fall back to classname heuristics.
* - For "vehicle" records `extra` is the transport mode ("air" | "sea" |
* "ground"; anything else -> "ground").
* - For "magazine" records `extra` is the round count (magazine roundCapacity).
* - `mass` imports into `vehicles.maxMass` for vehicle records (physical mass
* from the export); asset records do not carry a matching field.
*
* Legacy field aliases (`class`, `category`, `name`) are still accepted.
*
* planRecord() is pure (safe to unit test); enrichPlanMedia() does the
* filesystem work (.paa lookup, hemtt PAA->PNG conversion, screenshot
* matching); upsertPlan() writes to Payload and is an idempotent upsert —
* assets keyed by `className`, vehicles by `classname`. Updates refresh only
* in-game data (name, assetType/transportMode, mod, description) and attach a
* new thumbnail/image only when a fresh media doc was produced, so
* approvalStatus and human-edited "Virtual Data" are never reset.
*/
import { spawnSync } from "child_process";
import { existsSync, mkdirSync, readFileSync, statSync } from "fs";
import { join } from "path";
import type { Payload } from "payload";
import { plaintextToLexical } from "@/lib/tickets/lexical";
/** Mirrors the Assets collection's assetType enum (src/collections/logistics/Assets.ts). */
export const ASSET_TYPES = [
"weapon", "magazine", "optic", "muzzle", "bipod", "uniform", "vest",
"backpack", "helmet", "facewear", "nvg", "radio", "medical", "tool",
"explosive", "skin", "accessory", "miscellaneous",
] as const;
export type AssetType = (typeof ASSET_TYPES)[number];
export type TransportMode = "ground" | "air" | "sea";
const ASSET_TYPE_SET = new Set<string>(ASSET_TYPES);
const TRANSPORT_MODES: readonly string[] = ["ground", "air", "sea"];
export interface CatalogRecord {
classname?: string;
/** Legacy alias for classname. */
class?: string;
type?: string;
/** Legacy alias for type. */
category?: string;
displayName?: string;
/** Legacy alias for displayName. */
name?: string;
picture?: string;
mod?: string;
description?: string;
/** Vehicles only: physical mass, imported into maxMass. */
mass?: number;
/** Transport mode for vehicles, round count for magazines, otherwise "". */
extra?: number | string;
/** Weapons only: slot plus classnames of compatible records in the same catalog. */
compat?: { slot?: string; magazines?: unknown; attachments?: unknown };
}
export interface PlanMedia {
/** Resolved .paa path under --paa-root (exists check only, no conversion). */
paaPath: string;
/** Converted PNG (only produced in approve mode by enrichPlanMedia). */
pngPath: string;
/** Matched --screenshots PNG/WebP/JPG preview for the classname. */
screenshotPath: string;
}
export interface ImportPlan {
kind: "asset" | "vehicle";
className: string;
displayName: string;
description: string;
/** The Assets.assetType value; "vehicle" for vehicle plans. */
assetType: AssetType | "vehicle";
/** Vehicles only. */
transportMode: TransportMode;
/** Vehicles only: physical mass from the export (written to maxMass). */
mass?: number;
/** Magazines only: round count from `extra`. */
roundCapacity?: number;
/** Weapons only: compatibility references (classnames), linked in a second pass. */
compat?: WeaponCompat;
mod: string;
/** Icon-map ref or rec.picture, used to resolve the .paa thumbnail. */
pictureRef: string;
media: PlanMedia;
}
export type WeaponSlot = "primary" | "secondary" | "launcher";
export interface WeaponCompat {
slot?: WeaponSlot;
/** Deduplicated (case-insensitive) classnames. */
magazines: string[];
attachments: string[];
}
/** Classnames from an untrusted JSON list: strings only, trimmed, case-insensitive unique. */
function classList(value: unknown): string[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
const out: string[] = [];
for (const item of value) {
if (typeof item !== "string") continue;
const name = item.trim();
const key = name.toLowerCase();
if (!name || seen.has(key)) continue;
seen.add(key);
out.push(name);
}
return out;
}
function parseCompat(raw: CatalogRecord["compat"]): WeaponCompat | undefined {
if (!raw || typeof raw !== "object") return undefined;
const slot = ["primary", "secondary", "launcher"].includes(String(raw.slot))
? (raw.slot as WeaponSlot)
: undefined;
const magazines = classList(raw.magazines);
const attachments = classList(raw.attachments);
if (!slot && magazines.length === 0 && attachments.length === 0) return undefined;
return { ...(slot ? { slot } : {}), magazines, attachments };
}
export interface PlanLookups {
/** icon_map JSON: classname -> .paa ref (takes priority over rec.picture). */
icons?: Record<string, unknown>;
}
function lookupIcon(icons: Record<string, unknown> | undefined, className: string): string {
if (!icons || typeof icons !== "object") return "";
for (const [key, value] of Object.entries(icons)) {
if (key.toLowerCase() === className.toLowerCase() && typeof value === "string") return value;
}
return "";
}
/**
* Classify an asset record. Known types win; unknown types fall back to
* classname heuristics, ending at "miscellaneous" (a valid enum value — the
* old "item" fallback was not).
*/
function classifyAssetType(className: string, type: string): AssetType {
const t = (type || "").toLowerCase();
if (ASSET_TYPE_SET.has(t)) return t as AssetType;
const c = className.toLowerCase();
if (c.includes("mag") || c.startsWith("30rnd") || c.startsWith("20rnd")) return "magazine";
if (/^(arifle|smg|hgun|srifle|lm|mmg|rifle|launch)/.test(c)) return "weapon";
if (/^(30|40|45|9|7|5|6|12|mag_|rhs_mag)/.test(c)) return "magazine";
return "miscellaneous";
}
/** Legacy vehicle heuristic, used only when `type` is not a known value. */
function looksLikeVehicle(className: string, type: string): boolean {
if (type && /vehicle|car|tank|uav|ship|heli|truck/.test(type.toLowerCase())) return true;
const c = className.toLowerCase();
return (
/^(b_|o_|i_|c_)(mr|tru|car|heli|tank|uav|boat|apc|lt|soldier)/.test(c) &&
!/backpack|vest|helmet/.test(c)
);
}
/** Numeric `extra` (round count for magazines); tolerates numeric strings. */
function numericExtra(extra: number | string | undefined): number | undefined {
if (extra === undefined || extra === "") return undefined;
const n = typeof extra === "number" ? extra : Number(String(extra).trim());
return Number.isFinite(n) && n > 0 ? n : undefined;
}
/** Transport mode from a vehicle record's `extra`, defaulting to "ground". */
function transportModeFromExtra(extra: number | string | undefined): TransportMode {
if (typeof extra === "string" && TRANSPORT_MODES.includes(extra.trim().toLowerCase())) {
return extra.trim().toLowerCase() as TransportMode;
}
return "ground";
}
/**
* Default Vehicles.category derived from the transport mode. Only applied
* when a template has no category yet; officers refine it by hand (the export
* carries no doctrine classification).
*/
export function defaultCategoryForTransport(mode: TransportMode): "utility" | "transport" {
return mode === "ground" ? "utility" : "transport";
}
/** Positive finite mass from a catalog record, undefined otherwise. */
function positiveMass(mass: number | undefined): number | undefined {
return typeof mass === "number" && Number.isFinite(mass) && mass > 0 ? mass : undefined;
}
/**
* Plan one catalog record (pure — no filesystem or database access).
* Returns undefined for records without a usable classname.
*/
export function planRecord(rec: CatalogRecord, lookups: PlanLookups = {}): ImportPlan | undefined {
const className = String(rec.classname ?? rec.class ?? "").trim();
if (!className) return undefined;
const rawType = String(rec.type ?? rec.category ?? "").trim().toLowerCase();
const displayName = String(rec.displayName ?? rec.name ?? "").trim() || className;
const description = String(rec.description ?? "").trim();
const mod = String(rec.mod ?? "").trim() || "Arma 3";
const pictureRef = lookupIcon(lookups.icons, className) || String(rec.picture ?? "").trim();
if (rawType === "vehicle" || (!ASSET_TYPE_SET.has(rawType) && looksLikeVehicle(className, rawType))) {
const mass = positiveMass(rec.mass);
return {
kind: "vehicle",
className,
displayName,
description,
assetType: "vehicle",
transportMode: transportModeFromExtra(rec.extra),
...(mass !== undefined ? { mass } : {}),
mod,
pictureRef,
media: { paaPath: "", pngPath: "", screenshotPath: "" },
};
}
const assetType = classifyAssetType(className, rawType);
const roundCapacity = assetType === "magazine" ? numericExtra(rec.extra) : undefined;
const compat = assetType === "weapon" ? parseCompat(rec.compat) : undefined;
return {
kind: "asset",
className,
displayName,
description,
assetType,
transportMode: "ground",
...(roundCapacity !== undefined ? { roundCapacity } : {}),
...(compat ? { compat } : {}),
mod,
pictureRef,
media: { paaPath: "", pngPath: "", screenshotPath: "" },
};
}
/* -------------------------------------------------------------------------
* Filesystem media resolution (CLI only — never runs in planRecord/tests)
* ----------------------------------------------------------------------- */
function basename(p: string): string {
const seg = p.split(/[\\/]/);
return seg[seg.length - 1];
}
function resolvePaaPath(ref: string, paaRoot: string): string {
if (!ref || !paaRoot) return "";
const clean = ref.replace(/^[\\/]+/, "").replace(/\\/g, "/");
const cand = join(paaRoot, clean);
return existsSync(cand) ? cand : "";
}
function convertPaaToPng(hemtt: string, paaPath: string, outDir: string): string | undefined {
const dest = join(outDir, basename(paaPath).replace(/\.paa$/i, "") + ".png");
if (existsSync(dest)) return dest;
mkdirSync(outDir, { recursive: true });
const r = spawnSync(hemtt, ["utils", "paa", "convert", paaPath, dest], { encoding: "utf8" });
return r.status === 0 && existsSync(dest) ? dest : undefined;
}
export interface MediaEnv {
/** Root mirroring ref paths where extracted .paa files live. */
paaRoot: string;
/** PNG/WebP/JPG per-classname 3D-rendered previews ("" to disable). */
screenshots: string;
/** Destination for converted PNGs. */
outDir: string;
/** hemtt binary used for the PAA->PNG conversion. */
hemtt: string;
}
/**
* Resolve media for a plan on the filesystem: .paa ref -> existing file,
* converted PNG, and screenshot match. With `convert = false` (dry-run) this
* is read-only: the .paa existence check runs but no PNG is produced.
*/
export function enrichPlanMedia(plan: ImportPlan, env: MediaEnv, convert = true): void {
const paaPath = resolvePaaPath(plan.pictureRef, env.paaRoot);
plan.media.paaPath = paaPath;
if (paaPath && convert) {
plan.media.pngPath = convertPaaToPng(env.hemtt, paaPath, env.outDir) ?? "";
}
// Skip 0-byte images: Arma's screenshot command writes empty files when the
// game is misconfigured (HDR below 16-bit), and uploading one fails.
plan.media.screenshotPath = env.screenshots
? (["png", "webp", "jpg"]
.map((ext) => join(env.screenshots, plan.className + "." + ext))
.find(hasContent) ?? "")
: "";
}
/* -------------------------------------------------------------------------
* Database writes (Payload local API)
* ----------------------------------------------------------------------- */
/** A file that exists and actually has bytes in it. */
function hasContent(path: string): boolean {
if (!existsSync(path)) return false;
try {
return statSync(path).size > 0;
} catch {
return false;
}
}
/**
* Resolve the fuel resource id required by Vehicles.fuel.fuelType.
* Looked up by code name first (`res_fuel` by default, which is stable even
* when the display name is something like "Gasoline"), then by a name equal
* to "Fuel" in any casing. Pass a different code name to use another resource.
*/
export async function resolveFuelConfig(payload: Payload, codeName = "res_fuel"): Promise<number> {
const byCode = await payload.find({
collection: "resources",
where: { codeName: { equals: codeName } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (byCode.docs[0]) return Number(byCode.docs[0].id);
const byName = await payload.find({
collection: "resources",
where: { name: { like: "fuel" } },
limit: 50,
depth: 0,
overrideAccess: true,
});
const fuel = byName.docs.find((d) => String(d.name).trim().toLowerCase() === "fuel");
if (!fuel) {
throw new Error(
`No fuel resource found (code name '${codeName}' or name 'Fuel'). Cannot set vehicle fuel fields; pass --fuel <codeName>.`,
);
}
return Number(fuel.id);
}
export interface UpsertResult {
action: "created" | "updated";
collection: "assets" | "vehicles";
id: number;
}
/**
* Upsert one planned record into `assets` (keyed by `className`) or
* `vehicles` (keyed by `classname`), exact match. `fuelId` (from
* resolveFuelConfig) is required for vehicle plans.
*/
export async function upsertPlan(payload: Payload, plan: ImportPlan, fuelId?: number): Promise<UpsertResult> {
return plan.kind === "vehicle" ? upsertVehicle(payload, plan, fuelId) : upsertAsset(payload, plan);
}
const IMAGE_MIMETYPES: Record<string, string> = {
png: "image/png",
webp: "image/webp",
jpg: "image/jpeg",
jpeg: "image/jpeg",
};
/**
* Find-or-create a media doc for the file, deduped by filename so re-runs
* reuse the same media row instead of piling up duplicates. `created` tells
* callers whether this run actually produced a new image; only then is an
* existing doc's thumbnail/image refreshed (a human-chosen image is kept).
* Failures resolve to undefined — the record is still imported, just without
* an image.
*/
async function resolveMedia(payload: Payload, filePath: string): Promise<{ id: number; created: boolean } | undefined> {
try {
const fileName = basename(filePath);
const buffer = readFileSync(filePath);
const ext = (fileName.split(".").pop() ?? "").toLowerCase();
const mimetype = IMAGE_MIMETYPES[ext] ?? "application/octet-stream";
const existing = await payload.find({
collection: "media",
where: { filename: { equals: fileName } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) return { id: Number(existing.docs[0].id), created: false };
const created = await payload.create({
collection: "media",
data: { alt: fileName },
file: { data: buffer, mimetype, name: fileName, size: buffer.length },
overrideAccess: true,
});
return { id: Number(created.id), created: true };
} catch {
return undefined;
}
}
/** First available image path for the plan, or "" when none was produced. */
function planImagePath(plan: ImportPlan): string {
return plan.media.pngPath || plan.media.screenshotPath || "";
}
/**
* Asset metadata group written on every import (mod) — gameDescription only
* when the record carries a description, so an empty export can never wipe a
* human-entered description. thumbnail is appended by the caller when a new
* image exists.
*/
function assetMetadata(plan: ImportPlan): Record<string, unknown> {
const metadata: Record<string, unknown> = { mod: plan.mod };
if (plan.description) metadata.gameDescription = plan.description;
return metadata;
}
async function upsertAsset(payload: Payload, plan: ImportPlan): Promise<UpsertResult> {
// planRecord guarantees a real Assets.assetType value for kind "asset".
const assetType = plan.assetType as AssetType;
const existing = await payload.find({
collection: "assets",
where: { className: { equals: plan.className } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) {
const id = Number(existing.docs[0].id);
const data: Record<string, unknown> = {
name: plan.displayName,
assetType,
"Asset Metadata": assetMetadata(plan),
};
const imagePath = planImagePath(plan);
// Attach an image whenever the record has none. That covers importing the
// catalog first and adding screenshots in a later run, and repairs records
// whose image never landed. An image that is already set is never replaced
// (it may be a human's choice), and resolveMedia reuses an existing media
// doc, so repeated runs do not pile up duplicates.
const current = existing.docs[0] as unknown as { "Asset Metadata"?: { thumbnail?: unknown } };
if (imagePath && !current["Asset Metadata"]?.thumbnail) {
const media = await resolveMedia(payload, imagePath);
if (media) (data["Asset Metadata"] as Record<string, unknown>).thumbnail = media.id;
}
await payload.update({ collection: "assets", id, data, overrideAccess: true });
return { action: "updated", collection: "assets", id };
}
const imagePath = planImagePath(plan);
const mediaId = imagePath ? (await resolveMedia(payload, imagePath))?.id : undefined;
const data: Record<string, unknown> = {
name: plan.displayName,
className: plan.className,
assetType,
"Asset Metadata": {
...assetMetadata(plan),
...(mediaId !== undefined ? { thumbnail: mediaId } : {}),
},
...(assetType === "magazine" && plan.roundCapacity !== undefined
? { "Magazine Configuration": { roundCapacity: plan.roundCapacity } }
: {}),
};
const created = await payload.create({
collection: "assets",
// draft: false pins the non-draft create overload; `as never` satisfies
// the generated create type, which marks defaultValue-backed fields
// (approvalStatus, crafting, storageDimensions) required even though
// Payload fills them at runtime (repo precedent: reservationOptions.ts).
draft: false,
data: data as never,
overrideAccess: true,
});
return { action: "created", collection: "assets", id: Number(created.id) };
}
async function upsertVehicle(payload: Payload, plan: ImportPlan, fuelId: number | undefined): Promise<UpsertResult> {
if (!fuelId) throw new Error("No resource named 'Fuel' found. Cannot set vehicle fuel fields");
const existing = await payload.find({
collection: "vehicles",
where: { classname: { equals: plan.className } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) {
const id = Number(existing.docs[0].id);
const data: Record<string, unknown> = {
name: plan.displayName,
transportMode: plan.transportMode,
};
if (plan.description) data.description = plaintextToLexical(plan.description);
// Physical mass is pure game data: refresh it on every import.
if (plan.mass !== undefined) data.maxMass = plan.mass;
const imagePath = planImagePath(plan);
// Same rule as assets: fill an empty image, never replace one that is set.
const current = existing.docs[0] as unknown as { image?: unknown; category?: unknown };
// Category default only fills templates nobody has classified yet.
if (!Array.isArray(current.category) || current.category.length === 0) {
data.category = [defaultCategoryForTransport(plan.transportMode)];
}
if (imagePath && !current.image) {
const media = await resolveMedia(payload, imagePath);
if (media) data.image = media.id;
}
await payload.update({ collection: "vehicles", id, data, overrideAccess: true });
return { action: "updated", collection: "vehicles", id };
}
const imagePath = planImagePath(plan);
const mediaId = imagePath ? (await resolveMedia(payload, imagePath))?.id : undefined;
const data: Record<string, unknown> = {
name: plan.displayName,
classname: plan.className,
fuel: { fuelType: fuelId, fuelCapacity: 100, fuelConsumptionRate: 1 },
transportMode: plan.transportMode,
category: [defaultCategoryForTransport(plan.transportMode)],
...(plan.mass !== undefined ? { maxMass: plan.mass } : {}),
...(plan.description ? { description: plaintextToLexical(plan.description) } : {}),
...(mediaId !== undefined ? { image: mediaId } : {}),
};
const created = await payload.create({
collection: "vehicles",
// draft: false pins the non-draft create overload; `as never` satisfies
// the generated create type (approvalStatus is marked required though
// Payload fills the default at runtime).
draft: false,
data: data as never,
overrideAccess: true,
});
return { action: "created", collection: "vehicles", id: Number(created.id) };
}
/* -------------------------------------------------------------------------
* Weapon compatibility (second pass, after every record has been upserted)
* ----------------------------------------------------------------------- */
/** Asset types each Weapon Configuration relationship accepts (its filterOptions). */
const MAGAZINE_TYPES = new Set<string>(["magazine"]);
const ATTACHMENT_TYPES = new Set<string>(["optic", "muzzle", "bipod", "accessory"]);
export interface CompatLinkResult {
/** Weapons whose relationships or slot changed. */
updated: number;
/** Weapons already up to date. */
unchanged: number;
/** Weapon classnames not found in the assets collection. */
missingWeapons: number;
/** References to classnames that are not imported assets. */
unresolved: number;
/** References to assets of a type the relationship does not accept
* (e.g. rail lights/lasers, which import as "miscellaneous"). */
skippedType: number;
errors: number;
}
function relationIds(value: unknown): number[] {
if (!Array.isArray(value)) return [];
return value
.map((v) => (typeof v === "number" ? v : typeof v === "object" && v && "id" in v ? Number((v as { id: unknown }).id) : NaN))
.filter((n) => Number.isFinite(n));
}
/**
* Links each weapon to its compatible magazines and attachments. These are
* relationships to the asset rows that were imported, so nothing is copied
* or duplicated. Links are MERGED with what is already on the weapon (links
* added by hand are kept) and deduplicated; the slot is only filled when it
* is empty. Run after upserting the whole catalog, so references to records
* later in the file resolve.
*/
export async function linkWeaponCompatibility(
payload: Payload,
plans: ImportPlan[],
log: (line: string) => void = () => {},
): Promise<CompatLinkResult> {
const result: CompatLinkResult = { updated: 0, unchanged: 0, missingWeapons: 0, unresolved: 0, skippedType: 0, errors: 0 };
const weapons = plans.filter((p) => p.kind === "asset" && p.compat);
if (weapons.length === 0) return result;
// One lookup table for every classname involved: weapons + their references.
const wanted = new Set<string>();
for (const w of weapons) {
wanted.add(w.className);
for (const c of [...w.compat!.magazines, ...w.compat!.attachments]) wanted.add(c);
}
const byLower = new Map<string, { id: number; assetType: string }>();
const names = [...wanted];
for (let i = 0; i < names.length; i += 500) {
const chunk = names.slice(i, i + 500);
const found = await payload.find({
collection: "assets",
where: { className: { in: chunk } },
limit: chunk.length * 2,
depth: 0,
pagination: false,
overrideAccess: true,
});
for (const doc of found.docs) {
const key = String(doc.className).toLowerCase();
if (!byLower.has(key)) byLower.set(key, { id: Number(doc.id), assetType: String(doc.assetType) });
}
}
// The exporter writes each reference with the referenced record's own
// classname, so the exact-match query above finds it; the map is keyed in
// lower case only so duplicates that differ in case collapse to one id.
const resolve = (name: string, allowed: Set<string>, into: number[]) => {
const hit = byLower.get(name.toLowerCase());
if (!hit) { result.unresolved++; return; }
if (!allowed.has(hit.assetType)) { result.skippedType++; return; }
if (!into.includes(hit.id)) into.push(hit.id);
};
for (const weapon of weapons) {
const self = byLower.get(weapon.className.toLowerCase());
if (!self) { result.missingWeapons++; continue; }
try {
const doc = await payload.findByID({ collection: "assets", id: self.id, depth: 0, overrideAccess: true });
const config = (doc as unknown as { "Weapon Configuration"?: Record<string, unknown> })["Weapon Configuration"] ?? {};
const currentMags = relationIds(config.compatibleMagazines);
const currentAtts = relationIds(config.compatibleAttachments);
const mags = [...currentMags];
const atts = [...currentAtts];
for (const m of weapon.compat!.magazines) resolve(m, MAGAZINE_TYPES, mags);
for (const a of weapon.compat!.attachments) resolve(a, ATTACHMENT_TYPES, atts);
const slot = config.slotType || weapon.compat!.slot || undefined;
const changed = mags.length !== currentMags.length
|| atts.length !== currentAtts.length
|| (slot ?? null) !== (config.slotType ?? null);
if (!changed) { result.unchanged++; continue; }
await payload.update({
collection: "assets",
id: self.id,
data: {
"Weapon Configuration": {
...(slot ? { slotType: slot } : {}),
compatibleMagazines: mags,
compatibleAttachments: atts,
},
} as never,
overrideAccess: true,
});
result.updated++;
log(`Linked ${weapon.className}: ${mags.length} magazines, ${atts.length} attachments`);
} catch (e) {
result.errors++;
log(`ERR linking ${weapon.className}: ${(e as Error).message}`);
}
}
return result;
}