just took a big shit on that thing, packer complete, please god kill me 1000+ changes :))))))))))

This commit is contained in:
2026-10-22 11:38:48 +02:00
parent 379b6203cd
commit 1a4fd6b31e
556 changed files with 10810 additions and 462 deletions
+8 -5
View File
@@ -15,15 +15,18 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"check": "tsc --noEmit"
"check": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"shimejic": "workspace:*",
"sharp": "^0.33.0",
"cac": "^6.7.14"
"cac": "^6.7.14",
"sharp": "catalog:",
"shimejic": "workspace:*"
},
"devDependencies": {
"@types/node": "^22.0.0",
"sharp": "catalog:",
"typescript": "catalog:",
"@types/node": "^22.0.0"
"vitest": "catalog:"
}
}
+234 -34
View File
@@ -1,44 +1,244 @@
#!/usr/bin/env node
/**
* cli.ts — command-line interface for the packer.
*
* Wraps `pack()` from index.ts. Parses arguments with cac, calls the
* orchestrator, formats output for a terminal. Exit code reflects
* success (0) or failure (1).
*
* Two output modes:
* - Default: concise summary per atlas, warnings, errors.
* - --verbose: additionally lists every file written and per-frame
* position details.
*
* --dry-run calls pack({ dryRun: true }) which goes through the full
* pipeline but skips all writes. Reports what would happen. Useful for
* verifying config changes before committing them.
*/
import { cac } from "cac";
import { pack } from "./index.js";
import { pack, PACKER_VERSION, type PackResult } from "./index.js";
const cli = cac("shimejic-pack");
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
cli.command("<input>", "Path to character asset folder")
.option("-o, --output <path>", "Output directory (default: ./dist)")
.option("-c, --config <path>", "Overrides JSON (default: <input>/character.config.json)")
.option("--dry-run", "Report without writing files")
.option("--verbose", "Verbose output")
.action(async (input: string, options: Record<string, unknown>) => {
try {
const result = await pack({
input,
output: (options.output as string | undefined) ?? "./dist",
...(options.config !== undefined && { config: options.config as string }),
...(options.dryRun !== undefined && { dryRun: Boolean(options.dryRun) }),
});
interface CliOptions {
output?: string;
config?: string;
maxAtlasSize?: string | number;
effort?: string | number;
dryRun?: boolean;
verbose?: boolean;
}
if (!result.ok) {
if (result.errors) {
for (const err of result.errors) {
console.error(`[error] ${err.path}: ${err.message}`);
}
}
process.exit(1);
}
/* ------------------------------------------------------------------ */
/* Main */
/* ------------------------------------------------------------------ */
if (result.warnings && result.warnings.length > 0) {
for (const w of result.warnings) console.warn(`[warn] ${w}`);
}
export async function runCli(argv: string[]): Promise<number> {
const cli = cac("shimejic-pack");
console.log("shimejic-pack: not implemented yet");
process.exit(0);
} catch (err) {
console.error(`[fatal] ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
cli.command("<input>", "Path to character asset folder")
.option("-o, --output <path>", "Output directory (default: ./dist)")
.option("-c, --config <path>", "Overrides JSON (default: <input>/character.config.json)")
.option("--max-atlas-size <px>", "Max atlas dimension (default: 2048)")
.option("--effort <n>", "WebP compression effort 0-6 (default: 6)")
.option("--dry-run", "Report without writing files")
.option("--verbose", "Verbose output");
cli.help();
cli.version(PACKER_VERSION);
let parsed: ReturnType<typeof cli.parse>;
try {
parsed = cli.parse(["node", "shimejic-pack", ...argv]);
} catch (err) {
// cac throws on parse errors (unknown flag, missing arg)
console.error(`[error] ${err instanceof Error ? err.message : String(err)}`);
return 1;
}
// --help / --version exit through cac's own handlers
if (parsed.options.help || parsed.options.version) {
return 0;
}
const args = parsed.args as string[];
const input = args[0];
if (input === undefined) {
console.error("[error] Missing required argument: <input>");
cli.outputHelp();
return 1;
}
const options = parsed.options as CliOptions;
const output = options.output ?? "./dist";
/* ---------------- Parse numeric options ---------------- */
let maxAtlasSize: number | undefined;
if (options.maxAtlasSize !== undefined) {
const n = parseInt(String(options.maxAtlasSize), 10);
if (!Number.isFinite(n) || n <= 0) {
console.error(`[error] Invalid --max-atlas-size: "${options.maxAtlasSize}"`);
return 1;
}
maxAtlasSize = n;
}
let effort: number | undefined;
if (options.effort !== undefined) {
const n = parseInt(String(options.effort), 10);
if (!Number.isFinite(n) || n < 0 || n > 6) {
console.error(`[error] Invalid --effort: "${options.effort}" (must be 0-6)`);
return 1;
}
effort = n;
}
/* ---------------- Run pack ---------------- */
let result: PackResult;
try {
result = await pack({
input,
output,
...(options.config !== undefined && { config: options.config }),
...(maxAtlasSize !== undefined && { maxAtlasSize }),
...(effort !== undefined && { effort }),
dryRun: options.dryRun === true,
});
} catch (err) {
console.error(`[fatal] ${err instanceof Error ? err.message : String(err)}`);
return 1;
}
/* ---------------- Format output ---------------- */
printResult(result, {
dryRun: options.dryRun === true,
verbose: options.verbose === true,
});
cli.help();
cli.version("0.0.1");
cli.parse();
return result.ok ? 0 : 1;
}
/* ------------------------------------------------------------------ */
/* Output formatting */
/* ------------------------------------------------------------------ */
interface PrintOptions {
dryRun: boolean;
verbose: boolean;
}
function printResult(result: PackResult, opts: PrintOptions): void {
const { dryRun, verbose } = opts;
const prefix = dryRun ? "[dry-run] " : "";
// Warnings
if (result.warnings && result.warnings.length > 0) {
for (const w of result.warnings) {
console.warn(`${prefix}[warn] ${w}`);
}
}
// Errors — print regardless of ok, since ok:false means these are why
if (!result.ok) {
if (result.errors && result.errors.length > 0) {
for (const err of result.errors) {
console.error(`${prefix}[error] ${err.path}: ${err.message}`);
}
} else {
console.error(`${prefix}[error] Packer failed with no error details.`);
}
return;
}
// Atlas summary
if (result.atlases && result.atlases.length > 0) {
const reused = result.atlases.filter(a => a.action === "reused").length;
const encoded = result.atlases.filter(a => a.action === "encoded").length;
if (verbose) {
for (const atlas of result.atlases) {
const icon = atlas.action === "encoded" ? "✎" : "·";
const label = atlas.action === "encoded" ? "encoded" : "reused ";
const size = formatBytes(atlas.bytes);
console.log(`${prefix} ${icon} ${atlas.id.padEnd(32)} ${label} ${atlas.atlasHash} ${size}`);
}
console.log();
}
const totalBytes = result.atlases.reduce((s, a) => s + a.bytes, 0);
console.log(`${prefix}${result.atlases.length} atlases: ${encoded} encoded, ${reused} reused`);
if (encoded > 0) {
console.log(`${prefix} ${formatBytes(totalBytes)} generated`);
}
}
// Orphans
if (result.orphansDeleted && result.orphansDeleted.length > 0) {
console.log(
`${prefix}Deleted ${result.orphansDeleted.length} orphaned atlas${
result.orphansDeleted.length === 1 ? "" : "s"
}`,
);
if (verbose) {
for (const o of result.orphansDeleted) {
console.log(`${prefix} - ${o}`);
}
}
}
// Written files
if (!dryRun && result.written) {
if (verbose) {
console.log();
if (result.written.config) {
console.log(`${prefix}Wrote ${result.written.config}`);
}
if (result.written.manifest) {
console.log(`${prefix}Wrote ${result.written.manifest}`);
}
if (result.written.atlases.length > 0) {
for (const a of result.written.atlases) {
console.log(`${prefix}Wrote ${a}`);
}
}
}
}
// Success line
if (!verbose && !dryRun) {
console.log(`${prefix}Done.`);
}
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
/* ------------------------------------------------------------------ */
/* Bootstrap */
/* ------------------------------------------------------------------ */
// Guard against import — only run when executed directly.
// `import.meta.url` comparisons are the ESM idiom for "is this the main module".
const isMainModule =
import.meta.url === `file://${process.argv[1]}` ||
import.meta.url.endsWith(process.argv[1]?.replace(/\\/g, "/") ?? "");
if (isMainModule) {
runCli(process.argv.slice(2)).then(
code => process.exit(code),
err => {
console.error(`[fatal] ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
},
);
}
+685
View File
@@ -0,0 +1,685 @@
/**
* config-gen.ts — merge scan + encode results + user overrides into a
* final CharacterConfig.
*
* The output shape matches the shimejic library's `CharacterConfig` type.
* Every field is either explicit (from user's `character.config.json`),
* inferred from the folder structure (scan result), or defaulted with a
* warning.
*
* Atlas URLs point at the encoded WebP filenames:
*
* atlases/<atlasId>.<atlasHash>.webp
*
* Consumers fetch `<config>`, then resolve atlas URLs relative to the
* config file's location.
*
* Frame names within clips match the original filename (with extension
* for state frames, without for icons). Consumers look up frames by
* these names in the atlas definition.
*
* Errors are accumulated, not thrown. Missing required config (look
* distance, bubble dimensions) errors. Missing optional config (voice,
* text, timing) uses library defaults silently.
*/
import type {
AtlasDefinition,
BubbleDefinition,
CharacterConfig,
ClipDefinition,
EventDefinition,
FrameRegion,
IconDefinition,
LookDefinition,
LookSectorDefinition,
StateDefinition,
TextDefinition,
TimingDefinition,
VoiceDefinition,
} from "shimejic";
import type { EncodedAtlas } from "./encode.js";
import type { ScanResult, ScannedState } from "./scan.js";
/* ------------------------------------------------------------------ */
/* Packer input config (character.config.json) */
/* ------------------------------------------------------------------ */
export interface StateConfig {
base?: {
framerate?: number;
loop?: boolean;
};
look?: {
pivot: { x: number; y: number };
distance: { min: number; max: number };
hysteresis?: number;
sectors?: Record<
string,
{
minAngle: number;
maxAngle: number;
minDistance?: number;
maxDistance?: number;
}
>;
};
events?: Record<
string,
{
framerate?: number;
chance?: number;
interval?: [number, number];
cooldown?: number;
weight?: number;
interrupt?: "cut" | "finish";
chatter?: Array<{
at: number;
unit: "frame" | "ms";
text: string;
}>;
}
>;
}
export interface BubblePackConfig {
width: number;
height: number;
framerate?: number;
anchorX?: number;
anchorY?: number;
frameMode?: "loop" | "hold" | "reverse-on-dismiss";
text?: Partial<TextDefinition>;
}
export interface PackerConfig {
id?: string;
initialState?: string;
spawnState?: string;
defaults?: {
framerate?: number;
clipLoop?: boolean;
};
states?: Record<string, StateConfig>;
bubbles?: Record<string, BubblePackConfig>;
text?: Partial<TextDefinition>;
timing?: Partial<TimingDefinition>;
voice?: VoiceDefinition;
}
/* ------------------------------------------------------------------ */
/* Constants */
/* ------------------------------------------------------------------ */
const COMPASS_ANGLES: Record<string, [number, number]> = {
t: [337.5, 22.5],
tr: [22.5, 67.5],
r: [67.5, 112.5],
br: [112.5, 157.5],
b: [157.5, 202.5],
bl: [202.5, 247.5],
l: [247.5, 292.5],
tl: [292.5, 337.5],
up: [337.5, 22.5],
"up-right": [22.5, 67.5],
right: [67.5, 112.5],
"down-right": [112.5, 157.5],
down: [157.5, 202.5],
"down-left": [202.5, 247.5],
left: [247.5, 292.5],
"up-left": [292.5, 337.5],
};
const DEFAULT_FRAMERATE = 8;
const DEFAULT_CLIP_LOOP = true;
const DEFAULT_HYSTERESIS = 1;
const DEFAULT_EVENT_CHANCE = 0.4;
const DEFAULT_EVENT_INTERVAL: [number, number] = [4, 10];
const DEFAULT_EVENT_COOLDOWN = 6;
const DEFAULT_EVENT_WEIGHT = 1;
const DEFAULT_EVENT_INTERRUPT = "cut" as const;
/* ------------------------------------------------------------------ */
/* Result types */
/* ------------------------------------------------------------------ */
export interface ConfigGenInput {
scanned: ScanResult;
encoded: Map<string, EncodedAtlas>;
overrides: PackerConfig | null;
/** Fallback id if overrides don't specify one. Typically the input folder's basename. */
fallbackId: string;
}
export interface ConfigGenResult {
config: CharacterConfig | null;
warnings: string[];
errors: Array<{ path: string; message: string }>;
}
/* ------------------------------------------------------------------ */
/* Main entry */
/* ------------------------------------------------------------------ */
export function generateConfig(input: ConfigGenInput): ConfigGenResult {
const warnings: string[] = [];
const errors: Array<{ path: string; message: string }> = [];
// Scanned errors propagate directly
for (const err of input.scanned.errors) {
errors.push({ path: err.path, message: err.message });
}
warnings.push(...input.scanned.warnings);
if (errors.length > 0) {
return { config: null, warnings, errors };
}
const overrides = input.overrides ?? {};
const defaults = {
framerate: overrides.defaults?.framerate ?? DEFAULT_FRAMERATE,
clipLoop: overrides.defaults?.clipLoop ?? DEFAULT_CLIP_LOOP,
};
const id = overrides.id ?? input.fallbackId;
const initialState = resolveInitialState(input.scanned, overrides, warnings, errors);
if (initialState === null) {
return { config: null, warnings, errors };
}
const spawnState = resolveSpawnState(input.scanned, overrides, errors);
const atlases = buildAtlases(input.scanned, input.encoded, errors);
const states = buildStates(input.scanned, overrides, defaults, atlases, warnings, errors);
const bubbles = buildBubbles(input.scanned, overrides, input.encoded, errors);
const icons = buildIcons(input.scanned);
if (errors.length > 0) {
return { config: null, warnings, errors };
}
const config: CharacterConfig = {
version: 1,
id,
initialState,
atlases,
states,
bubbles,
...(spawnState !== null && { spawnState }),
...(icons !== undefined && { icons }),
...(overrides.text !== undefined && { text: overrides.text }),
...(overrides.timing !== undefined && { timing: overrides.timing }),
...(overrides.voice !== undefined && { voice: overrides.voice }),
};
return { config, warnings, errors };
}
/* ------------------------------------------------------------------ */
/* Top-level resolution */
/* ------------------------------------------------------------------ */
function resolveInitialState(
scanned: ScanResult,
overrides: PackerConfig,
warnings: string[],
errors: Array<{ path: string; message: string }>,
): string | null {
if (overrides.initialState !== undefined) {
if (!scanned.states.has(overrides.initialState)) {
errors.push({
path: "initialState",
message: `Config refers to unknown state "${overrides.initialState}". Available states: ${[...scanned.states.keys()].join(", ") || "(none)"}.`,
});
return null;
}
return overrides.initialState;
}
const stateNames = [...scanned.states.keys()].sort();
if (stateNames.length === 0) {
errors.push({
path: "states",
message: "No states found. Character must have at least one state.",
});
return null;
}
const first = stateNames[0]!;
warnings.push(
`initialState defaulted to "${first}" (first alphabetically). Set "initialState" in character.config.json to override.`,
);
return first;
}
function resolveSpawnState(
scanned: ScanResult,
overrides: PackerConfig,
errors: Array<{ path: string; message: string }>,
): string | null {
if (overrides.spawnState === undefined) return null;
if (!scanned.states.has(overrides.spawnState)) {
errors.push({
path: "spawnState",
message: `Config refers to unknown state "${overrides.spawnState}".`,
});
return null;
}
return overrides.spawnState;
}
/* ------------------------------------------------------------------ */
/* Atlases */
/* ------------------------------------------------------------------ */
function buildAtlases(
scanned: ScanResult,
encoded: Map<string, EncodedAtlas>,
errors: Array<{ path: string; message: string }>,
): Record<string, AtlasDefinition> {
const result: Record<string, AtlasDefinition> = {};
for (const [id, scannedAtlas] of scanned.atlases) {
const encodedAtlas = encoded.get(id);
if (encodedAtlas === undefined) {
errors.push({
path: scannedAtlas.sourcePath,
message: `Atlas "${id}" was scanned but failed to encode.`,
});
continue;
}
const frames: Record<string, FrameRegion> = {};
for (const frame of scannedAtlas.frames) {
// For state frames, name includes .png extension (as it appears
// on disk). For icons, name has no extension (semantic identifier).
frames[frame.name] = {
x: 0, // placeholder — filled below from packed frames
y: 0,
w: frame.width,
h: frame.height,
};
}
// Overwrite with actual packed positions from the packed atlas.
// We don't have direct access to PackedAtlas here — only EncodedAtlas,
// which has dimensions and hash but not per-frame positions. So we
// recompute positions using the same grid math as pack.ts.
//
// Both pack.ts and config-gen use the same formula, so they stay
// in sync as long as the formula is stable. If pack.ts ever gains
// a new strategy (MaxRects for trim), this duplication must be
// eliminated by threading the PackedAtlas through.
const n = scannedAtlas.frames.length;
const cols = Math.ceil(Math.sqrt(n));
const cellW = scannedAtlas.width;
const cellH = scannedAtlas.height;
for (let i = 0; i < scannedAtlas.frames.length; i++) {
const frame = scannedAtlas.frames[i]!;
const col = i % cols;
const row = Math.floor(i / cols);
frames[frame.name] = {
x: col * cellW,
y: row * cellH,
w: cellW,
h: cellH,
};
}
result[id] = {
url: `atlases/${id}.${encodedAtlas.atlasHash}.webp`,
width: encodedAtlas.width,
height: encodedAtlas.height,
frames,
};
}
return result;
}
/* ------------------------------------------------------------------ */
/* States */
/* ------------------------------------------------------------------ */
interface Defaults {
framerate: number;
clipLoop: boolean;
}
function buildStates(
scanned: ScanResult,
overrides: PackerConfig,
defaults: Defaults,
atlases: Record<string, AtlasDefinition>,
warnings: string[],
errors: Array<{ path: string; message: string }>,
): Record<string, StateDefinition> {
const result: Record<string, StateDefinition> = {};
for (const [stateName, scannedState] of scanned.states) {
const stateOverrides = overrides.states?.[stateName] ?? {};
const built = buildState(stateName, scannedState, stateOverrides, defaults, atlases, scanned, warnings, errors);
if (built !== null) {
result[stateName] = built;
}
}
return result;
}
function buildState(
stateName: string,
scannedState: ScannedState,
stateOverrides: StateConfig,
defaults: Defaults,
atlases: Record<string, AtlasDefinition>,
scanned: ScanResult,
warnings: string[],
errors: Array<{ path: string; message: string }>,
): StateDefinition | null {
const baseAtlas = atlases[scannedState.baseAtlasId];
if (baseAtlas === undefined) {
errors.push({
path: `states.${stateName}.base`,
message: `Atlas "${scannedState.baseAtlasId}" is missing from encoded atlases.`,
});
return null;
}
const baseFrames = Object.keys(baseAtlas.frames);
const baseClip: ClipDefinition = {
atlas: scannedState.baseAtlasId,
frames: baseFrames,
framerate: stateOverrides.base?.framerate ?? defaults.framerate,
loop: stateOverrides.base?.loop ?? defaults.clipLoop,
};
const state: StateDefinition = { base: baseClip };
// Look sectors
if (scannedState.lookSectors.size > 0) {
const look = buildLook(stateName, scannedState, stateOverrides.look, atlases, baseFrames.length, errors);
if (look !== null) state.look = look;
}
// Events
if (scannedState.events.size > 0) {
const events = buildEvents(stateName, scannedState, stateOverrides.events, defaults, atlases, errors);
if (events.length > 0) state.events = events;
}
return state;
}
function buildLook(
stateName: string,
scannedState: ScannedState,
lookOverrides: StateConfig["look"],
atlases: Record<string, AtlasDefinition>,
baseFrameCount: number,
errors: Array<{ path: string; message: string }>,
): LookDefinition | null {
if (lookOverrides === undefined) {
errors.push({
path: `states.${stateName}.look`,
message: `State "${stateName}" has look sectors on disk but no "look" config. Add "states.${stateName}.look" with pivot and distance to character.config.json.`,
});
return null;
}
if (typeof lookOverrides.pivot?.x !== "number" || typeof lookOverrides.pivot?.y !== "number") {
errors.push({
path: `states.${stateName}.look.pivot`,
message: `"look.pivot" must have numeric x and y.`,
});
return null;
}
if (typeof lookOverrides.distance?.min !== "number" || typeof lookOverrides.distance?.max !== "number") {
errors.push({
path: `states.${stateName}.look.distance`,
message: `"look.distance" must have numeric min and max.`,
});
return null;
}
const sectors: LookSectorDefinition[] = [];
for (const [sectorName, sectorAtlasId] of scannedState.lookSectors) {
const sectorAtlas = atlases[sectorAtlasId];
if (sectorAtlas === undefined) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Atlas "${sectorAtlasId}" for sector "${sectorName}" is missing.`,
});
continue;
}
const frames = Object.keys(sectorAtlas.frames);
const explicitAngles = lookOverrides.sectors?.[sectorName];
const compassAngles = COMPASS_ANGLES[sectorName];
const angles = explicitAngles
? ([explicitAngles.minAngle, explicitAngles.maxAngle] as [number, number])
: compassAngles;
if (angles === undefined) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Sector "${sectorName}" has no angles in config, and "${sectorName}" is not a compass direction (t, tr, r, br, b, bl, l, tl or up, up-right, etc.). Add angles to character.config.json.`,
});
continue;
}
const sector: LookSectorDefinition = {
minAngle: angles[0],
maxAngle: angles[1],
folder: sectorName,
atlas: sectorAtlasId,
frames,
};
if (explicitAngles?.minDistance !== undefined || explicitAngles?.maxDistance !== undefined) {
if (explicitAngles?.minDistance === undefined || explicitAngles?.maxDistance === undefined) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Sector "${sectorName}" specifies only one of minDistance/maxDistance. Both must be set or both omitted.`,
});
continue;
}
if (explicitAngles.minDistance > explicitAngles.maxDistance) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Sector "${sectorName}" has minDistance (${explicitAngles.minDistance}) greater than maxDistance (${explicitAngles.maxDistance}).`,
});
continue;
}
sector.minDistance = explicitAngles.minDistance;
sector.maxDistance = explicitAngles.maxDistance;
}
sectors.push(sector);
}
// One final check: base frame count matches sector frame counts
for (const sector of sectors) {
if (sector.frames.length !== baseFrameCount) {
errors.push({
path: `states.${stateName}.look.sectors.${sector.folder}`,
message: `Sector "${sector.folder}" has ${sector.frames.length} frames, base has ${baseFrameCount}. Frame counts must match.`,
});
}
}
return {
pivot: lookOverrides.pivot,
distance: lookOverrides.distance,
hysteresis: lookOverrides.hysteresis ?? DEFAULT_HYSTERESIS,
sectors,
};
}
function buildEvents(
stateName: string,
scannedState: ScannedState,
eventOverrides: StateConfig["events"],
defaults: Defaults,
atlases: Record<string, AtlasDefinition>,
errors: Array<{ path: string; message: string }>,
): EventDefinition[] {
const result: EventDefinition[] = [];
for (const [eventName, eventAtlasId] of scannedState.events) {
const eventAtlas = atlases[eventAtlasId];
if (eventAtlas === undefined) {
errors.push({
path: `states.${stateName}.events.${eventName}`,
message: `Atlas "${eventAtlasId}" for event "${eventName}" is missing.`,
});
continue;
}
const overrides = eventOverrides?.[eventName] ?? {};
const event: EventDefinition = {
name: eventName,
atlas: eventAtlasId,
frames: Object.keys(eventAtlas.frames),
framerate: overrides.framerate ?? defaults.framerate,
chance: overrides.chance ?? DEFAULT_EVENT_CHANCE,
interval: overrides.interval ?? DEFAULT_EVENT_INTERVAL,
cooldown: overrides.cooldown ?? DEFAULT_EVENT_COOLDOWN,
weight: overrides.weight ?? DEFAULT_EVENT_WEIGHT,
};
if (overrides.interrupt !== undefined) {
event.interrupt = overrides.interrupt;
} else {
event.interrupt = DEFAULT_EVENT_INTERRUPT;
}
if (overrides.chatter !== undefined) {
event.chatter = overrides.chatter;
}
result.push(event);
}
return result;
}
/* ------------------------------------------------------------------ */
/* Bubbles and icons */
/* ------------------------------------------------------------------ */
function buildBubbles(
scanned: ScanResult,
overrides: PackerConfig,
encoded: Map<string, EncodedAtlas>,
errors: Array<{ path: string; message: string }>,
): Record<string, BubbleDefinition> {
const result: Record<string, BubbleDefinition> = {};
if (scanned.defaultBubbleAtlasId !== null) {
const atlas = encoded.get(scanned.defaultBubbleAtlasId);
if (atlas !== undefined) {
const packOverrides = overrides.bubbles?.default;
if (packOverrides === undefined) {
errors.push({
path: "bubbles.default",
message: `Default bubble pack has no dimensions in config. Add "bubbles.default" with width and height to character.config.json.`,
});
} else {
const bubble: BubbleDefinition = {
atlas: scanned.defaultBubbleAtlasId,
frames: getAtlasFrameNames(scanned, scanned.defaultBubbleAtlasId),
width: packOverrides.width,
height: packOverrides.height,
};
applyBubbleExtras(bubble, packOverrides);
result.default = bubble;
}
}
}
for (const [packName, pack] of scanned.bubblePacks) {
const atlas = encoded.get(pack.atlasId);
if (atlas === undefined) continue;
const packOverrides = overrides.bubbles?.[packName];
if (packOverrides === undefined) {
errors.push({
path: `bubbles.${packName}`,
message: `Bubble pack "${packName}" has no dimensions in config. Add "bubbles.${packName}" with width and height to character.config.json.`,
});
continue;
}
const bubble: BubbleDefinition = {
atlas: pack.atlasId,
frames: getAtlasFrameNames(scanned, pack.atlasId),
width: packOverrides.width,
height: packOverrides.height,
};
applyBubbleExtras(bubble, packOverrides);
result[packName] = bubble;
}
return result;
}
function applyBubbleExtras(bubble: BubbleDefinition, overrides: BubblePackConfig): void {
if (overrides.framerate !== undefined) bubble.framerate = overrides.framerate;
if (overrides.anchorX !== undefined) bubble.anchorX = overrides.anchorX;
if (overrides.anchorY !== undefined) bubble.anchorY = overrides.anchorY;
if (overrides.frameMode !== undefined) bubble.frameMode = overrides.frameMode;
if (overrides.text !== undefined) bubble.text = overrides.text;
}
function buildIcons(scanned: ScanResult): Record<string, IconDefinition> | undefined {
const result: Record<string, IconDefinition> = {};
let hasAny = false;
// Shared icons → key = icon name (e.g. "heart")
if (scanned.sharedIconAtlasId !== null) {
const atlas = scanned.atlases.get(scanned.sharedIconAtlasId);
if (atlas !== undefined) {
for (const frame of atlas.frames) {
result[frame.name] = {
atlas: scanned.sharedIconAtlasId,
frames: [frame.name],
};
hasAny = true;
}
}
}
// Per-pack icons → key = "<pack>/<icon>" (e.g. "sneeze/sparkle")
for (const [packName, pack] of scanned.bubblePacks) {
if (pack.iconAtlasId === null) continue;
const atlas = scanned.atlases.get(pack.iconAtlasId);
if (atlas === undefined) continue;
for (const frame of atlas.frames) {
result[`${packName}/${frame.name}`] = {
atlas: pack.iconAtlasId,
frames: [frame.name],
};
hasAny = true;
}
}
return hasAny ? result : undefined;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function getAtlasFrameNames(scanned: ScanResult, atlasId: string): string[] {
const atlas = scanned.atlases.get(atlasId);
if (atlas === undefined) return [];
return atlas.frames.map(f => f.name);
}
+173
View File
@@ -0,0 +1,173 @@
import { createHash } from "node:crypto";
import { promises as fs } from "node:fs";
import sharp from "sharp";
import { shortSha256 } from "./hash.js";
import type { PackedAtlas } from "./pack.js";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface EncodeOptions {
/**
* WebP compression effort, 0-6. Higher spends more CPU for smaller
* output. Default 6. Values outside [0, 6] are clamped.
*/
effort?: number;
}
export interface EncodedAtlas {
/** Final WebP file bytes. */
bytes: Buffer;
/**
* SHA-256 of (frame bytes || frame position) for every frame, in
* order. Changes if any frame's pixels or packed position changes.
*/
frameHash: string;
/**
* 8-character SHA-256 of the WebP bytes. Goes into the URL filename.
* Changes if pixels, packing, or encoder output changes.
*/
atlasHash: string;
/** Atlas width in pixels. Matches the WebP file. */
width: number;
/** Atlas height in pixels. Matches the WebP file. */
height: number;
}
export type EncodeOutcome = { ok: true; encoded: EncodedAtlas } | { ok: false; error: string };
export interface EncodeAllResult {
encoded: Map<string, EncodedAtlas>;
errors: Array<{ atlasId: string; message: string }>;
}
/* ------------------------------------------------------------------ */
/* Main entry */
/* ------------------------------------------------------------------ */
export async function encodeAtlas(atlas: PackedAtlas, options: EncodeOptions = {}): Promise<EncodeOutcome> {
try {
const effort = clampEffort(options.effort ?? 6);
// Read every frame's source bytes exactly once. Reused for both
// hashing and compositing, so I/O happens once per frame.
const frameBuffers = await Promise.all(
atlas.frames.map(async frame => {
try {
return await fs.readFile(frame.source.path);
} catch (err) {
throw new Error(
`Failed to read frame "${frame.source.name}" from "${frame.source.path}": ${
err instanceof Error ? err.message : String(err)
}`,
);
}
}),
);
// frameHash: bytes of every frame, interleaved with its packed
// position. Stable across runs if nothing changed.
const frameHasher = createHash("sha256");
for (let i = 0; i < atlas.frames.length; i++) {
const frame = atlas.frames[i]!;
frameHasher.update(frameBuffers[i]!);
frameHasher.update(`|${frame.x},${frame.y},${frame.w},${frame.h}|`);
}
const frameHash = frameHasher.digest("hex");
// Composite every frame onto a transparent canvas at its position.
const composites = atlas.frames.map((frame, i) => ({
input: frameBuffers[i]!,
left: frame.x,
top: frame.y,
}));
const webpBuffer = await sharp({
create: {
width: atlas.width,
height: atlas.height,
channels: 4,
background: { r: 0, g: 0, b: 0, alpha: 0 },
},
})
.composite(composites)
.webp({
lossless: true,
effort,
smartSubsample: false,
alphaQuality: 100,
})
.toBuffer();
const atlasHash = shortSha256(webpBuffer);
return {
ok: true,
encoded: {
bytes: webpBuffer,
frameHash,
atlasHash,
width: atlas.width,
height: atlas.height,
},
};
} catch (err) {
return {
ok: false,
error: err instanceof Error ? err.message : String(err),
};
}
}
export async function encodeAll(
packedAtlases: Map<string, PackedAtlas>,
options: EncodeOptions = {},
): Promise<EncodeAllResult> {
const encoded = new Map<string, EncodedAtlas>();
const errors: Array<{ atlasId: string; message: string }> = [];
for (const [id, atlas] of packedAtlases) {
const outcome = await encodeAtlas(atlas, options);
if (outcome.ok) {
encoded.set(id, outcome.encoded);
} else {
errors.push({ atlasId: id, message: outcome.error });
}
}
return { encoded, errors };
}
export async function computeFrameHash(packed: PackedAtlas): Promise<string> {
const buffers = await Promise.all(
packed.frames.map(async frame => {
try {
return await fs.readFile(frame.source.path);
} catch (err) {
throw new Error(
`Failed to read frame "${frame.source.name}" from "${frame.source.path}": ${
err instanceof Error ? err.message : String(err)
}`,
);
}
}),
);
const hasher = createHash("sha256");
for (let i = 0; i < packed.frames.length; i++) {
const frame = packed.frames[i]!;
hasher.update(buffers[i]!);
hasher.update(`|${frame.x},${frame.y},${frame.w},${frame.h}|`);
}
return hasher.digest("hex");
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function clampEffort(effort: number): number {
if (!Number.isFinite(effort)) return 6;
return Math.max(0, Math.min(6, Math.floor(effort)));
}
+15
View File
@@ -0,0 +1,15 @@
import { createHash } from "node:crypto";
export function sha256(data: Buffer | Uint8Array | string): string {
const h = createHash("sha256");
if (typeof data === "string") {
h.update(data, "utf8");
} else {
h.update(data);
}
return h.digest("hex");
}
export function shortSha256(data: Buffer | Uint8Array | string): string {
return sha256(data).slice(0, 8);
}
+376 -9
View File
@@ -1,26 +1,393 @@
/**
* shimejic-packer — main orchestrator.
*
* Runs the full pipeline: scan → pack → encode (or reuse) → config →
* validate → write. Idempotent: skips encoding for atlases whose source
* frames haven't changed since the last run, based on `frameHash`
* comparison against the previous manifest.
*
* Public API for both the CLI and programmatic callers (CMS, tests).
*/
import { promises as fs } from "node:fs";
import path from "node:path";
import type { CharacterConfig } from "shimejic";
import { generateConfig, type PackerConfig } from "./config-gen.js";
import { computeFrameHash, encodeAtlas, type EncodedAtlas } from "./encode.js";
import { packAll, type PackedAtlas } from "./pack.js";
import { scan } from "./scan.js";
import { validateGeneratedConfig } from "./validate.js";
import {
atlasFileExists,
buildManifest,
cleanupOrphanAtlases,
readManifest,
writeAtlasFile,
writeConfigFile,
writeManifest,
type AtlasManifestEntry,
type Manifest,
} from "./write.js";
export const PACKER_VERSION = "0.1.0";
/* ------------------------------------------------------------------ */
/* Public types */
/* ------------------------------------------------------------------ */
export interface PackOptions {
/** Path to the folder containing character assets. */
input: string;
/** Path where atlases and character.json should be written. */
/** Path where atlases, character.json, and manifest.json are written. */
output: string;
/** Path to overrides JSON. Defaults to `<input>/character.config.json` if present. */
/**
* Path to overrides JSON. If omitted, checks
* `<input>/character.config.json`. If neither exists, uses inferred
* defaults (fine for simple characters, errors for anything requiring
* config like look sectors or bubble dimensions).
*/
config?: string;
/** Max atlas dimension in pixels. Default 2048. */
maxAtlasSize?: number;
/** Report what would be done without writing files. */
/** WebP effort 0-6. Default 6 (max quality). */
effort?: number;
/** Report what would happen without writing files. Default false. */
dryRun?: boolean;
}
export interface AtlasOutcome {
id: string;
/** True if reused from the previous manifest. */
action: "reused" | "encoded";
atlasHash: string;
bytes: number;
}
export interface PackResult {
ok: boolean;
/** Populated on success. */
characterConfig?: unknown;
/** Populated on failure. */
characterConfig?: CharacterConfig;
errors?: Array<{ path: string; message: string }>;
/** Non-fatal issues. */
warnings?: string[];
/** Per-atlas outcome, in the order they were processed. */
atlases?: AtlasOutcome[];
/** Files written during this run. All null/empty on dry-run. */
written?: {
config: string | null;
manifest: string | null;
atlases: string[];
};
/** Atlas files deleted as orphans. */
orphansDeleted?: string[];
}
export async function pack(_options: PackOptions): Promise<PackResult> {
throw new Error("shimejic-packer: not implemented yet");
/* ------------------------------------------------------------------ */
/* Main entry */
/* ------------------------------------------------------------------ */
export async function pack(options: PackOptions): Promise<PackResult> {
const { input, output, config: configPath, maxAtlasSize, effort, dryRun = false } = options;
const errors: Array<{ path: string; message: string }> = [];
const warnings: string[] = [];
const atlasOutcomes: AtlasOutcome[] = [];
const writtenAtlases: string[] = [];
let writtenConfig: string | null = null;
let writtenManifest: string | null = null;
let orphansDeleted: string[] = [];
/* ---------------- 1. Scan ---------------- */
const scanned = await scan(input);
for (const err of scanned.errors) {
errors.push({ path: err.path, message: err.message });
}
warnings.push(...scanned.warnings);
if (errors.length > 0) {
return { ok: false, errors, warnings };
}
/* ---------------- 2. Load overrides ---------------- */
const overrides = await loadOverrides(input, configPath, errors);
if (errors.length > 0) {
return { ok: false, errors, warnings };
}
/* ---------------- 3. Pack ---------------- */
const { packed, errors: packErrors } = packAll(scanned.atlases, {
...(maxAtlasSize !== undefined && { maxSize: maxAtlasSize }),
});
for (const pe of packErrors) {
errors.push({ path: pe.atlasId, message: pe.message });
}
if (errors.length > 0) {
return { ok: false, errors, warnings };
}
/* ---------------- 4. Read previous manifest ---------------- */
const prevManifest = await readManifest(output);
/* ---------------- 5. Encode or reuse ---------------- */
const encoded = new Map<string, EncodedAtlas>();
for (const [id, packedAtlas] of packed) {
const outcome = await encodeOrReuse(id, packedAtlas, prevManifest, output, effort);
if (!outcome.ok) {
errors.push({ path: id, message: outcome.error });
continue;
}
encoded.set(id, outcome.encoded);
atlasOutcomes.push({
id,
action: outcome.reused ? "reused" : "encoded",
atlasHash: outcome.encoded.atlasHash,
bytes: outcome.encoded.bytes.length,
});
}
if (errors.length > 0) {
return { ok: false, errors, warnings };
}
/* ---------------- 6. Generate config ---------------- */
const fallbackId = path.basename(path.resolve(input));
const configGen = generateConfig({
scanned,
encoded,
overrides,
fallbackId,
});
warnings.push(...configGen.warnings);
errors.push(...configGen.errors);
if (configGen.config === null) {
return { ok: false, errors, warnings };
}
/* ---------------- 7. Validate ---------------- */
const validation = validateGeneratedConfig(configGen.config);
if (!validation.ok) {
for (const verr of validation.errors) {
errors.push({ path: verr.path, message: verr.message });
}
return { ok: false, errors, warnings };
}
/* ---------------- 8. Write (unless dry-run) ---------------- */
if (dryRun) {
return {
ok: true,
characterConfig: configGen.config,
warnings,
atlases: atlasOutcomes,
written: { config: null, manifest: null, atlases: [] },
orphansDeleted: [],
};
}
// Write newly-encoded atlases (skip reused ones — their files exist)
for (const [id, enc] of encoded) {
const outcome = atlasOutcomes.find(a => a.id === id);
if (outcome?.action === "reused") continue;
try {
const written = await writeAtlasFile(output, id, enc.atlasHash, enc.bytes);
writtenAtlases.push(written);
} catch (err) {
errors.push({
path: id,
message: `Failed to write atlas: ${err instanceof Error ? err.message : String(err)}`,
});
}
}
if (errors.length > 0) {
return { ok: false, errors, warnings };
}
// Write character.json
try {
writtenConfig = await writeConfigFile(output, configGen.config);
} catch (err) {
errors.push({
path: output,
message: `Failed to write character.json: ${err instanceof Error ? err.message : String(err)}`,
});
return { ok: false, errors, warnings };
}
// Cleanup orphan atlases
orphansDeleted = await cleanupOrphanAtlases(output, configGen.config);
if (orphansDeleted.length > 0) {
warnings.push(
`Cleaned up ${orphansDeleted.length} orphaned atlas file${orphansDeleted.length === 1 ? "" : "s"}.`,
);
}
// Write manifest — only after atlases and config are on disk
const frameCounts = new Map<string, number>();
for (const [id, packedAtlas] of packed) {
frameCounts.set(id, packedAtlas.frames.length);
}
const manifest = buildManifest(configGen.config.id, PACKER_VERSION, encoded, frameCounts);
try {
writtenManifest = await writeManifest(output, manifest);
} catch (err) {
// Manifest failure is non-fatal — next run re-encodes everything.
warnings.push(`Failed to write manifest: ${err instanceof Error ? err.message : String(err)}`);
}
return {
ok: true,
characterConfig: configGen.config,
warnings,
atlases: atlasOutcomes,
written: {
config: writtenConfig,
manifest: writtenManifest,
atlases: writtenAtlases,
},
orphansDeleted,
};
}
/* ------------------------------------------------------------------ */
/* Encode or reuse */
/* ------------------------------------------------------------------ */
interface EncodeReuseOk {
ok: true;
encoded: EncodedAtlas;
reused: boolean;
}
interface EncodeReuseErr {
ok: false;
error: string;
}
async function encodeOrReuse(
atlasId: string,
packed: PackedAtlas,
prevManifest: Manifest | null,
outputDir: string,
effort: number | undefined,
): Promise<EncodeReuseOk | EncodeReuseErr> {
// Attempt reuse first
if (prevManifest !== null) {
const prev = prevManifest.atlases[atlasId];
if (prev !== undefined) {
let frameHash: string;
try {
frameHash = await computeFrameHash(packed);
} catch (err) {
return {
ok: false,
error: err instanceof Error ? err.message : String(err),
};
}
if (prev.frameHash === frameHash) {
const fileExists = await atlasFileExists(outputDir, atlasId, prev.atlasHash);
if (fileExists) {
return {
ok: true,
encoded: makeReusedAtlas(prev),
reused: true,
};
}
// Manifest says unchanged, but the file is missing. Fall through to encode.
}
}
}
// Encode fresh
const outcome = await encodeAtlas(packed, {
...(effort !== undefined && { effort }),
});
if (!outcome.ok) {
return { ok: false, error: outcome.error };
}
return { ok: true, encoded: outcome.encoded, reused: false };
}
function makeReusedAtlas(prev: AtlasManifestEntry): EncodedAtlas {
return {
// Empty buffer — reused atlases aren't rewritten, so bytes are unused.
bytes: Buffer.alloc(0),
frameHash: prev.frameHash,
atlasHash: prev.atlasHash,
width: prev.width,
height: prev.height,
};
}
/* ------------------------------------------------------------------ */
/* Overrides loading */
/* ------------------------------------------------------------------ */
async function loadOverrides(
input: string,
explicitPath: string | undefined,
errors: Array<{ path: string; message: string }>,
): Promise<PackerConfig | null> {
let configPath: string | null = null;
if (explicitPath !== undefined) {
configPath = explicitPath;
} else {
const defaultPath = path.join(input, "character.config.json");
if (await fileExists(defaultPath)) {
configPath = defaultPath;
}
}
if (configPath === null) return null;
let content: string;
try {
content = await fs.readFile(configPath, "utf8");
} catch (err) {
errors.push({
path: configPath,
message: `Failed to read config file: ${err instanceof Error ? err.message : String(err)}`,
});
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(content);
} catch (err) {
errors.push({
path: configPath,
message: `Config is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
});
return null;
}
if (typeof parsed !== "object" || parsed === null) {
errors.push({
path: configPath,
message: "Config must be a JSON object.",
});
return null;
}
return parsed as PackerConfig;
}
async function fileExists(p: string): Promise<boolean> {
try {
await fs.access(p);
return true;
} catch {
return false;
}
}
+165
View File
@@ -0,0 +1,165 @@
/**
* pack.ts — lay out a scanned atlas into a uniform grid.
*
* Given N frames of size W×H, the packer produces the smallest square-ish
* grid that holds them:
*
* cols = ceil(sqrt(N))
* rows = ceil(N / cols)
* atlas width = cols × W
* atlas height = rows × H
*
* Each frame i lands at cell (i % cols, floor(i / cols)):
*
* ┌──────┬──────┬──────┐
* │ 0 │ 1 │ 2 │
* ├──────┼──────┼──────┤
* │ 3 │ 4 │ 5 │
* └──────┴──────┴──────┘
*
* No padding between cells. Pixel-art rendering samples each cell exactly,
* so adjacent frame pixels can't bleed into each other. Trim (v1.5) will
* replace the uniform grid with MaxRects packing and per-frame regions.
*
* The packer does not touch the filesystem. It reads from `ScannedAtlas`
* and returns positions. Encoding and writing are separate concerns.
*/
import type { FrameSource, ScannedAtlas } from "./scan.js";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface PackedFrame {
/** Original frame reference, carrying source path and dimensions. */
source: FrameSource;
/** Top-left X in the atlas, in pixels. */
x: number;
/** Top-left Y in the atlas, in pixels. */
y: number;
/** Frame width. Same for every frame in the atlas. */
w: number;
/** Frame height. Same for every frame in the atlas. */
h: number;
}
export interface PackedAtlas {
/** Source scanner result this atlas was derived from. */
source: ScannedAtlas;
/** Final atlas width in pixels. */
width: number;
/** Final atlas height in pixels. */
height: number;
/** Number of columns in the grid. */
cols: number;
/** Number of rows in the grid. */
rows: number;
/** Frames in their assigned cells, in original frame order. */
frames: PackedFrame[];
}
export interface PackOptions {
/**
* Max allowed atlas dimension in pixels. If the computed atlas would
* exceed this, the packer returns an error naming the atlas. Default 2048.
*/
maxSize?: number;
}
export type PackOutcome = { ok: true; atlas: PackedAtlas } | { ok: false; error: string };
/* ------------------------------------------------------------------ */
/* Main entry */
/* ------------------------------------------------------------------ */
export function packAtlas(scanned: ScannedAtlas, options: PackOptions = {}): PackOutcome {
const maxSize = options.maxSize ?? 2048;
if (scanned.frames.length === 0) {
return {
ok: false,
error: `Atlas "${scanned.id}" has no frames to pack.`,
};
}
const frameW = scanned.width;
const frameH = scanned.height;
if (frameW <= 0 || frameH <= 0) {
return {
ok: false,
error: `Atlas "${scanned.id}" has invalid frame dimensions: ${frameW}×${frameH}.`,
};
}
const n = scanned.frames.length;
const cols = Math.ceil(Math.sqrt(n));
const rows = Math.ceil(n / cols);
const atlasW = cols * frameW;
const atlasH = rows * frameH;
if (atlasW > maxSize || atlasH > maxSize) {
const suggestion =
atlasW > maxSize && atlasH > maxSize
? "Split the atlas into smaller folders, or increase --max-atlas-size."
: atlasW > maxSize
? "Split the atlas into smaller folders, or increase --max-atlas-size."
: "Split the atlas into smaller folders, or increase --max-atlas-size.";
return {
ok: false,
error: `Atlas "${scanned.id}" would be ${atlasW}×${atlasH}, exceeding max size ${maxSize}. ${suggestion}`,
};
}
const frames: PackedFrame[] = scanned.frames.map((frame, i) => {
const col = i % cols;
const row = Math.floor(i / cols);
return {
source: frame,
x: col * frameW,
y: row * frameH,
w: frameW,
h: frameH,
};
});
return {
ok: true,
atlas: {
source: scanned,
width: atlasW,
height: atlasH,
cols,
rows,
frames,
},
};
}
/**
* Pack every atlas from a scanner result. Returns two maps: the packed
* atlases that succeeded, and per-atlas errors that failed. Callers
* accumulate errors into the overall error list before reporting.
*/
export interface PackAllResult {
packed: Map<string, PackedAtlas>;
errors: Array<{ atlasId: string; message: string }>;
}
export function packAll(scannedAtlases: Map<string, ScannedAtlas>, options: PackOptions = {}): PackAllResult {
const packed = new Map<string, PackedAtlas>();
const errors: Array<{ atlasId: string; message: string }> = [];
for (const [id, atlas] of scannedAtlases) {
const outcome = packAtlas(atlas, options);
if (outcome.ok) {
packed.set(id, outcome.atlas);
} else {
errors.push({ atlasId: id, message: outcome.error });
}
}
return { packed, errors };
}
+702
View File
@@ -0,0 +1,702 @@
/**
* scan.ts — walk the input folder and produce a structured inventory of
* every atlas, state, bubble pack, and icon that the input tree defines.
*
* Does not modify the filesystem, does not encode anything, does not
* write output. Only reads.
*
* Validation policy: all errors and warnings are accumulated into the
* returned result. The function itself never throws on validation
* failures. Callers inspect `result.errors` and decide whether to
* proceed (empty means ready to pack).
*
* Expected input structure:
*
* <input>/
* ├── states/ required
* │ ├── <state>/ at least one
* │ │ ├── <n>.png base frames
* │ │ ├── look/ optional
* │ │ │ └── <sector>/ look sector
* │ │ │ └── <n>.png
* │ │ └── event/ optional
* │ │ └── <event>/ event clip
* │ │ └── <n>.png
* │ └── ...
* └── bubbles/ optional
* ├── <n>.png default bubble (loose frames)
* ├── _icons/ shared icons
* │ └── <name>.png
* └── <pack>/ named bubble pack
* ├── <n>.png
* └── icons/ optional per-pack icons
* └── <name>.png
*
* Frame naming: every state/bubble frame filename must contain a number
* (Reading B — gaps allowed, zero-start not required). Frames within one
* folder must share dimensions. Icon filenames are the icon identifiers;
* no number required.
*/
import { promises as fs, type Dirent } from "node:fs";
import path from "node:path";
import type { Metadata } from "sharp";
import sharp from "sharp";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface FrameSource {
/** Original filename of the source PNG. For state frames, this is
* the raw filename from disk. For icon frames, this is the icon
* identifier (filename without `.png`). */
name: string;
/** Absolute path on disk. */
path: string;
/** Numeric order extracted from the filename. Used for sorting.
* Zero for icons (sorting uses `name` instead). */
order: number;
/** Source image width in pixels. */
width: number;
/** Source image height in pixels. */
height: number;
}
export interface ScannedAtlas {
/** Atlas identifier, e.g. `state_idle` or `bubbles_icons`. */
id: string;
/** Source folder that produced this atlas. */
sourcePath: string;
/** Frames in final sorted order. */
frames: FrameSource[];
/** Frame width. All frames are guaranteed equal (validated). */
width: number;
/** Frame height. All frames are guaranteed equal (validated). */
height: number;
}
export interface ScannedState {
name: string;
/** Atlas ID of the base clip. */
baseAtlasId: string;
/** Sector folder name → atlas ID. */
lookSectors: Map<string, string>;
/** Event name → atlas ID. */
events: Map<string, string>;
}
export interface ScannedBubblePack {
name: string;
/** Atlas ID of the bubble frames. */
atlasId: string;
/** Per-pack icon atlas ID, or null if no `icons/` folder exists. */
iconAtlasId: string | null;
}
export interface ScanError {
/** Path (file or folder) that produced the error. */
path: string;
/** Human-readable description. */
message: string;
}
export interface ScanResult {
/** Every atlas discovered, keyed by atlas ID. */
atlases: Map<string, ScannedAtlas>;
/** State definitions, keyed by state name. */
states: Map<string, ScannedState>;
/** Default bubble atlas ID (from loose PNGs in `bubbles/`), or null. */
defaultBubbleAtlasId: string | null;
/** Shared icons atlas ID (from `bubbles/_icons/`), or null. */
sharedIconAtlasId: string | null;
/** Named bubble packs, keyed by pack name. */
bubblePacks: Map<string, ScannedBubblePack>;
/** Non-fatal issues (e.g. folder name normalization). */
warnings: string[];
/** Fatal issues. If non-empty, the caller must not proceed. */
errors: ScanError[];
}
/* ------------------------------------------------------------------ */
/* Main entry */
/* ------------------------------------------------------------------ */
export async function scan(inputDir: string): Promise<ScanResult> {
const result: ScanResult = {
atlases: new Map(),
states: new Map(),
defaultBubbleAtlasId: null,
sharedIconAtlasId: null,
bubblePacks: new Map(),
warnings: [],
errors: [],
};
const stat = await tryStat(inputDir);
if (stat === null) {
result.errors.push({
path: inputDir,
message: "Input folder does not exist.",
});
return result;
}
if (!stat.isDirectory()) {
result.errors.push({
path: inputDir,
message: "Input must be a directory.",
});
return result;
}
const statesDir = path.join(inputDir, "states");
if (await dirExists(statesDir)) {
await scanStates(statesDir, result);
} else {
result.errors.push({
path: statesDir,
message: 'Missing required "states/" folder inside input.',
});
}
const bubblesDir = path.join(inputDir, "bubbles");
if (await dirExists(bubblesDir)) {
await scanBubbles(bubblesDir, result);
}
return result;
}
/* ------------------------------------------------------------------ */
/* Filesystem helpers */
/* ------------------------------------------------------------------ */
async function tryStat(p: string): Promise<Awaited<ReturnType<typeof fs.stat>> | null> {
try {
return await fs.stat(p);
} catch {
return null;
}
}
async function dirExists(p: string): Promise<boolean> {
const stat = await tryStat(p);
return stat !== null && stat.isDirectory();
}
async function readDir(dir: string): Promise<Dirent[]> {
try {
return await fs.readdir(dir, { withFileTypes: true });
} catch {
return [];
}
}
function isPngFile(name: string): boolean {
return name.toLowerCase().endsWith(".png");
}
function isIgnoredFile(name: string): boolean {
if (name.startsWith(".")) return true;
const systemFiles = ["Thumbs.db", "desktop.ini"];
return systemFiles.includes(name);
}
/**
* Extract the first numeric run from a filename. Returns null if no
* digits present. Used for ordering frames within a folder.
*/
function extractOrder(filename: string): number | null {
const match = filename.match(/(\d+)/);
if (!match) return null;
const num = parseInt(match[1]!, 10);
return Number.isFinite(num) ? num : null;
}
/**
* Normalize a folder name to lowercase, emitting a warning if the
* original had uppercase. The normalized form is what the packer uses
* for atlas IDs and state names.
*/
function normalizeFolderName(name: string, fullPath: string, result: ScanResult): string {
const lower = name.toLowerCase();
if (name !== lower) {
result.warnings.push(`Folder "${fullPath}" has non-lowercase name "${name}". Normalized to "${lower}".`);
}
return lower;
}
/* ------------------------------------------------------------------ */
/* Frame reading */
/* ------------------------------------------------------------------ */
/**
* Read a single PNG file and produce a FrameSource. Returns null on
* error (error is recorded in result).
*/
async function readFrame(filePath: string, filename: string, result: ScanResult): Promise<FrameSource | null> {
if (!isPngFile(filename)) {
result.errors.push({
path: filePath,
message: `Unsupported file format: "${filename}". Only .png files are supported.`,
});
return null;
}
const order = extractOrder(filename);
if (order === null) {
result.errors.push({
path: filePath,
message: `Frame filename must contain a number: "${filename}".`,
});
return null;
}
let metadata: Metadata;
try {
metadata = await sharp(filePath).metadata();
} catch (err) {
result.errors.push({
path: filePath,
message: `Failed to read image: ${err instanceof Error ? err.message : String(err)}`,
});
return null;
}
if (!metadata.width || !metadata.height) {
result.errors.push({
path: filePath,
message: `Could not determine image dimensions: "${filename}".`,
});
return null;
}
return {
name: filename,
path: filePath,
order,
width: metadata.width,
height: metadata.height,
};
}
/**
* Read a specific icon file (no number requirement). The icon's semantic
* name is the filename without extension.
*/
async function readIcon(filePath: string, filename: string, result: ScanResult): Promise<FrameSource | null> {
if (!isPngFile(filename)) {
result.errors.push({
path: filePath,
message: `Unsupported file format: "${filename}". Icons must be .png files.`,
});
return null;
}
let metadata: Metadata;
try {
metadata = await sharp(filePath).metadata();
} catch (err) {
result.errors.push({
path: filePath,
message: `Failed to read image: ${err instanceof Error ? err.message : String(err)}`,
});
return null;
}
if (!metadata.width || !metadata.height) {
result.errors.push({
path: filePath,
message: `Could not determine image dimensions: "${filename}".`,
});
return null;
}
const iconName = filename.replace(/\.png$/i, "");
return {
name: iconName,
path: filePath,
order: 0,
width: metadata.width,
height: metadata.height,
};
}
async function readFramesFromDir(dir: string, result: ScanResult): Promise<FrameSource[]> {
const entries = await readDir(dir);
const frames: FrameSource[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
if (isIgnoredFile(entry.name)) continue;
const frame = await readFrame(path.join(dir, entry.name), entry.name, result);
if (frame) frames.push(frame);
}
return frames;
}
/* ------------------------------------------------------------------ */
/* Atlas validation */
/* ------------------------------------------------------------------ */
/**
* Validate a group of frames destined for one atlas. Checks duplicate
* orders, dimension consistency. Sorts and returns the atlas. Returns
* `error: true` if any validation failed — the caller should not add
* this atlas to the result.
*/
function makeAtlas(
id: string,
sourcePath: string,
frames: FrameSource[],
result: ScanResult,
): { atlas: ScannedAtlas; error: boolean } {
let hasError = false;
// Duplicate orders
const seen = new Map<number, string>();
for (const frame of frames) {
const existing = seen.get(frame.order);
if (existing !== undefined) {
result.errors.push({
path: sourcePath,
message: `Duplicate frame number ${frame.order} in "${existing}" and "${frame.name}".`,
});
hasError = true;
}
seen.set(frame.order, frame.name);
}
// Size consistency
if (frames.length > 0) {
const first = frames[0]!;
for (const frame of frames.slice(1)) {
if (frame.width !== first.width || frame.height !== first.height) {
result.errors.push({
path: frame.path,
message: `Frame size ${frame.width}×${frame.height} differs from ${first.width}x${first.height} (from "${first.name}"). All frames in "${sourcePath}" must be the same size.`,
});
hasError = true;
}
}
}
frames.sort((a, b) => a.order - b.order);
return {
atlas: {
id,
sourcePath,
frames,
width: frames[0]?.width ?? 0,
height: frames[0]?.height ?? 0,
},
error: hasError,
};
}
/* ------------------------------------------------------------------ */
/* States */
/* ------------------------------------------------------------------ */
async function scanStates(statesDir: string, result: ScanResult): Promise<void> {
const entries = await readDir(statesDir);
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const fullPath = path.join(statesDir, entry.name);
const stateName = normalizeFolderName(entry.name, fullPath, result);
await scanState(fullPath, stateName, result);
}
}
async function scanState(stateDir: string, stateName: string, result: ScanResult): Promise<void> {
const state: ScannedState = {
name: stateName,
baseAtlasId: "",
lookSectors: new Map(),
events: new Map(),
};
const entries = await readDir(stateDir);
const baseFrames: FrameSource[] = [];
for (const entry of entries) {
if (entry.isFile() && !isIgnoredFile(entry.name)) {
const frame = await readFrame(path.join(stateDir, entry.name), entry.name, result);
if (frame) baseFrames.push(frame);
}
}
if (baseFrames.length === 0) {
result.errors.push({
path: stateDir,
message: `State "${stateName}" has no base frames. Every state folder must contain at least one .png.`,
});
return;
}
const atlasId = `state_${stateName}`;
const { atlas, error } = makeAtlas(atlasId, stateDir, baseFrames, result);
if (error) return;
result.atlases.set(atlas.id, atlas);
state.baseAtlasId = atlas.id;
const lookDir = path.join(stateDir, "look");
if (await dirExists(lookDir)) {
await scanLookSectors(lookDir, stateName, state, baseFrames.length, result);
}
const eventDir = path.join(stateDir, "event");
if (await dirExists(eventDir)) {
await scanEvents(eventDir, stateName, state, result);
}
result.states.set(stateName, state);
}
async function scanLookSectors(
lookDir: string,
stateName: string,
state: ScannedState,
baseFrameCount: number,
result: ScanResult,
): Promise<void> {
const entries = await readDir(lookDir);
let foundAnySector = false;
for (const entry of entries) {
if (!entry.isDirectory()) continue;
foundAnySector = true;
const sectorDir = path.join(lookDir, entry.name);
const sectorName = normalizeFolderName(entry.name, sectorDir, result);
const frames = await readFramesFromDir(sectorDir, result);
if (frames.length === 0) {
result.errors.push({
path: sectorDir,
message: `Look sector "${sectorName}" (state "${stateName}") has no frames.`,
});
continue;
}
if (frames.length !== baseFrameCount) {
result.errors.push({
path: sectorDir,
message: `Look sector "${sectorName}" (state "${stateName}") has ${frames.length} frames, but base has ${baseFrameCount}. Frame counts must match.`,
});
continue;
}
const atlasId = `state_${stateName}_look_${sectorName}`;
const { atlas, error } = makeAtlas(atlasId, sectorDir, frames, result);
if (error) continue;
result.atlases.set(atlas.id, atlas);
state.lookSectors.set(sectorName, atlas.id);
}
if (!foundAnySector) {
result.errors.push({
path: lookDir,
message: `Empty "look/" folder in state "${stateName}". Remove the folder or add sector subfolders.`,
});
}
}
async function scanEvents(eventDir: string, stateName: string, state: ScannedState, result: ScanResult): Promise<void> {
const entries = await readDir(eventDir);
let foundAnyEvent = false;
for (const entry of entries) {
if (!entry.isDirectory()) continue;
foundAnyEvent = true;
const eventClipDir = path.join(eventDir, entry.name);
const eventName = normalizeFolderName(entry.name, eventClipDir, result);
const frames = await readFramesFromDir(eventClipDir, result);
if (frames.length === 0) {
result.errors.push({
path: eventClipDir,
message: `Event "${eventName}" (state "${stateName}") has no frames.`,
});
continue;
}
const atlasId = `state_${stateName}_event_${eventName}`;
const { atlas, error } = makeAtlas(atlasId, eventClipDir, frames, result);
if (error) continue;
result.atlases.set(atlas.id, atlas);
state.events.set(eventName, atlas.id);
}
if (!foundAnyEvent) {
result.errors.push({
path: eventDir,
message: `Empty "event/" folder in state "${stateName}". Remove the folder or add event subfolders.`,
});
}
}
/* ------------------------------------------------------------------ */
/* Bubbles and icons */
/* ------------------------------------------------------------------ */
async function scanBubbles(bubblesDir: string, result: ScanResult): Promise<void> {
const entries = await readDir(bubblesDir);
const looseFrames: FrameSource[] = [];
for (const entry of entries) {
if (entry.isFile()) {
if (isIgnoredFile(entry.name)) continue;
const frame = await readFrame(path.join(bubblesDir, entry.name), entry.name, result);
if (frame) looseFrames.push(frame);
} else if (entry.isDirectory()) {
const subDir = path.join(bubblesDir, entry.name);
const lowerName = normalizeFolderName(entry.name, subDir, result);
if (lowerName === "_icons") {
await scanIconFolder(subDir, "bubbles_icons", result, true);
} else {
await scanBubblePack(subDir, lowerName, result);
}
}
}
if (looseFrames.length > 0) {
const { atlas, error } = makeAtlas("bubbles", bubblesDir, looseFrames, result);
if (!error) {
result.atlases.set(atlas.id, atlas);
result.defaultBubbleAtlasId = atlas.id;
}
}
}
async function scanBubblePack(packDir: string, packName: string, result: ScanResult): Promise<void> {
const entries = await readDir(packDir);
const frames: FrameSource[] = [];
let iconAtlasId: string | null = null;
for (const entry of entries) {
if (entry.isFile()) {
if (isIgnoredFile(entry.name)) continue;
const frame = await readFrame(path.join(packDir, entry.name), entry.name, result);
if (frame) frames.push(frame);
} else if (entry.isDirectory()) {
const subDir = path.join(packDir, entry.name);
const subName = entry.name.toLowerCase();
if (subName === "icons") {
const iconAtlas = `bubbles_${packName}_icons`;
const id = await scanIconFolder(subDir, iconAtlas, result, false);
if (id !== null) iconAtlasId = id;
} else {
result.errors.push({
path: subDir,
message: `Unexpected subfolder in bubble pack "${packName}": "${entry.name}". Only "icons/" is allowed.`,
});
}
}
}
if (frames.length === 0) {
result.errors.push({
path: packDir,
message: `Bubble pack "${packName}" has no frames.`,
});
return;
}
const atlasId = `bubbles_${packName}`;
const { atlas, error } = makeAtlas(atlasId, packDir, frames, result);
if (error) return;
result.atlases.set(atlas.id, atlas);
result.bubblePacks.set(packName, {
name: packName,
atlasId: atlas.id,
iconAtlasId,
});
}
/**
* Read an icon folder. Icons don't require numbers — filename (without
* .png) is the icon's semantic identifier. All icons in one folder must
* be the same size.
*
* If `isSharedIcons` is true, records the atlas as the shared icon
* atlas on the result. Otherwise returns the atlas ID for the caller
* to associate with a bubble pack.
*/
async function scanIconFolder(
iconsDir: string,
atlasId: string,
result: ScanResult,
isSharedIcons: boolean,
): Promise<string | null> {
const entries = await readDir(iconsDir);
const frames: FrameSource[] = [];
for (const entry of entries) {
if (entry.isDirectory()) {
result.errors.push({
path: path.join(iconsDir, entry.name),
message: `Unexpected subfolder in icon folder: "${entry.name}". Icons must be PNG files directly in the folder.`,
});
continue;
}
if (isIgnoredFile(entry.name)) continue;
const frame = await readIcon(path.join(iconsDir, entry.name), entry.name, result);
if (frame) frames.push(frame);
}
if (frames.length === 0) {
result.errors.push({
path: iconsDir,
message: `Empty icon folder. Remove it or add icon .png files.`,
});
return null;
}
// Case-insensitive icon name collision check
const seen = new Map<string, string>();
for (const frame of frames) {
const key = frame.name.toLowerCase();
const existing = seen.get(key);
if (existing !== undefined) {
result.errors.push({
path: frame.path,
message: `Duplicate icon name "${frame.name}" collides with "${existing}".`,
});
}
seen.set(key, frame.name);
}
// Size consistency
const first = frames[0]!;
for (const frame of frames.slice(1)) {
if (frame.width !== first.width || frame.height !== first.height) {
result.errors.push({
path: frame.path,
message: `Icon size ${frame.width}×${frame.height} differs from ${first.width}*${first.height}. All icons in this folder must be the same size.`,
});
}
}
// Icons sort alphabetically by name
frames.sort((a, b) => a.name.localeCompare(b.name));
const atlas: ScannedAtlas = {
id: atlasId,
sourcePath: iconsDir,
frames,
width: first.width,
height: first.height,
};
result.atlases.set(atlas.id, atlas);
if (isSharedIcons) {
result.sharedIconAtlasId = atlas.id;
}
return atlas.id;
}
@@ -0,0 +1,175 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";
import { runCli } from "../cli.js";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
let tmpDir: string;
let inputDir: string;
let outputDir: string;
let logSpy: MockInstance<typeof vi.spyOn>;
let warnSpy: MockInstance<typeof vi.spyOn>;
let errorSpy: MockInstance<typeof vi.spyOn>;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-test-"));
inputDir = path.join(tmpDir, "input");
outputDir = path.join(tmpDir, "output");
await fs.mkdir(inputDir, { recursive: true });
logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(async () => {
logSpy.mockRestore();
warnSpy.mockRestore();
errorSpy.mockRestore();
await fs.rm(tmpDir, { recursive: true, force: true });
});
async function makePng(relativePath: string, width = 16, height = 16): Promise<void> {
const filePath = path.join(inputDir, relativePath);
await fs.mkdir(path.dirname(filePath), { recursive: true });
const buffer = await sharp({
create: {
width,
height,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 1 },
},
})
.png()
.toBuffer();
await fs.writeFile(filePath, buffer);
}
async function fileExists(p: string): Promise<boolean> {
try {
await fs.access(p);
return true;
} catch {
return false;
}
}
/* ------------------------------------------------------------------ */
/* Argument validation */
/* ------------------------------------------------------------------ */
describe("runCli — argument validation", () => {
it("returns 1 when no input argument", async () => {
const code = await runCli([]);
expect(code).toBe(1);
});
it("returns 1 on invalid --max-atlas-size", async () => {
await makePng("states/idle/0.png");
const code = await runCli([inputDir, "-o", outputDir, "--max-atlas-size", "not-a-number"]);
expect(code).toBe(1);
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Invalid --max-atlas-size"));
});
it("returns 1 on invalid --effort", async () => {
await makePng("states/idle/0.png");
const code = await runCli([inputDir, "-o", outputDir, "--effort", "99"]);
expect(code).toBe(1);
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Invalid --effort"));
});
});
/* ------------------------------------------------------------------ */
/* Successful runs */
/* ------------------------------------------------------------------ */
describe("runCli — success", () => {
it("returns 0 for valid input", async () => {
await makePng("states/idle/0.png");
const code = await runCli([inputDir, "-o", outputDir]);
expect(code).toBe(0);
});
it("writes character.json", async () => {
await makePng("states/idle/0.png");
await runCli([inputDir, "-o", outputDir]);
expect(await fileExists(path.join(outputDir, "character.json"))).toBe(true);
});
it("prints atlas count", async () => {
await makePng("states/idle/0.png");
await runCli([inputDir, "-o", outputDir]);
const calls = logSpy.mock.calls.map(c => String(c[0]));
expect(calls.some(l => l.includes("1 atlases"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Dry-run */
/* ------------------------------------------------------------------ */
describe("runCli — dry-run", () => {
it("does not write files", async () => {
await makePng("states/idle/0.png");
await runCli([inputDir, "-o", outputDir, "--dry-run"]);
expect(await fileExists(path.join(outputDir, "character.json"))).toBe(false);
});
it("prefixes output with [dry-run]", async () => {
await makePng("states/idle/0.png");
await runCli([inputDir, "-o", outputDir, "--dry-run"]);
const calls = logSpy.mock.calls.map(c => String(c[0]));
expect(calls.some(l => l.startsWith("[dry-run]"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Verbose */
/* ------------------------------------------------------------------ */
describe("runCli — verbose", () => {
it("prints per-atlas lines", async () => {
await makePng("states/idle/0.png");
await runCli([inputDir, "-o", outputDir, "--verbose"]);
const calls = logSpy.mock.calls.map(c => String(c[0]));
expect(calls.some(l => l.includes("state_idle"))).toBe(true);
expect(calls.some(l => l.includes("encoded"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Error cases */
/* ------------------------------------------------------------------ */
describe("runCli — errors", () => {
it("returns 1 on missing input directory", async () => {
const code = await runCli([path.join(tmpDir, "nope"), "-o", outputDir]);
expect(code).toBe(1);
});
it("prints errors to stderr", async () => {
const code = await runCli([path.join(tmpDir, "nope"), "-o", outputDir]);
expect(code).toBe(1);
expect(errorSpy).toHaveBeenCalled();
});
});
/* ------------------------------------------------------------------ */
/* Idempotency behavior visible from CLI */
/* ------------------------------------------------------------------ */
describe("runCli — idempotency", () => {
it("reports reused on second run", async () => {
await makePng("states/idle/0.png");
await runCli([inputDir, "-o", outputDir]);
logSpy.mockClear();
await runCli([inputDir, "-o", outputDir]);
const calls = logSpy.mock.calls.map(c => String(c[0]));
expect(calls.some(l => l.includes("0 encoded, 1 reused"))).toBe(true);
});
});
@@ -0,0 +1,860 @@
import { describe, expect, it } from "vitest";
import { generateConfig } from "../config-gen.js";
import type { EncodedAtlas } from "../encode.js";
import type { ScanResult, ScannedAtlas, ScannedBubblePack, ScannedState } from "../scan.js";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
function makeScannedAtlas(id: string, frameNames: string[], w = 16, h = 16): ScannedAtlas {
return {
id,
sourcePath: `/fake/${id}`,
frames: frameNames.map((name, i) => ({
name,
path: `/fake/${id}/${name}`,
order: i,
width: w,
height: h,
})),
width: w,
height: h,
};
}
function makeEncoded(hash = "abcdef12", w = 16, h = 16): EncodedAtlas {
return {
bytes: Buffer.alloc(0),
frameHash: "f".repeat(64),
atlasHash: hash,
width: w,
height: h,
};
}
function makeScanned(overrides: Partial<ScanResult> = {}): ScanResult {
return {
atlases: new Map(),
states: new Map(),
defaultBubbleAtlasId: null,
sharedIconAtlasId: null,
bubblePacks: new Map(),
warnings: [],
errors: [],
...overrides,
};
}
function simpleState(name: string, baseAtlasId: string): ScannedState {
return {
name,
baseAtlasId,
lookSectors: new Map(),
events: new Map(),
};
}
/* ------------------------------------------------------------------ */
/* Basic config generation */
/* ------------------------------------------------------------------ */
describe("generateConfig — basic", () => {
it("generates a config for a single-state character with no overrides", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png", "1.png"])]]),
});
const encoded = new Map([["state_idle", makeEncoded("abc12345")]]);
const result = generateConfig({
scanned,
encoded,
overrides: null,
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
expect(result.config).not.toBeNull();
expect(result.config?.id).toBe("cat");
expect(result.config?.initialState).toBe("idle");
expect(result.config?.atlases.state_idle?.url).toBe("atlases/state_idle.abc12345.webp");
expect(result.config?.states.idle?.base.frames).toEqual(["0.png", "1.png"]);
expect(result.config?.states.idle?.base.framerate).toBe(8);
expect(result.config?.states.idle?.base.loop).toBe(true);
});
it("uses overrides.id when provided", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png"])]]),
});
const result = generateConfig({
scanned,
encoded: new Map([["state_idle", makeEncoded()]]),
overrides: { id: "my-cat" },
fallbackId: "cat",
});
expect(result.config?.id).toBe("my-cat");
});
it("warns when initialState is defaulted", () => {
const scanned = makeScanned({
states: new Map([
["walk", simpleState("walk", "state_walk")],
["idle", simpleState("idle", "state_idle")],
]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_walk", makeScannedAtlas("state_walk", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_walk", makeEncoded("def67890")],
]),
overrides: null,
fallbackId: "cat",
});
expect(result.config?.initialState).toBe("idle");
expect(result.warnings.some(w => w.includes("initialState defaulted"))).toBe(true);
});
it("errors when overrides.initialState is unknown", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png"])]]),
});
const result = generateConfig({
scanned,
encoded: new Map([["state_idle", makeEncoded()]]),
overrides: { initialState: "nonexistent" },
fallbackId: "cat",
});
expect(result.errors.some(e => e.path === "initialState")).toBe(true);
expect(result.config).toBeNull();
});
it("accepts valid spawnState", () => {
const scanned = makeScanned({
states: new Map([
["idle", simpleState("idle", "state_idle")],
["spawn", simpleState("spawn", "state_spawn")],
]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_spawn", makeScannedAtlas("state_spawn", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_spawn", makeEncoded("s")],
]),
overrides: { spawnState: "spawn" },
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
expect(result.config?.spawnState).toBe("spawn");
});
it("errors when spawnState is unknown", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png"])]]),
});
const result = generateConfig({
scanned,
encoded: new Map([["state_idle", makeEncoded()]]),
overrides: { spawnState: "nonexistent" },
fallbackId: "cat",
});
expect(result.errors.some(e => e.path === "spawnState")).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Atlases */
/* ------------------------------------------------------------------ */
describe("generateConfig — atlases", () => {
it("computes correct frame regions for a 4-frame atlas", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png", "1.png", "2.png", "3.png"], 16, 16)],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([["state_idle", makeEncoded("h", 32, 32)]]),
overrides: null,
fallbackId: "cat",
});
const atlas = result.config?.atlases.state_idle;
expect(atlas?.width).toBe(32);
expect(atlas?.height).toBe(32);
expect(atlas?.frames["0.png"]).toEqual({ x: 0, y: 0, w: 16, h: 16 });
expect(atlas?.frames["1.png"]).toEqual({ x: 16, y: 0, w: 16, h: 16 });
expect(atlas?.frames["2.png"]).toEqual({ x: 0, y: 16, w: 16, h: 16 });
expect(atlas?.frames["3.png"]).toEqual({ x: 16, y: 16, w: 16, h: 16 });
});
it("errors when an atlas failed to encode", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png"])]]),
});
const result = generateConfig({
scanned,
encoded: new Map(),
overrides: null,
fallbackId: "cat",
});
expect(result.errors.some(e => e.message.includes("failed to encode"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Look sectors */
/* ------------------------------------------------------------------ */
describe("generateConfig — look sectors", () => {
it("uses compass angles for standard sector names", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png", "1.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png", "1.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("lookhash")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 50, max: 500 },
},
},
},
},
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
const sector = result.config?.states.idle?.look?.sectors[0];
expect(sector?.minAngle).toBe(337.5);
expect(sector?.maxAngle).toBe(22.5);
expect(sector?.folder).toBe("t");
});
it("uses explicit angles when config provides them", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 100 },
sectors: {
t: { minAngle: 350, maxAngle: 10 },
},
},
},
},
},
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
const sector = result.config?.states.idle?.look?.sectors[0];
expect(sector?.minAngle).toBe(350);
expect(sector?.maxAngle).toBe(10);
});
it("errors when look sectors exist but no config is provided", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: null,
fallbackId: "cat",
});
expect(result.errors.some(e => e.path === "states.idle.look")).toBe(true);
});
it("errors on non-compass sector name without explicit angles", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("towardPlayer", "state_idle_look_towardPlayer");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_towardPlayer", makeScannedAtlas("state_idle_look_towardPlayer", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_towardPlayer", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 100 },
},
},
},
},
fallbackId: "cat",
});
expect(result.errors.some(e => e.message.includes("not a compass direction"))).toBe(true);
});
it("passes through per-sector distance overrides", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
sectors: {
t: {
minAngle: 0,
maxAngle: 45,
minDistance: 200,
maxDistance: 400,
},
},
},
},
},
},
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
const sector = result.config?.states.idle?.look?.sectors[0];
expect(sector?.minDistance).toBe(200);
expect(sector?.maxDistance).toBe(400);
});
it("errors when only minDistance is set", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
sectors: {
t: { minAngle: 0, maxAngle: 45, minDistance: 200 },
},
},
},
},
},
fallbackId: "cat",
});
expect(result.errors.some(e => e.message.includes("only one of"))).toBe(true);
});
it("errors when only maxDistance is set", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
sectors: {
t: { minAngle: 0, maxAngle: 45, maxDistance: 400 },
},
},
},
},
},
fallbackId: "cat",
});
expect(result.errors.some(e => e.message.includes("only one of"))).toBe(true);
});
it("errors when minDistance exceeds maxDistance", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
sectors: {
t: {
minAngle: 0,
maxAngle: 45,
minDistance: 400,
maxDistance: 200,
},
},
},
},
},
},
fallbackId: "cat",
});
expect(result.errors.some(e => e.message.includes("greater than maxDistance"))).toBe(true);
});
it("accepts equal minDistance and maxDistance", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
sectors: {
t: {
minAngle: 0,
maxAngle: 45,
minDistance: 300,
maxDistance: 300,
},
},
},
},
},
},
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
const sector = result.config?.states.idle?.look?.sectors[0];
expect(sector?.minDistance).toBe(300);
expect(sector?.maxDistance).toBe(300);
});
it("omits distance fields when not configured", () => {
const state = simpleState("idle", "state_idle");
state.lookSectors.set("t", "state_idle_look_t");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_look_t", makeScannedAtlas("state_idle_look_t", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_look_t", makeEncoded("l")],
]),
overrides: {
states: {
idle: {
look: {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
},
},
},
},
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
const sector = result.config?.states.idle?.look?.sectors[0];
expect(sector?.minDistance).toBeUndefined();
expect(sector?.maxDistance).toBeUndefined();
expect("minDistance" in (sector ?? {})).toBe(false);
expect("maxDistance" in (sector ?? {})).toBe(false);
});
});
/* ------------------------------------------------------------------ */
/* Events */
/* ------------------------------------------------------------------ */
describe("generateConfig — events", () => {
it("uses defaults when no event config provided", () => {
const state = simpleState("idle", "state_idle");
state.events.set("sneeze", "state_idle_event_sneeze");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_event_sneeze", makeScannedAtlas("state_idle_event_sneeze", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_event_sneeze", makeEncoded("e")],
]),
overrides: null,
fallbackId: "cat",
});
const event = result.config?.states.idle?.events?.[0];
expect(event?.chance).toBe(0.4);
expect(event?.interval).toEqual([4, 10]);
expect(event?.cooldown).toBe(6);
expect(event?.weight).toBe(1);
expect(event?.interrupt).toBe("cut");
});
it("applies event overrides", () => {
const state = simpleState("idle", "state_idle");
state.events.set("sneeze", "state_idle_event_sneeze");
const scanned = makeScanned({
states: new Map([["idle", state]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["state_idle_event_sneeze", makeScannedAtlas("state_idle_event_sneeze", ["0.png"])],
]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["state_idle_event_sneeze", makeEncoded("e")],
]),
overrides: {
states: {
idle: {
events: {
sneeze: { chance: 0.15, cooldown: 20 },
},
},
},
},
fallbackId: "cat",
});
const event = result.config?.states.idle?.events?.[0];
expect(event?.chance).toBe(0.15);
expect(event?.cooldown).toBe(20);
expect(event?.interval).toEqual([4, 10]);
});
});
/* ------------------------------------------------------------------ */
/* Bubbles */
/* ------------------------------------------------------------------ */
describe("generateConfig — bubbles", () => {
it("errors when default bubble has no config", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["bubbles", makeScannedAtlas("bubbles", ["0.png"], 64, 32)],
]),
defaultBubbleAtlasId: "bubbles",
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["bubbles", makeEncoded("b", 64, 32)],
]),
overrides: null,
fallbackId: "cat",
});
expect(result.errors.some(e => e.path === "bubbles.default")).toBe(true);
});
it("includes default bubble when config provided", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["bubbles", makeScannedAtlas("bubbles", ["0.png"], 64, 32)],
]),
defaultBubbleAtlasId: "bubbles",
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["bubbles", makeEncoded("b", 64, 32)],
]),
overrides: {
bubbles: {
default: { width: 200, height: 100 },
},
},
fallbackId: "cat",
});
expect(result.errors).toEqual([]);
const bubble = result.config?.bubbles.default;
expect(bubble?.width).toBe(200);
expect(bubble?.height).toBe(100);
});
it("includes named bubble packs", () => {
const pack: ScannedBubblePack = {
name: "sneeze",
atlasId: "bubbles_sneeze",
iconAtlasId: null,
};
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["bubbles_sneeze", makeScannedAtlas("bubbles_sneeze", ["0.png"], 64, 32)],
]),
bubblePacks: new Map([["sneeze", pack]]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["bubbles_sneeze", makeEncoded("b", 64, 32)],
]),
overrides: {
bubbles: {
sneeze: { width: 180, height: 72 },
},
},
fallbackId: "cat",
});
expect(result.config?.bubbles.sneeze?.width).toBe(180);
});
});
/* ------------------------------------------------------------------ */
/* Icons */
/* ------------------------------------------------------------------ */
describe("generateConfig — icons", () => {
it("includes shared icons by simple name", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["bubbles_icons", makeScannedAtlas("bubbles_icons", ["heart", "fish"], 16, 16)],
]),
sharedIconAtlasId: "bubbles_icons",
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["bubbles_icons", makeEncoded("i", 32, 16)],
]),
overrides: null,
fallbackId: "cat",
});
expect(result.config?.icons?.heart).toEqual({
atlas: "bubbles_icons",
frames: ["heart"],
});
expect(result.config?.icons?.fish).toEqual({
atlas: "bubbles_icons",
frames: ["fish"],
});
});
it("includes per-pack icons with namespaced names", () => {
const pack: ScannedBubblePack = {
name: "sneeze",
atlasId: "bubbles_sneeze",
iconAtlasId: "bubbles_sneeze_icons",
};
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([
["state_idle", makeScannedAtlas("state_idle", ["0.png"])],
["bubbles_sneeze", makeScannedAtlas("bubbles_sneeze", ["0.png"], 64, 32)],
["bubbles_sneeze_icons", makeScannedAtlas("bubbles_sneeze_icons", ["sparkle"], 16, 16)],
]),
bubblePacks: new Map([["sneeze", pack]]),
});
const result = generateConfig({
scanned,
encoded: new Map([
["state_idle", makeEncoded()],
["bubbles_sneeze", makeEncoded("b", 64, 32)],
["bubbles_sneeze_icons", makeEncoded("i", 16, 16)],
]),
overrides: {
bubbles: {
sneeze: { width: 180, height: 72 },
},
},
fallbackId: "cat",
});
expect(result.config?.icons?.["sneeze/sparkle"]).toEqual({
atlas: "bubbles_sneeze_icons",
frames: ["sparkle"],
});
});
});
/* ------------------------------------------------------------------ */
/* Pass-through fields */
/* ------------------------------------------------------------------ */
describe("generateConfig — pass-through fields", () => {
it("passes through text, timing, voice overrides", () => {
const scanned = makeScanned({
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png"])]]),
});
const result = generateConfig({
scanned,
encoded: new Map([["state_idle", makeEncoded()]]),
overrides: {
text: { font: "14px monospace", speed: 12 },
timing: { holdLast: 2 },
voice: { basePitch: 1.5 },
},
fallbackId: "cat",
});
expect(result.config?.text?.font).toBe("14px monospace");
expect(result.config?.text?.speed).toBe(12);
expect(result.config?.timing?.holdLast).toBe(2);
expect(result.config?.voice?.basePitch).toBe(1.5);
});
});
/* ------------------------------------------------------------------ */
/* Scanned errors propagate */
/* ------------------------------------------------------------------ */
describe("generateConfig — scanned errors", () => {
it("returns null config when scan had errors", () => {
const scanned = makeScanned({
errors: [{ path: "/some/path", message: "Bad frame" }],
});
const result = generateConfig({
scanned,
encoded: new Map(),
overrides: null,
fallbackId: "cat",
});
expect(result.config).toBeNull();
expect(result.errors.length).toBe(1);
expect(result.errors[0]?.message).toBe("Bad frame");
});
it("propagates scan warnings", () => {
const scanned = makeScanned({
warnings: ["Folder had uppercase name"],
states: new Map([["idle", simpleState("idle", "state_idle")]]),
atlases: new Map([["state_idle", makeScannedAtlas("state_idle", ["0.png"])]]),
});
const result = generateConfig({
scanned,
encoded: new Map([["state_idle", makeEncoded()]]),
overrides: null,
fallbackId: "cat",
});
expect(result.warnings.some(w => w.includes("uppercase"))).toBe(true);
});
});
@@ -0,0 +1,462 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { computeFrameHash, encodeAll, encodeAtlas } from "../encode.js";
import type { PackedAtlas } from "../pack.js";
import type { FrameSource } from "../scan.js";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "encode-test-"));
});
afterEach(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
interface Color {
r: number;
g: number;
b: number;
a?: number;
}
async function makePng(relativePath: string, width: number, height: number, color: Color): Promise<void> {
const filePath = path.join(tmpDir, relativePath);
await fs.mkdir(path.dirname(filePath), { recursive: true });
const alpha = color.a ?? 1;
const buffer = await sharp({
create: {
width,
height,
channels: 4,
background: { r: color.r, g: color.g, b: color.b, alpha },
},
})
.png()
.toBuffer();
await fs.writeFile(filePath, buffer);
}
function makeFrameSource(name: string, fullPath: string, order: number, w = 16, h = 16): FrameSource {
return { name, path: fullPath, order, width: w, height: h };
}
/**
* Build a PackedAtlas directly from a set of already-written PNG files.
* Skips scan/pack for unit-style tests. `files` is an array of {relPath,
* color} representing frames that already exist on disk.
*/
function makePackedAtlas(frameW: number, frameH: number, files: Array<{ relPath: string; color: Color }>): PackedAtlas {
const frames = files.map((f, i) => ({
source: makeFrameSource(path.basename(f.relPath), path.join(tmpDir, f.relPath), i, frameW, frameH),
x: (i % Math.ceil(Math.sqrt(files.length))) * frameW,
y: Math.floor(i / Math.ceil(Math.sqrt(files.length))) * frameH,
w: frameW,
h: frameH,
}));
const n = files.length;
const cols = Math.ceil(Math.sqrt(n));
const rows = Math.ceil(n / cols);
return {
source: {
id: "test",
sourcePath: tmpDir,
frames: frames.map(f => f.source),
width: frameW,
height: frameH,
},
width: cols * frameW,
height: rows * frameH,
cols,
rows,
frames,
};
}
/* ------------------------------------------------------------------ */
/* WebP validation */
/* ------------------------------------------------------------------ */
describe("encodeAtlas — WebP output", () => {
it("produces a valid WebP file", async () => {
await makePng("0.png", 16, 16, { r: 255, g: 0, b: 0 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } }]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
// RIFF....WEBP magic bytes
expect(outcome.encoded.bytes.toString("ascii", 0, 4)).toBe("RIFF");
expect(outcome.encoded.bytes.toString("ascii", 8, 12)).toBe("WEBP");
});
it("produces the correct dimensions", async () => {
await makePng("0.png", 16, 16, { r: 255, g: 0, b: 0 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } }]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
const meta = await sharp(outcome.encoded.bytes).metadata();
expect(meta.width).toBe(16);
expect(meta.height).toBe(16);
expect(meta.format).toBe("webp");
});
it("atlasHash is exactly 8 characters", async () => {
await makePng("0.png", 16, 16, { r: 255, g: 0, b: 0 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } }]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.encoded.atlasHash).toMatch(/^[0-9a-f]{8}$/);
});
it("frameHash is 64 characters", async () => {
await makePng("0.png", 16, 16, { r: 255, g: 0, b: 0 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } }]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.encoded.frameHash).toMatch(/^[0-9a-f]{64}$/);
});
});
/* ------------------------------------------------------------------ */
/* Determinism */
/* ------------------------------------------------------------------ */
describe("encodeAtlas — determinism", () => {
it("same input produces byte-identical WebP", async () => {
await makePng("0.png", 16, 16, { r: 200, g: 100, b: 50 });
await makePng("1.png", 16, 16, { r: 50, g: 100, b: 200 });
const atlas = makePackedAtlas(16, 16, [
{ relPath: "0.png", color: { r: 200, g: 100, b: 50 } },
{ relPath: "1.png", color: { r: 50, g: 100, b: 200 } },
]);
const a = await encodeAtlas(atlas, { effort: 4 });
const b = await encodeAtlas(atlas, { effort: 4 });
expect(a.ok).toBe(true);
expect(b.ok).toBe(true);
if (!a.ok || !b.ok) return;
expect(a.encoded.atlasHash).toBe(b.encoded.atlasHash);
expect(a.encoded.frameHash).toBe(b.encoded.frameHash);
expect(a.encoded.bytes.equals(b.encoded.bytes)).toBe(true);
});
it("different pixel content produces different hashes", async () => {
await makePng("0.png", 16, 16, { r: 255, g: 0, b: 0 });
await makePng("1.png", 16, 16, { r: 0, g: 255, b: 0 });
const redAtlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } }]);
const greenAtlas = makePackedAtlas(16, 16, [{ relPath: "1.png", color: { r: 0, g: 255, b: 0 } }]);
const red = await encodeAtlas(redAtlas);
const green = await encodeAtlas(greenAtlas);
expect(red.ok).toBe(true);
expect(green.ok).toBe(true);
if (!red.ok || !green.ok) return;
expect(red.encoded.atlasHash).not.toBe(green.encoded.atlasHash);
expect(red.encoded.frameHash).not.toBe(green.encoded.frameHash);
});
});
/* ------------------------------------------------------------------ */
/* Pixel placement */
/* ------------------------------------------------------------------ */
describe("encodeAtlas — pixel placement", () => {
it("places each frame at its packed position", async () => {
// 4 frames of 8×8 → 2×2 grid, 16×16 atlas
await makePng("0.png", 8, 8, { r: 255, g: 0, b: 0 }); // red
await makePng("1.png", 8, 8, { r: 0, g: 255, b: 0 }); // green
await makePng("2.png", 8, 8, { r: 0, g: 0, b: 255 }); // blue
await makePng("3.png", 8, 8, { r: 255, g: 255, b: 0 }); // yellow
const atlas = makePackedAtlas(8, 8, [
{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } },
{ relPath: "1.png", color: { r: 0, g: 255, b: 0 } },
{ relPath: "2.png", color: { r: 0, g: 0, b: 255 } },
{ relPath: "3.png", color: { r: 255, g: 255, b: 0 } },
]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
const raw = await sharp(outcome.encoded.bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
expect(raw.info.width).toBe(16);
expect(raw.info.height).toBe(16);
expect(raw.info.channels).toBe(4);
const pixelAt = (x: number, y: number) => {
const i = (y * 16 + x) * 4;
return {
r: raw.data[i]!,
g: raw.data[i + 1]!,
b: raw.data[i + 2]!,
a: raw.data[i + 3]!,
};
};
// Top-left of each cell
expect(pixelAt(0, 0).r).toBeCloseTo(255, -1);
expect(pixelAt(0, 0).g).toBeCloseTo(0, -1);
expect(pixelAt(8, 0).g).toBeCloseTo(255, -1);
expect(pixelAt(8, 0).r).toBeCloseTo(0, -1);
expect(pixelAt(0, 8).b).toBeCloseTo(255, -1);
expect(pixelAt(0, 8).r).toBeCloseTo(0, -1);
expect(pixelAt(8, 8).r).toBeCloseTo(255, -1);
expect(pixelAt(8, 8).g).toBeCloseTo(255, -1);
expect(pixelAt(8, 8).b).toBeCloseTo(0, -1);
});
it("leaves empty cells transparent", async () => {
// 5 frames of 8×8 → 3×2 grid (6 cells), one empty cell at bottom-right
await makePng("0.png", 8, 8, { r: 255, g: 0, b: 0 });
await makePng("1.png", 8, 8, { r: 0, g: 255, b: 0 });
await makePng("2.png", 8, 8, { r: 0, g: 0, b: 255 });
await makePng("3.png", 8, 8, { r: 255, g: 255, b: 0 });
await makePng("4.png", 8, 8, { r: 128, g: 0, b: 128 });
const atlas = makePackedAtlas(8, 8, [
{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } },
{ relPath: "1.png", color: { r: 0, g: 255, b: 0 } },
{ relPath: "2.png", color: { r: 0, g: 0, b: 255 } },
{ relPath: "3.png", color: { r: 255, g: 255, b: 0 } },
{ relPath: "4.png", color: { r: 128, g: 0, b: 128 } },
]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
const raw = await sharp(outcome.encoded.bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
expect(raw.info.width).toBe(24);
expect(raw.info.height).toBe(16);
// Empty cell at (16, 8) through (23, 15)
const emptyI = (8 * 24 + 16) * 4;
expect(raw.data[emptyI + 3]).toBe(0); // alpha = 0
});
it("preserves frame transparency", async () => {
await makePng("0.png", 8, 8, { r: 255, g: 0, b: 0, a: 0.5 });
const atlas = makePackedAtlas(8, 8, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0, a: 0.5 } }]);
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
const raw = await sharp(outcome.encoded.bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
const centerI = (4 * 8 + 4) * 4;
// Alpha should be near 128 (0.5 × 255), with tolerance for rounding
expect(raw.data[centerI + 3]).toBeGreaterThan(120);
expect(raw.data[centerI + 3]).toBeLessThan(136);
});
});
/* ------------------------------------------------------------------ */
/* Effort parameter */
/* ------------------------------------------------------------------ */
describe("encodeAtlas — effort", () => {
it("accepts effort values 0 through 6", async () => {
await makePng("0.png", 16, 16, { r: 100, g: 150, b: 200 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 100, g: 150, b: 200 } }]);
for (const effort of [0, 1, 2, 3, 4, 5, 6]) {
const outcome = await encodeAtlas(atlas, { effort });
expect(outcome.ok).toBe(true);
}
});
it("clamps out-of-range values", async () => {
await makePng("0.png", 16, 16, { r: 100, g: 150, b: 200 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 100, g: 150, b: 200 } }]);
// Negative and >6 should clamp, still produce valid output
const neg = await encodeAtlas(atlas, { effort: -5 });
const big = await encodeAtlas(atlas, { effort: 100 });
expect(neg.ok).toBe(true);
expect(big.ok).toBe(true);
});
it("defaults to effort 6", async () => {
await makePng("0.png", 16, 16, { r: 100, g: 150, b: 200 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 100, g: 150, b: 200 } }]);
const defaultOutcome = await encodeAtlas(atlas);
const explicit6 = await encodeAtlas(atlas, { effort: 6 });
expect(defaultOutcome.ok).toBe(true);
expect(explicit6.ok).toBe(true);
if (!defaultOutcome.ok || !explicit6.ok) return;
// Same bytes = same effective effort
expect(defaultOutcome.encoded.bytes.equals(explicit6.encoded.bytes)).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Error handling */
/* ------------------------------------------------------------------ */
describe("encodeAtlas — errors", () => {
it("returns ok:false for missing frame file", async () => {
const atlas: PackedAtlas = {
source: {
id: "test",
sourcePath: tmpDir,
frames: [],
width: 16,
height: 16,
},
width: 16,
height: 16,
cols: 1,
rows: 1,
frames: [
{
source: makeFrameSource("missing.png", path.join(tmpDir, "missing.png"), 0),
x: 0,
y: 0,
w: 16,
h: 16,
},
],
};
const outcome = await encodeAtlas(atlas);
expect(outcome.ok).toBe(false);
if (outcome.ok) return;
expect(outcome.error).toContain("Failed to read frame");
});
});
describe("encodeAll", () => {
it("encodes every atlas successfully", async () => {
await makePng("a/0.png", 8, 8, { r: 255, g: 0, b: 0 });
await makePng("b/0.png", 8, 8, { r: 0, g: 255, b: 0 });
const atlasA = makePackedAtlas(8, 8, [{ relPath: "a/0.png", color: { r: 255, g: 0, b: 0 } }]);
const atlasB = makePackedAtlas(8, 8, [{ relPath: "b/0.png", color: { r: 0, g: 255, b: 0 } }]);
const atlases = new Map([
["a", atlasA],
["b", atlasB],
]);
const result = await encodeAll(atlases);
expect(result.errors).toEqual([]);
expect(result.encoded.size).toBe(2);
expect(result.encoded.get("a")?.atlasHash).toBeDefined();
expect(result.encoded.get("b")?.atlasHash).toBeDefined();
});
it("accumulates errors without stopping", async () => {
await makePng("good/0.png", 8, 8, { r: 255, g: 0, b: 0 });
const good = makePackedAtlas(8, 8, [{ relPath: "good/0.png", color: { r: 255, g: 0, b: 0 } }]);
const bad: PackedAtlas = {
source: { id: "bad", sourcePath: tmpDir, frames: [], width: 16, height: 16 },
width: 16,
height: 16,
cols: 1,
rows: 1,
frames: [
{
source: makeFrameSource("missing.png", path.join(tmpDir, "missing.png"), 0),
x: 0,
y: 0,
w: 16,
h: 16,
},
],
};
const atlases = new Map([
["good", good],
["bad", bad],
]);
const result = await encodeAll(atlases);
expect(result.encoded.size).toBe(1);
expect(result.errors.length).toBe(1);
expect(result.errors[0]?.atlasId).toBe("bad");
});
});
describe("computeFrameHash", () => {
it("is stable across calls", async () => {
await makePng("0.png", 16, 16, { r: 100, g: 150, b: 200 });
await makePng("1.png", 16, 16, { r: 200, g: 150, b: 100 });
const atlas = makePackedAtlas(16, 16, [
{ relPath: "0.png", color: { r: 100, g: 150, b: 200 } },
{ relPath: "1.png", color: { r: 200, g: 150, b: 100 } },
]);
const a = await computeFrameHash(atlas);
const b = await computeFrameHash(atlas);
expect(a).toBe(b);
});
it("matches the frameHash returned by encodeAtlas", async () => {
await makePng("0.png", 16, 16, { r: 100, g: 150, b: 200 });
const atlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 100, g: 150, b: 200 } }]);
const precomputed = await computeFrameHash(atlas);
const encoded = await encodeAtlas(atlas);
expect(encoded.ok).toBe(true);
if (!encoded.ok) return;
expect(precomputed).toBe(encoded.encoded.frameHash);
});
it("changes when frame content changes", async () => {
await makePng("0.png", 16, 16, { r: 255, g: 0, b: 0 });
await makePng("1.png", 16, 16, { r: 0, g: 255, b: 0 });
const redAtlas = makePackedAtlas(16, 16, [{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } }]);
const greenAtlas = makePackedAtlas(16, 16, [{ relPath: "1.png", color: { r: 0, g: 255, b: 0 } }]);
const redHash = await computeFrameHash(redAtlas);
const greenHash = await computeFrameHash(greenAtlas);
expect(redHash).not.toBe(greenHash);
});
it("changes when frame positions change", async () => {
await makePng("0.png", 8, 8, { r: 255, g: 0, b: 0 });
await makePng("1.png", 8, 8, { r: 0, g: 255, b: 0 });
const atlas = makePackedAtlas(8, 8, [
{ relPath: "0.png", color: { r: 255, g: 0, b: 0 } },
{ relPath: "1.png", color: { r: 0, g: 255, b: 0 } },
]);
const hash1 = await computeFrameHash(atlas);
const swapped: PackedAtlas = {
...atlas,
frames: atlas.frames.map((f, i) => ({
...f,
x: i === 0 ? f.x + 8 : f.x - 8,
})),
};
const hash2 = await computeFrameHash(swapped);
expect(hash1).not.toBe(hash2);
});
it("throws on missing frame file", async () => {
const atlas: PackedAtlas = {
source: {
id: "test",
sourcePath: tmpDir,
frames: [],
width: 16,
height: 16,
},
width: 16,
height: 16,
cols: 1,
rows: 1,
frames: [
{
source: makeFrameSource("missing.png", path.join(tmpDir, "missing.png"), 0),
x: 0,
y: 0,
w: 16,
h: 16,
},
],
};
await expect(computeFrameHash(atlas)).rejects.toThrow(/Failed to read frame/);
});
});
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { sha256, shortSha256 } from "../hash";
describe("sha256", () => {
it("returns 64-char hex for empty input", () => {
expect(sha256("")).toBe("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
});
it('returns the known hash for "hello"', () => {
expect(sha256("hello")).toBe("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824");
});
it("hashes a string the same as its UTF-8 buffer", () => {
expect(sha256("hello")).toBe(sha256(Buffer.from("hello", "utf8")));
});
it("hashes a Buffer the same as the equivalent Uint8Array", () => {
const bytes = [1, 2, 3, 4, 5];
expect(sha256(Buffer.from(bytes))).toBe(sha256(new Uint8Array(bytes)));
});
it("handles non-ASCII strings", () => {
// Sanity check that UTF-8 encoding is used, not Latin-1
expect(sha256("日本語")).toBe(sha256(Buffer.from("日本語", "utf8")));
});
it("is deterministic", () => {
const input = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7]);
expect(sha256(input)).toBe(sha256(input));
});
it("produces different output for different input", () => {
expect(sha256("a")).not.toBe(sha256("b"));
expect(sha256(Buffer.from([0]))).not.toBe(sha256(Buffer.from([1])));
});
it("empty buffer and empty string hash identically", () => {
expect(sha256(Buffer.alloc(0))).toBe(sha256(""));
});
});
describe("shortSha256", () => {
it("returns exactly 8 characters", () => {
expect(shortSha256("")).toHaveLength(8);
expect(shortSha256("hello")).toHaveLength(8);
expect(shortSha256(Buffer.alloc(10000))).toHaveLength(8);
});
it("is a prefix of the full sha256", () => {
const full = sha256("hello");
const short = shortSha256("hello");
expect(full.startsWith(short)).toBe(true);
});
it('preserves the "different input → different hash" property', () => {
expect(shortSha256("a")).not.toBe(shortSha256("b"));
});
it("accepts both strings and buffers", () => {
expect(shortSha256("hello")).toBe(shortSha256(Buffer.from("hello", "utf8")));
});
it("is deterministic", () => {
expect(shortSha256("content")).toBe(shortSha256("content"));
});
});
@@ -0,0 +1,320 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { pack } from "../index.js";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
let tmpDir: string;
let inputDir: string;
let outputDir: string;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "pack-test-"));
inputDir = path.join(tmpDir, "input");
outputDir = path.join(tmpDir, "output");
await fs.mkdir(inputDir, { recursive: true });
});
afterEach(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
async function makePng(
relativePath: string,
width = 16,
height = 16,
color: { r: number; g: number; b: number } = { r: 255, g: 0, b: 0 },
): Promise<void> {
const filePath = path.join(inputDir, relativePath);
await fs.mkdir(path.dirname(filePath), { recursive: true });
const buffer = await sharp({
create: {
width,
height,
channels: 4,
background: { ...color, alpha: 1 },
},
})
.png()
.toBuffer();
await fs.writeFile(filePath, buffer);
}
async function writeConfig(config: object): Promise<void> {
await fs.writeFile(path.join(inputDir, "character.config.json"), JSON.stringify(config, null, 2));
}
async function fileExists(p: string): Promise<boolean> {
try {
await fs.access(p);
return true;
} catch {
return false;
}
}
/* ------------------------------------------------------------------ */
/* Happy path */
/* ------------------------------------------------------------------ */
describe("pack — minimal valid input", () => {
it("produces character.json and atlas files", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/1.png");
const result = await pack({ input: inputDir, output: outputDir });
expect(result.ok).toBe(true);
expect(result.errors).toBeUndefined();
expect(result.characterConfig).toBeDefined();
expect(result.characterConfig?.id).toBe("input");
expect(result.characterConfig?.initialState).toBe("idle");
expect(await fileExists(path.join(outputDir, "character.json"))).toBe(true);
expect(await fileExists(path.join(outputDir, "manifest.json"))).toBe(true);
const atlasFiles = await fs.readdir(path.join(outputDir, "atlases"));
expect(atlasFiles.length).toBe(1);
expect(atlasFiles[0]).toMatch(/^state_idle\.[0-9a-f]{8}\.webp$/);
});
it("reports encoded atlases in result", async () => {
await makePng("states/idle/0.png");
const result = await pack({ input: inputDir, output: outputDir });
expect(result.atlases).toBeDefined();
expect(result.atlases?.length).toBe(1);
expect(result.atlases?.[0]?.id).toBe("state_idle");
expect(result.atlases?.[0]?.action).toBe("encoded");
expect(result.atlases?.[0]?.bytes).toBeGreaterThan(0);
});
it("writes valid JSON to character.json", async () => {
await makePng("states/idle/0.png");
await pack({ input: inputDir, output: outputDir });
const content = await fs.readFile(path.join(outputDir, "character.json"), "utf8");
const parsed = JSON.parse(content);
expect(parsed.version).toBe(1);
expect(parsed.atlases).toBeDefined();
expect(parsed.states).toBeDefined();
});
it("uses config overrides when character.config.json exists", async () => {
await makePng("states/idle/0.png");
await writeConfig({ id: "my-cat" });
const result = await pack({ input: inputDir, output: outputDir });
expect(result.ok).toBe(true);
expect(result.characterConfig?.id).toBe("my-cat");
});
it("uses --config explicit path over input folder", async () => {
await makePng("states/idle/0.png");
await writeConfig({ id: "from-input" });
const altConfigPath = path.join(tmpDir, "alt.config.json");
await fs.writeFile(altConfigPath, JSON.stringify({ id: "from-explicit" }));
const result = await pack({
input: inputDir,
output: outputDir,
config: altConfigPath,
});
expect(result.characterConfig?.id).toBe("from-explicit");
});
});
/* ------------------------------------------------------------------ */
/* Idempotency */
/* ------------------------------------------------------------------ */
describe("pack — idempotency", () => {
it("skips encoding unchanged atlases on second run", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/1.png");
const first = await pack({ input: inputDir, output: outputDir });
expect(first.ok).toBe(true);
expect(first.atlases?.[0]?.action).toBe("encoded");
const second = await pack({ input: inputDir, output: outputDir });
expect(second.ok).toBe(true);
expect(second.atlases?.[0]?.action).toBe("reused");
expect(second.atlases?.[0]?.atlasHash).toBe(first.atlases?.[0]?.atlasHash);
});
it("re-encodes when frame content changes", async () => {
await makePng("states/idle/0.png", 16, 16, { r: 255, g: 0, b: 0 });
const first = await pack({ input: inputDir, output: outputDir });
const firstHash = first.atlases?.[0]?.atlasHash;
await makePng("states/idle/0.png", 16, 16, { r: 0, g: 255, b: 0 });
const second = await pack({ input: inputDir, output: outputDir });
expect(second.ok).toBe(true);
expect(second.atlases?.[0]?.action).toBe("encoded");
expect(second.atlases?.[0]?.atlasHash).not.toBe(firstHash);
});
it("re-encodes when atlas file is deleted between runs", async () => {
await makePng("states/idle/0.png");
const first = await pack({ input: inputDir, output: outputDir });
expect(first.ok).toBe(true);
const atlasFiles = await fs.readdir(path.join(outputDir, "atlases"));
for (const f of atlasFiles) {
await fs.unlink(path.join(outputDir, "atlases", f));
}
const second = await pack({ input: inputDir, output: outputDir });
expect(second.ok).toBe(true);
expect(second.atlases?.[0]?.action).toBe("encoded");
});
it("re-encodes everything on first run (no manifest)", async () => {
await makePng("states/idle/0.png");
const result = await pack({ input: inputDir, output: outputDir });
expect(result.atlases?.[0]?.action).toBe("encoded");
});
});
/* ------------------------------------------------------------------ */
/* Orphan cleanup */
/* ------------------------------------------------------------------ */
describe("pack — orphan cleanup", () => {
it("deletes atlas files not in current config", async () => {
await makePng("states/idle/0.png");
const first = await pack({ input: inputDir, output: outputDir });
expect(first.ok).toBe(true);
const orphanPath = path.join(outputDir, "atlases", "state_old.deadbeef.webp");
await fs.writeFile(orphanPath, "orphan");
await pack({ input: inputDir, output: outputDir });
expect(await fileExists(orphanPath)).toBe(false);
});
it("reports deleted orphans in result", async () => {
await makePng("states/idle/0.png");
await pack({ input: inputDir, output: outputDir });
const orphanPath = path.join(outputDir, "atlases", "orphan.12345678.webp");
await fs.writeFile(orphanPath, "orphan");
const second = await pack({ input: inputDir, output: outputDir });
expect(second.orphansDeleted?.length).toBe(1);
});
});
/* ------------------------------------------------------------------ */
/* Dry run */
/* ------------------------------------------------------------------ */
describe("pack — dry-run", () => {
it("does not write any files", async () => {
await makePng("states/idle/0.png");
await pack({ input: inputDir, output: outputDir, dryRun: true });
expect(await fileExists(path.join(outputDir, "character.json"))).toBe(false);
expect(await fileExists(path.join(outputDir, "manifest.json"))).toBe(false);
expect(await fileExists(path.join(outputDir, "atlases"))).toBe(false);
});
it("still returns characterConfig and atlas outcomes", async () => {
await makePng("states/idle/0.png");
const result = await pack({ input: inputDir, output: outputDir, dryRun: true });
expect(result.ok).toBe(true);
expect(result.characterConfig).toBeDefined();
expect(result.atlases?.length).toBe(1);
expect(result.written?.config).toBeNull();
expect(result.written?.manifest).toBeNull();
expect(result.written?.atlases).toEqual([]);
});
});
/* ------------------------------------------------------------------ */
/* Error paths */
/* ------------------------------------------------------------------ */
describe("pack — errors", () => {
it("fails on missing input directory", async () => {
const result = await pack({
input: path.join(tmpDir, "nonexistent"),
output: outputDir,
});
expect(result.ok).toBe(false);
expect(result.errors?.length).toBeGreaterThan(0);
});
it("fails on missing states folder", async () => {
const result = await pack({ input: inputDir, output: outputDir });
expect(result.ok).toBe(false);
expect(result.errors?.some(e => e.message.includes("states/"))).toBe(true);
});
it("fails on invalid config JSON", async () => {
await makePng("states/idle/0.png");
await fs.writeFile(path.join(inputDir, "character.config.json"), "not json");
const result = await pack({ input: inputDir, output: outputDir });
expect(result.ok).toBe(false);
expect(result.errors?.some(e => e.message.includes("not valid JSON"))).toBe(true);
});
it("fails when look sectors exist without config", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/look/t/0.png");
const result = await pack({ input: inputDir, output: outputDir });
expect(result.ok).toBe(false);
expect(result.errors?.some(e => e.path === "states.idle.look")).toBe(true);
});
it("accumulates multiple errors", async () => {
const result = await pack({ input: inputDir, output: outputDir });
expect(result.ok).toBe(false);
expect(result.errors?.length).toBeGreaterThan(0);
});
});
/* ------------------------------------------------------------------ */
/* Config overrides integration */
/* ------------------------------------------------------------------ */
describe("pack — overrides integration", () => {
it("respects framerate override", async () => {
await makePng("states/idle/0.png");
await writeConfig({
states: { idle: { base: { framerate: 16 } } },
});
const result = await pack({ input: inputDir, output: outputDir });
expect(result.characterConfig?.states.idle?.base.framerate).toBe(16);
});
it("respects maxAtlasSize and fails when too big", async () => {
for (let i = 0; i < 16; i++) {
await makePng(`states/idle/${i}.png`, 256, 256);
}
await writeConfig({ id: "big" });
const result = await pack({
input: inputDir,
output: outputDir,
maxAtlasSize: 512,
});
expect(result.ok).toBe(false);
expect(result.errors?.some(e => e.message.includes("exceeding max size"))).toBe(true);
});
});
@@ -0,0 +1,270 @@
import { describe, expect, it } from "vitest";
import { packAll, packAtlas } from "../pack.js";
import type { FrameSource, ScannedAtlas } from "../scan.js";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
function makeFrame(name: string, order: number, w = 16, h = 16): FrameSource {
return { name, path: `/fake/${name}`, order, width: w, height: h };
}
function makeAtlas(id: string, frameCount: number, w = 16, h = 16): ScannedAtlas {
const frames: FrameSource[] = [];
for (let i = 0; i < frameCount; i++) {
frames.push(makeFrame(`${i}.png`, i, w, h));
}
return {
id,
sourcePath: `/fake/${id}`,
frames,
width: w,
height: h,
};
}
/* ------------------------------------------------------------------ */
/* Grid math */
/* ------------------------------------------------------------------ */
describe("packAtlas — grid dimensions", () => {
it("single frame produces a 1×1 grid", () => {
const outcome = packAtlas(makeAtlas("a", 1));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.cols).toBe(1);
expect(outcome.atlas.rows).toBe(1);
expect(outcome.atlas.width).toBe(16);
expect(outcome.atlas.height).toBe(16);
});
it("two frames produce a 2×1 grid", () => {
const outcome = packAtlas(makeAtlas("a", 2));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.cols).toBe(2);
expect(outcome.atlas.rows).toBe(1);
expect(outcome.atlas.width).toBe(32);
expect(outcome.atlas.height).toBe(16);
});
it("four frames produce a 2×2 grid", () => {
const outcome = packAtlas(makeAtlas("a", 4));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.cols).toBe(2);
expect(outcome.atlas.rows).toBe(2);
expect(outcome.atlas.width).toBe(32);
expect(outcome.atlas.height).toBe(32);
});
it("five frames produce a 3×2 grid (with one empty cell)", () => {
const outcome = packAtlas(makeAtlas("a", 5));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.cols).toBe(3);
expect(outcome.atlas.rows).toBe(2);
expect(outcome.atlas.width).toBe(48);
expect(outcome.atlas.height).toBe(32);
});
it("nine frames produce a 3×3 grid", () => {
const outcome = packAtlas(makeAtlas("a", 9));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.cols).toBe(3);
expect(outcome.atlas.rows).toBe(3);
expect(outcome.atlas.width).toBe(48);
expect(outcome.atlas.height).toBe(48);
});
it("ten frames produce a 4×3 grid", () => {
const outcome = packAtlas(makeAtlas("a", 10));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.cols).toBe(4);
expect(outcome.atlas.rows).toBe(3);
expect(outcome.atlas.width).toBe(64);
expect(outcome.atlas.height).toBe(48);
});
it("uses frame dimensions correctly", () => {
const outcome = packAtlas(makeAtlas("a", 4, 64, 32));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
expect(outcome.atlas.width).toBe(128);
expect(outcome.atlas.height).toBe(64);
});
});
/* ------------------------------------------------------------------ */
/* Frame positions */
/* ------------------------------------------------------------------ */
describe("packAtlas — frame positions", () => {
it("places frames in row-major order", () => {
const outcome = packAtlas(makeAtlas("a", 4));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
const frames = outcome.atlas.frames;
// Grid is 2×2, so positions are:
// (0,0), (16,0), (0,16), (16,16)
expect(frames[0]?.x).toBe(0);
expect(frames[0]?.y).toBe(0);
expect(frames[1]?.x).toBe(16);
expect(frames[1]?.y).toBe(0);
expect(frames[2]?.x).toBe(0);
expect(frames[2]?.y).toBe(16);
expect(frames[3]?.x).toBe(16);
expect(frames[3]?.y).toBe(16);
});
it("all frames carry the frame dimensions as w and h", () => {
const outcome = packAtlas(makeAtlas("a", 4, 32, 24));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
for (const frame of outcome.atlas.frames) {
expect(frame.w).toBe(32);
expect(frame.h).toBe(24);
}
});
it("preserves frame order from scan", () => {
const frames: FrameSource[] = [makeFrame("b.png", 5), makeFrame("a.png", 1), makeFrame("c.png", 10)];
const atlas: ScannedAtlas = {
id: "x",
sourcePath: "/fake",
frames,
width: 16,
height: 16,
};
const outcome = packAtlas(atlas);
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
// Order is preserved from input, regardless of names/orders
expect(outcome.atlas.frames[0]?.source.name).toBe("b.png");
expect(outcome.atlas.frames[1]?.source.name).toBe("a.png");
expect(outcome.atlas.frames[2]?.source.name).toBe("c.png");
});
it("does not overlap frame regions", () => {
const outcome = packAtlas(makeAtlas("a", 9));
expect(outcome.ok).toBe(true);
if (!outcome.ok) return;
// For each pair, check that rectangles don't overlap
const frames = outcome.atlas.frames;
for (let i = 0; i < frames.length; i++) {
for (let j = i + 1; j < frames.length; j++) {
const a = frames[i]!;
const b = frames[j]!;
const overlapX = a.x < b.x + b.w && b.x < a.x + a.w;
const overlapY = a.y < b.y + b.h && b.y < a.y + a.h;
expect(overlapX && overlapY).toBe(false);
}
}
});
});
/* ------------------------------------------------------------------ */
/* Max size enforcement */
/* ------------------------------------------------------------------ */
describe("packAtlas — max size", () => {
it("accepts atlases that fit within the default 2048 limit", () => {
// 128 frames of 128×128 = 12 columns × 128 = 1536 × 1408
const outcome = packAtlas(makeAtlas("a", 128, 128, 128));
expect(outcome.ok).toBe(true);
});
it("rejects atlases larger than max", () => {
// 256 frames of 256×256 = 16 columns × 256 = 4096×4096
const outcome = packAtlas(makeAtlas("a", 256, 256, 256));
expect(outcome.ok).toBe(false);
if (outcome.ok) return;
expect(outcome.error).toContain("exceeding max size");
});
it("respects a custom maxSize", () => {
const outcome = packAtlas(makeAtlas("a", 16, 64, 64), { maxSize: 128 });
expect(outcome.ok).toBe(false);
if (outcome.ok) return;
expect(outcome.error).toContain("256×256");
});
it("includes atlas id in error message", () => {
const outcome = packAtlas(makeAtlas("my_state", 256, 256, 256));
expect(outcome.ok).toBe(false);
if (outcome.ok) return;
expect(outcome.error).toContain("my_state");
});
});
/* ------------------------------------------------------------------ */
/* Defensive checks */
/* ------------------------------------------------------------------ */
describe("packAtlas — defensive checks", () => {
it("errors on empty frame list", () => {
const atlas: ScannedAtlas = {
id: "a",
sourcePath: "/fake",
frames: [],
width: 0,
height: 0,
};
const outcome = packAtlas(atlas);
expect(outcome.ok).toBe(false);
if (outcome.ok) return;
expect(outcome.error).toContain("no frames");
});
it("errors on zero frame dimensions", () => {
const atlas: ScannedAtlas = {
id: "a",
sourcePath: "/fake",
frames: [makeFrame("0.png", 0)],
width: 0,
height: 0,
};
const outcome = packAtlas(atlas);
expect(outcome.ok).toBe(false);
});
});
/* ------------------------------------------------------------------ */
/* packAll */
/* ------------------------------------------------------------------ */
describe("packAll", () => {
it("packs every atlas and returns them keyed by id", () => {
const atlases = new Map([
["a", makeAtlas("a", 4)],
["b", makeAtlas("b", 2)],
]);
const result = packAll(atlases);
expect(result.errors).toEqual([]);
expect(result.packed.size).toBe(2);
expect(result.packed.get("a")?.cols).toBe(2);
expect(result.packed.get("b")?.cols).toBe(2);
});
it("accumulates errors without stopping", () => {
const atlases = new Map([
["good", makeAtlas("good", 4)],
["huge", makeAtlas("huge", 256, 256, 256)],
["alsogood", makeAtlas("alsogood", 2)],
]);
const result = packAll(atlases);
expect(result.packed.size).toBe(2); // good + alsogood
expect(result.errors.length).toBe(1);
expect(result.errors[0]?.atlasId).toBe("huge");
});
it("handles empty input", () => {
const result = packAll(new Map());
expect(result.packed.size).toBe(0);
expect(result.errors).toEqual([]);
});
});
@@ -0,0 +1,305 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { scan } from "../scan.js";
/* ------------------------------------------------------------------ */
/* Fixture helpers */
/* ------------------------------------------------------------------ */
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "scan-test-"));
});
afterEach(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
async function makePng(
relativePath: string,
width = 16,
height = 16,
color: { r: number; g: number; b: number } = { r: 255, g: 0, b: 0 },
): Promise<void> {
const filePath = path.join(tmpDir, relativePath);
await fs.mkdir(path.dirname(filePath), { recursive: true });
const buffer = await sharp({
create: {
width,
height,
channels: 4,
background: { ...color, alpha: 1 },
},
})
.png()
.toBuffer();
await fs.writeFile(filePath, buffer);
}
/* ------------------------------------------------------------------ */
/* Input validation */
/* ------------------------------------------------------------------ */
describe("scan — input validation", () => {
it("errors when input does not exist", async () => {
const result = await scan(path.join(tmpDir, "nope"));
expect(result.errors.length).toBeGreaterThan(0);
expect(result.errors[0]?.message).toContain("does not exist");
});
it("errors when input is a file, not a directory", async () => {
const filePath = path.join(tmpDir, "file");
await fs.writeFile(filePath, "not a dir");
const result = await scan(filePath);
expect(result.errors.some(e => e.message.includes("must be a directory"))).toBe(true);
});
it("errors when states/ folder is missing", async () => {
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("states/"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Basic successful scans */
/* ------------------------------------------------------------------ */
describe("scan — minimal valid input", () => {
it("scans one state with one frame", async () => {
await makePng("states/idle/0.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.states.size).toBe(1);
expect(result.states.get("idle")?.baseAtlasId).toBe("state_idle");
expect(result.atlases.get("state_idle")?.frames.length).toBe(1);
});
it("scans one state with multiple frames sorted by number", async () => {
await makePng("states/idle/2.png");
await makePng("states/idle/0.png");
await makePng("states/idle/10.png");
await makePng("states/idle/1.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
const frames = result.atlases.get("state_idle")?.frames ?? [];
expect(frames.map(f => f.order)).toEqual([0, 1, 2, 10]);
});
it("accepts filenames with numbers embedded", async () => {
await makePng("states/idle/frame_0.png");
await makePng("states/idle/frame_1.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.atlases.get("state_idle")?.frames.length).toBe(2);
});
it("accepts gaps in numbering (Reading B)", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/3.png");
await makePng("states/idle/7.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.atlases.get("state_idle")?.frames.length).toBe(3);
});
it("accepts non-zero start (Reading B)", async () => {
await makePng("states/idle/1.png");
await makePng("states/idle/2.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.atlases.get("state_idle")?.frames.length).toBe(2);
});
});
/* ------------------------------------------------------------------ */
/* Look sectors */
/* ------------------------------------------------------------------ */
describe("scan — look sectors", () => {
it("scans look sectors", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/1.png");
await makePng("states/idle/look/t/0.png");
await makePng("states/idle/look/t/1.png");
await makePng("states/idle/look/r/0.png");
await makePng("states/idle/look/r/1.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
const idle = result.states.get("idle");
expect(idle?.lookSectors.get("t")).toBe("state_idle_look_t");
expect(idle?.lookSectors.get("r")).toBe("state_idle_look_r");
});
it("errors when look sector has mismatched frame count", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/1.png");
await makePng("states/idle/look/t/0.png"); // base has 2, sector has 1
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("Frame counts must match"))).toBe(true);
});
it("errors on empty sector folder", async () => {
await makePng("states/idle/0.png");
await fs.mkdir(path.join(tmpDir, "states/idle/look/t"), { recursive: true });
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("has no frames"))).toBe(true);
});
it("errors on empty look/ folder", async () => {
await makePng("states/idle/0.png");
await fs.mkdir(path.join(tmpDir, "states/idle/look"), { recursive: true });
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes('Empty "look/"'))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Events */
/* ------------------------------------------------------------------ */
describe("scan — events", () => {
it("scans events", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/event/sneeze/0.png");
await makePng("states/idle/event/sneeze/1.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
const idle = result.states.get("idle");
expect(idle?.events.get("sneeze")).toBe("state_idle_event_sneeze");
});
it("errors on empty event folder", async () => {
await makePng("states/idle/0.png");
await fs.mkdir(path.join(tmpDir, "states/idle/event/sneeze"), { recursive: true });
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("has no frames"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Bubbles and icons */
/* ------------------------------------------------------------------ */
describe("scan — bubbles", () => {
it("scans default bubble from loose PNGs", async () => {
await makePng("states/idle/0.png");
await makePng("bubbles/0.png", 64, 32);
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.defaultBubbleAtlasId).toBe("bubbles");
});
it("scans named bubble packs", async () => {
await makePng("states/idle/0.png");
await makePng("bubbles/sneeze/0.png", 64, 32);
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.bubblePacks.get("sneeze")?.atlasId).toBe("bubbles_sneeze");
});
it("scans shared icons", async () => {
await makePng("states/idle/0.png");
await makePng("bubbles/_icons/heart.png", 16, 16);
await makePng("bubbles/_icons/fish.png", 16, 16);
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.sharedIconAtlasId).toBe("bubbles_icons");
const atlas = result.atlases.get("bubbles_icons");
expect(atlas?.frames.length).toBe(2);
// Sorted alphabetically
expect(atlas?.frames[0]?.name).toBe("fish");
expect(atlas?.frames[1]?.name).toBe("heart");
});
it("scans per-pack icons", async () => {
await makePng("states/idle/0.png");
await makePng("bubbles/sneeze/0.png", 64, 32);
await makePng("bubbles/sneeze/icons/sparkle.png", 16, 16);
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.bubblePacks.get("sneeze")?.iconAtlasId).toBe("bubbles_sneeze_icons");
});
it("works without bubbles/ folder", async () => {
await makePng("states/idle/0.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.defaultBubbleAtlasId).toBeNull();
expect(result.bubblePacks.size).toBe(0);
});
});
/* ------------------------------------------------------------------ */
/* Validation errors */
/* ------------------------------------------------------------------ */
describe("scan — validation errors", () => {
it("errors on non-PNG file in state folder", async () => {
await makePng("states/idle/0.png");
await fs.writeFile(path.join(tmpDir, "states/idle/notes.txt"), "hello");
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("Unsupported file format"))).toBe(true);
});
it("errors on frame without number", async () => {
await makePng("states/idle/idle.png");
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("must contain a number"))).toBe(true);
});
it("errors on duplicate frame numbers", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/00.png");
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("Duplicate frame number"))).toBe(true);
});
it("errors on inconsistent frame sizes", async () => {
await makePng("states/idle/0.png", 16, 16);
await makePng("states/idle/1.png", 32, 32);
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("differs from"))).toBe(true);
});
it("errors on state folder without base frames", async () => {
await makePng("states/idle/look/t/0.png");
const result = await scan(tmpDir);
expect(result.errors.some(e => e.message.includes("has no base frames"))).toBe(true);
});
it("ignores system files (.DS_Store, Thumbs.db, dotfiles)", async () => {
await makePng("states/idle/0.png");
await fs.writeFile(path.join(tmpDir, "states/idle/.DS_Store"), "x");
await fs.writeFile(path.join(tmpDir, "states/idle/Thumbs.db"), "x");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.atlases.get("state_idle")?.frames.length).toBe(1);
});
});
/* ------------------------------------------------------------------ */
/* Folder name normalization */
/* ------------------------------------------------------------------ */
describe("scan — folder name normalization", () => {
it("warns on non-lowercase folder names and normalizes", async () => {
await makePng("states/Idle/0.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.warnings.some(w => w.includes("non-lowercase"))).toBe(true);
expect(result.states.has("idle")).toBe(true);
expect(result.states.has("Idle")).toBe(false);
});
it("normalizes look sector names", async () => {
await makePng("states/idle/0.png");
await makePng("states/idle/look/T/0.png");
const result = await scan(tmpDir);
expect(result.errors).toEqual([]);
expect(result.states.get("idle")?.lookSectors.has("t")).toBe(true);
});
});
@@ -0,0 +1,187 @@
import type { CharacterConfig } from "shimejic";
import { describe, expect, it } from "vitest";
import { validateGeneratedConfig } from "../validate";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
function makeValidConfig(): CharacterConfig {
return {
version: 1,
id: "cat",
initialState: "idle",
atlases: {
state_idle: {
url: "atlases/state_idle.abc12345.webp",
width: 32,
height: 32,
frames: {
"0.png": { x: 0, y: 0, w: 16, h: 16 },
"1.png": { x: 16, y: 0, w: 16, h: 16 },
},
},
},
states: {
idle: {
base: {
atlas: "state_idle",
frames: ["0.png", "1.png"],
framerate: 8,
loop: true,
},
},
},
bubbles: {},
};
}
/* ------------------------------------------------------------------ */
/* Pass-through verification */
/* ------------------------------------------------------------------ */
describe("validateGeneratedConfig — valid config", () => {
it("returns ok true and empty errors for a valid config", () => {
const result = validateGeneratedConfig(makeValidConfig());
expect(result.ok).toBe(true);
expect(result.errors).toEqual([]);
});
it("accepts config with look sectors", () => {
const config = makeValidConfig();
config.states.idle!.look = {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 50, max: 500 },
hysteresis: 2,
sectors: [
{
minAngle: 0,
maxAngle: 180,
folder: "r",
atlas: "state_idle",
frames: ["0.png", "1.png"],
},
],
};
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(true);
});
it("accepts config with per-sector distance overrides", () => {
const config = makeValidConfig();
config.states.idle!.look = {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 500 },
hysteresis: 1,
sectors: [
{
minAngle: 0,
maxAngle: 180,
folder: "r",
atlas: "state_idle",
frames: ["0.png", "1.png"],
minDistance: 200,
maxDistance: 400,
},
],
};
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(true);
});
it("accepts config with events and chatter", () => {
const config = makeValidConfig();
config.states.idle!.events = [
{
name: "sneeze",
atlas: "state_idle",
frames: ["0.png"],
framerate: 10,
chance: 0.4,
interval: [4, 10],
cooldown: 6,
weight: 1,
interrupt: "cut",
chatter: [{ at: 0, unit: "frame", text: "achoo!" }],
},
];
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(true);
});
});
describe("validateGeneratedConfig — invalid config", () => {
it("returns ok false when initialState is unknown", () => {
const config = makeValidConfig();
config.initialState = "nonexistent";
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(false);
expect(result.errors.some(e => e.path === "initialState")).toBe(true);
});
it("returns ok false when a frame reference is broken", () => {
const config = makeValidConfig();
config.states.idle!.base.frames = ["0.png", "missing.png"];
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(false);
expect(result.errors.some(e => e.path.includes("base.frames[1]"))).toBe(true);
});
it("returns ok false when a look sector frame count mismatches", () => {
const config = makeValidConfig();
config.states.idle!.look = {
pivot: { x: 0.5, y: 0.5 },
distance: { min: 0, max: 100 },
hysteresis: 1,
sectors: [
{
minAngle: 0,
maxAngle: 180,
folder: "r",
atlas: "state_idle",
frames: ["0.png"], // base has 2
},
],
};
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(false);
expect(result.errors.some(e => e.path.includes("sectors[0].frames"))).toBe(true);
});
it("returns ok false when a bubble lacks dimensions", () => {
const config = makeValidConfig();
config.bubbles.default = {
atlas: "state_idle",
frames: ["0.png"],
width: 0,
height: 100,
};
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(false);
expect(result.errors.some(e => e.path.includes("bubbles.default"))).toBe(true);
});
it("returns multiple errors when config has multiple problems", () => {
const config = makeValidConfig();
config.initialState = "nonexistent";
config.states.idle!.base.frames = ["missing.png"];
const result = validateGeneratedConfig(config);
expect(result.ok).toBe(false);
expect(result.errors.length).toBeGreaterThanOrEqual(2);
});
});
describe("validateGeneratedConfig — error shape", () => {
it("errors have path and message fields", () => {
const config = makeValidConfig();
config.initialState = "nonexistent";
const result = validateGeneratedConfig(config);
expect(result.errors.length).toBeGreaterThan(0);
for (const err of result.errors) {
expect(typeof err.path).toBe("string");
expect(typeof err.message).toBe("string");
expect(err.path.length).toBeGreaterThan(0);
expect(err.message.length).toBeGreaterThan(0);
}
});
});
@@ -0,0 +1,315 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import type { CharacterConfig } from "shimejic";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { EncodedAtlas } from "../encode.js";
import {
atlasFileExists,
atlasFilename,
atlasFilePath,
buildManifest,
cleanupOrphanAtlases,
readManifest,
writeAtlasFile,
writeConfigFile,
writeManifest,
type Manifest,
} from "../write.js";
/* ------------------------------------------------------------------ */
/* Fixtures */
/* ------------------------------------------------------------------ */
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "write-test-"));
});
afterEach(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
function makeManifest(): Manifest {
return {
version: 1,
characterId: "cat",
packerVersion: "0.1.0",
generatedAt: "2026-01-15T10:00:00Z",
atlases: {
state_idle: {
frameHash: "a".repeat(64),
atlasHash: "abc12345",
width: 32,
height: 32,
frames: 4,
bytes: 1024,
},
},
};
}
function makeConfig(atlasUrls: Record<string, string> = {}): CharacterConfig {
const atlases: Record<string, any> = {};
for (const [id, url] of Object.entries(atlasUrls)) {
atlases[id] = { url, width: 32, height: 32, frames: {} };
}
return {
version: 1,
id: "cat",
initialState: "idle",
atlases,
states: {},
bubbles: {},
};
}
function makeEncoded(hash = "abcdef12"): EncodedAtlas {
return {
bytes: Buffer.from([0, 1, 2, 3]),
frameHash: "f".repeat(64),
atlasHash: hash,
width: 64,
height: 64,
};
}
/* ------------------------------------------------------------------ */
/* Path helpers */
/* ------------------------------------------------------------------ */
describe("path helpers", () => {
it("atlasFilename composes id and hash", () => {
expect(atlasFilename("state_idle", "abc12345")).toBe("state_idle.abc12345.webp");
});
it("atlasFilePath puts filename under atlases/", () => {
const p = atlasFilePath("/out", "state_idle", "abc12345");
expect(p).toBe(path.join("/out", "atlases", "state_idle.abc12345.webp"));
});
});
/* ------------------------------------------------------------------ */
/* Manifest I/O */
/* ------------------------------------------------------------------ */
describe("readManifest", () => {
it("returns null when file does not exist", async () => {
expect(await readManifest(tmpDir)).toBeNull();
});
it("returns null on malformed JSON", async () => {
await fs.writeFile(path.join(tmpDir, "manifest.json"), "not json{");
expect(await readManifest(tmpDir)).toBeNull();
});
it("returns null on wrong version", async () => {
await fs.writeFile(path.join(tmpDir, "manifest.json"), JSON.stringify({ version: 2, atlases: {} }));
expect(await readManifest(tmpDir)).toBeNull();
});
it("returns null when atlases field is missing", async () => {
await fs.writeFile(path.join(tmpDir, "manifest.json"), JSON.stringify({ version: 1 }));
expect(await readManifest(tmpDir)).toBeNull();
});
it("returns parsed manifest for valid file", async () => {
const manifest = makeManifest();
await fs.writeFile(path.join(tmpDir, "manifest.json"), JSON.stringify(manifest));
const result = await readManifest(tmpDir);
expect(result).not.toBeNull();
expect(result?.characterId).toBe("cat");
expect(result?.atlases.state_idle?.atlasHash).toBe("abc12345");
});
});
describe("writeManifest", () => {
it("writes a valid manifest file", async () => {
await writeManifest(tmpDir, makeManifest());
const content = await fs.readFile(path.join(tmpDir, "manifest.json"), "utf8");
const parsed = JSON.parse(content) as Manifest;
expect(parsed.characterId).toBe("cat");
});
it("creates the output directory if missing", async () => {
const nested = path.join(tmpDir, "deep", "nested");
await writeManifest(nested, makeManifest());
const exists = await fs
.access(path.join(nested, "manifest.json"))
.then(() => true)
.catch(() => false);
expect(exists).toBe(true);
});
it("round-trips through readManifest", async () => {
const manifest = makeManifest();
await writeManifest(tmpDir, manifest);
const read = await readManifest(tmpDir);
expect(read?.atlases.state_idle?.frameHash).toBe(manifest.atlases.state_idle?.frameHash);
});
it("does not leave tmp files on success", async () => {
await writeManifest(tmpDir, makeManifest());
const entries = await fs.readdir(tmpDir);
expect(entries.every(e => !e.endsWith(".tmp"))).toBe(true);
});
});
/* ------------------------------------------------------------------ */
/* Atlas file writes */
/* ------------------------------------------------------------------ */
describe("writeAtlasFile", () => {
it("writes bytes to the expected path", async () => {
const bytes = Buffer.from([10, 20, 30]);
const filePath = await writeAtlasFile(tmpDir, "state_idle", "abc12345", bytes);
expect(filePath).toBe(path.join(tmpDir, "atlases", "state_idle.abc12345.webp"));
const read = await fs.readFile(filePath);
expect(read.equals(bytes)).toBe(true);
});
it("creates the atlases directory", async () => {
await writeAtlasFile(tmpDir, "state_idle", "abc12345", Buffer.from([1]));
const exists = await fs
.access(path.join(tmpDir, "atlases"))
.then(() => true)
.catch(() => false);
expect(exists).toBe(true);
});
it("does not leave tmp files", async () => {
await writeAtlasFile(tmpDir, "state_idle", "abc12345", Buffer.from([1]));
const entries = await fs.readdir(path.join(tmpDir, "atlases"));
expect(entries.every(e => !e.endsWith(".tmp"))).toBe(true);
});
});
describe("atlasFileExists", () => {
it("returns false when file does not exist", async () => {
expect(await atlasFileExists(tmpDir, "state_idle", "abc12345")).toBe(false);
});
it("returns true after writeAtlasFile", async () => {
await writeAtlasFile(tmpDir, "state_idle", "abc12345", Buffer.from([1]));
expect(await atlasFileExists(tmpDir, "state_idle", "abc12345")).toBe(true);
});
it("distinguishes different hashes", async () => {
await writeAtlasFile(tmpDir, "state_idle", "abc12345", Buffer.from([1]));
expect(await atlasFileExists(tmpDir, "state_idle", "def67890")).toBe(false);
});
});
/* ------------------------------------------------------------------ */
/* Config file writes */
/* ------------------------------------------------------------------ */
describe("writeConfigFile", () => {
it("writes character.json", async () => {
const config = makeConfig();
const filePath = await writeConfigFile(tmpDir, config);
expect(filePath).toBe(path.join(tmpDir, "character.json"));
const content = await fs.readFile(filePath, "utf8");
const parsed = JSON.parse(content);
expect(parsed.id).toBe("cat");
});
it("produces valid JSON that reparses cleanly", async () => {
const config = makeConfig({ state_idle: "atlases/state_idle.abc12345.webp" });
await writeConfigFile(tmpDir, config);
const content = await fs.readFile(path.join(tmpDir, "character.json"), "utf8");
const parsed = JSON.parse(content) as CharacterConfig;
expect(parsed.atlases.state_idle?.url).toBe("atlases/state_idle.abc12345.webp");
});
});
/* ------------------------------------------------------------------ */
/* Orphan cleanup */
/* ------------------------------------------------------------------ */
describe("cleanupOrphanAtlases", () => {
async function makeAtlasFile(filename: string): Promise<void> {
await fs.mkdir(path.join(tmpDir, "atlases"), { recursive: true });
await fs.writeFile(path.join(tmpDir, "atlases", filename), "fake");
}
it("deletes .webp files not in config", async () => {
await makeAtlasFile("state_idle.abc12345.webp");
await makeAtlasFile("state_idle.oldhash1.webp");
await makeAtlasFile("state_walk.def67890.webp");
const config = makeConfig({
state_idle: "atlases/state_idle.abc12345.webp",
});
const deleted = await cleanupOrphanAtlases(tmpDir, config);
expect(deleted.sort()).toEqual(["state_idle.oldhash1.webp", "state_walk.def67890.webp"].sort());
});
it("keeps all files when config matches", async () => {
await makeAtlasFile("state_idle.abc12345.webp");
const config = makeConfig({
state_idle: "atlases/state_idle.abc12345.webp",
});
const deleted = await cleanupOrphanAtlases(tmpDir, config);
expect(deleted).toEqual([]);
const exists = await fs
.access(path.join(tmpDir, "atlases", "state_idle.abc12345.webp"))
.then(() => true)
.catch(() => false);
expect(exists).toBe(true);
});
it("ignores non-.webp files", async () => {
await makeAtlasFile("state_idle.abc12345.webp");
await fs.writeFile(path.join(tmpDir, "atlases", "README.txt"), "hi");
const config = makeConfig({
state_idle: "atlases/state_idle.abc12345.webp",
});
const deleted = await cleanupOrphanAtlases(tmpDir, config);
expect(deleted).toEqual([]);
const readmeExists = await fs
.access(path.join(tmpDir, "atlases", "README.txt"))
.then(() => true)
.catch(() => false);
expect(readmeExists).toBe(true);
});
it("returns empty array when atlases directory does not exist", async () => {
const config = makeConfig();
const deleted = await cleanupOrphanAtlases(tmpDir, config);
expect(deleted).toEqual([]);
});
});
/* ------------------------------------------------------------------ */
/* buildManifest */
/* ------------------------------------------------------------------ */
describe("buildManifest", () => {
it("builds entries from encoded map", () => {
const encoded = new Map([["state_idle", makeEncoded("abc12345")]]);
const frameCounts = new Map([["state_idle", 4]]);
const manifest = buildManifest("cat", "0.1.0", encoded, frameCounts);
expect(manifest.version).toBe(1);
expect(manifest.characterId).toBe("cat");
expect(manifest.packerVersion).toBe("0.1.0");
expect(manifest.atlases.state_idle?.atlasHash).toBe("abc12345");
expect(manifest.atlases.state_idle?.frames).toBe(4);
expect(manifest.atlases.state_idle?.width).toBe(64);
expect(manifest.atlases.state_idle?.height).toBe(64);
expect(manifest.atlases.state_idle?.bytes).toBe(4);
});
it("handles missing frame counts gracefully", () => {
const encoded = new Map([["state_idle", makeEncoded()]]);
const manifest = buildManifest("cat", "0.1.0", encoded, new Map());
expect(manifest.atlases.state_idle?.frames).toBe(0);
});
it("produces an ISO timestamp", () => {
const manifest = buildManifest("cat", "0.1.0", new Map(), new Map());
expect(() => new Date(manifest.generatedAt)).not.toThrow();
expect(new Date(manifest.generatedAt).toString()).not.toBe("Invalid Date");
});
});
+14
View File
@@ -0,0 +1,14 @@
import { validateConfig as libraryValidate, type CharacterConfig, type ValidationError } from "shimejic";
export interface ValidateResult {
ok: boolean;
errors: ValidationError[];
}
export function validateGeneratedConfig(config: CharacterConfig): ValidateResult {
const errors = libraryValidate(config);
return {
ok: errors.length === 0,
errors,
};
}
+284
View File
@@ -0,0 +1,284 @@
/**
* write.ts — atomic filesystem writes for packed output.
*
* Responsibilities:
* 1. Read and write `manifest.json` — the idempotency record.
* 2. Write atlas files atomically (tmp + rename).
* 3. Write `character.json` atomically.
* 4. Delete orphaned atlas files whose hashes no longer appear in
* the current config.
* 5. Expose path helpers so the orchestrator can check whether an
* atlas file already exists without duplicating the naming
* convention.
*
* Does NOT compute hashes, does NOT decide what to write, does NOT
* know about scanning or encoding. The orchestrator calls these
* functions in a specific order once it knows what to produce.
*
* Atomic writes: every write goes to `<path>.tmp` first, then renames
* to the final path. POSIX rename is atomic within a filesystem, so a
* partial write can never produce a corrupt `character.json` or
* `manifest.json` — either the old content or the new content is
* visible, never a truncated mix.
*
* Orphan cleanup: after writing new files, any `.webp` in `atlases/`
* whose filename doesn't match a current config entry is deleted. This
* handles the case where an atlas was renamed or removed — the old
* hash-file lingers on disk until cleanup runs.
*/
import { promises as fs } from "node:fs";
import path from "node:path";
import type { CharacterConfig } from "shimejic";
import type { EncodedAtlas } from "./encode.js";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface AtlasManifestEntry {
/** Full SHA-256 of input frame bytes + positions. Used for idempotency. */
frameHash: string;
/** 8-char SHA-256 of encoded WebP bytes. Goes into the filename. */
atlasHash: string;
/** Encoded atlas width in pixels. */
width: number;
/** Encoded atlas height in pixels. */
height: number;
/** Number of source frames in this atlas. */
frames: number;
/** Encoded WebP byte size. Informational; useful for logging. */
bytes: number;
}
export interface Manifest {
version: 1;
characterId: string;
packerVersion: string;
/** ISO 8601 timestamp of when the manifest was generated. */
generatedAt: string;
atlases: Record<string, AtlasManifestEntry>;
}
/* ------------------------------------------------------------------ */
/* Path helpers */
/* ------------------------------------------------------------------ */
/** Filename for an atlas: `<atlasId>.<atlasHash>.webp`. */
export function atlasFilename(atlasId: string, atlasHash: string): string {
return `${atlasId}.${atlasHash}.webp`;
}
/** Absolute path to an atlas file inside `<outputDir>/atlases/`. */
export function atlasFilePath(outputDir: string, atlasId: string, atlasHash: string): string {
return path.join(outputDir, "atlases", atlasFilename(atlasId, atlasHash));
}
/** Absolute path to the config file. */
export function configFilePath(outputDir: string): string {
return path.join(outputDir, "character.json");
}
/** Absolute path to the manifest file. */
export function manifestFilePath(outputDir: string): string {
return path.join(outputDir, "manifest.json");
}
/** True if the atlas file already exists on disk. */
export async function atlasFileExists(outputDir: string, atlasId: string, atlasHash: string): Promise<boolean> {
try {
await fs.access(atlasFilePath(outputDir, atlasId, atlasHash));
return true;
} catch {
return false;
}
}
/* ------------------------------------------------------------------ */
/* Manifest */
/* ------------------------------------------------------------------ */
/**
* Read the previous manifest from `<outputDir>/manifest.json`.
* Returns null on any of: file missing, malformed JSON, wrong version,
* missing `atlases` field. Caller treats null as "no previous state,
* encode everything".
*/
export async function readManifest(outputDir: string): Promise<Manifest | null> {
const manifestPath = manifestFilePath(outputDir);
let content: string;
try {
content = await fs.readFile(manifestPath, "utf8");
} catch {
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(content);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const m = parsed as Partial<Manifest>;
if (m.version !== 1) return null;
if (typeof m.atlases !== "object" || m.atlases === null) return null;
return m as Manifest;
}
/**
* Write the manifest atomically to `<outputDir>/manifest.json`.
* Creates the output directory if it doesn't exist.
*/
export async function writeManifest(outputDir: string, manifest: Manifest): Promise<string> {
await fs.mkdir(outputDir, { recursive: true });
const target = manifestFilePath(outputDir);
const tmp = `${target}.tmp`;
try {
await fs.writeFile(tmp, JSON.stringify(manifest, null, 2), "utf8");
await fs.rename(tmp, target);
} catch (err) {
await cleanupTmp(tmp);
throw err;
}
return target;
}
/**
* Build a fresh manifest from the current run's outputs.
* `frameCounts` maps atlasId → number of source frames. Needed because
* `EncodedAtlas` doesn't carry the frame count (it's a source-side
* concept, not an encoded-side one).
*/
export function buildManifest(
characterId: string,
packerVersion: string,
encoded: Map<string, EncodedAtlas>,
frameCounts: Map<string, number>,
): Manifest {
const atlases: Record<string, AtlasManifestEntry> = {};
for (const [id, enc] of encoded) {
atlases[id] = {
frameHash: enc.frameHash,
atlasHash: enc.atlasHash,
width: enc.width,
height: enc.height,
frames: frameCounts.get(id) ?? 0,
bytes: enc.bytes.length,
};
}
return {
version: 1,
characterId,
packerVersion,
generatedAt: new Date().toISOString(),
atlases,
};
}
/* ------------------------------------------------------------------ */
/* Atlas files */
/* ------------------------------------------------------------------ */
/**
* Write an atlas WebP file atomically. Returns the absolute path written.
* Creates `<outputDir>/atlases/` if it doesn't exist.
*/
export async function writeAtlasFile(
outputDir: string,
atlasId: string,
atlasHash: string,
bytes: Buffer,
): Promise<string> {
const atlasDir = path.join(outputDir, "atlases");
await fs.mkdir(atlasDir, { recursive: true });
const target = atlasFilePath(outputDir, atlasId, atlasHash);
const tmp = `${target}.tmp`;
try {
await fs.writeFile(tmp, bytes);
await fs.rename(tmp, target);
} catch (err) {
await cleanupTmp(tmp);
throw err;
}
return target;
}
/* ------------------------------------------------------------------ */
/* Config file */
/* ------------------------------------------------------------------ */
/**
* Write `character.json` atomically. Returns the absolute path written.
*/
export async function writeConfigFile(outputDir: string, config: CharacterConfig): Promise<string> {
await fs.mkdir(outputDir, { recursive: true });
const target = configFilePath(outputDir);
const tmp = `${target}.tmp`;
try {
await fs.writeFile(tmp, JSON.stringify(config, null, 2), "utf8");
await fs.rename(tmp, target);
} catch (err) {
await cleanupTmp(tmp);
throw err;
}
return target;
}
/* ------------------------------------------------------------------ */
/* Orphan cleanup */
/* ------------------------------------------------------------------ */
/**
* Delete `.webp` files in `<outputDir>/atlases/` that don't appear in
* the current config's atlas URLs.
*
* Builds the expected filename set from `config.atlases[*].url` — the
* URL is `atlases/<id>.<hash>.webp`, so `path.basename(url)` yields the
* filename. Any file in `atlases/` whose name isn't in that set gets
* deleted.
*
* Returns the list of deleted filenames. Ignores files that fail to
* delete (permissions, already removed) and any non-.webp entries.
*/
export async function cleanupOrphanAtlases(outputDir: string, config: CharacterConfig): Promise<string[]> {
const atlasDir = path.join(outputDir, "atlases");
let entries: string[];
try {
entries = await fs.readdir(atlasDir);
} catch {
return [];
}
const expected = new Set<string>();
for (const atlas of Object.values(config.atlases)) {
expected.add(path.basename(atlas.url));
}
const deleted: string[] = [];
for (const entry of entries) {
if (!entry.endsWith(".webp")) continue;
if (expected.has(entry)) continue;
try {
await fs.unlink(path.join(atlasDir, entry));
deleted.push(entry);
} catch {
// Skip — file might have been removed between readdir and unlink
}
}
return deleted;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
async function cleanupTmp(tmpPath: string): Promise<void> {
try {
await fs.unlink(tmpPath);
} catch {
// Ignore — tmp may not exist if writeFile failed early
}
}
+2 -1
View File
@@ -10,5 +10,6 @@
"noEmit": false,
"allowImportingTsExtensions": false
},
"include": ["src"]
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
include: ["src/**/*.test.ts"],
environment: "node",
},
});