Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

13.7 KB
Raw Blame
#!/usr/bin/env node
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    asset-meta.js
 * @brief   Generate .meta sidecar files for assets (UUID v4 + importer defaults).
 *
 * Each asset file (texture, audio, prefab, scene, etc.) gets a JSON sidecar
 * `<file>.meta` with a stable UUID and type-appropriate importer defaults.
 * Already-present .meta files are never overwritten — the UUID is the stable
 * identity for scene/prefab references and must survive across runs.
 *
 * Usage:
 *   node tools/asset-meta.js <dir>...                        # generate missing metas
 *   node tools/asset-meta.js <dir> --dry-run                 # preview only
 *   node tools/asset-meta.js <dir> --check                   # exit 1 if any missing (CI)
 *   node tools/asset-meta.js <dir> --emit-manifest <out>     # also write runtime manifest
 *   node tools/asset-meta.js <dir> --verbose
 *
 * Exit codes:
 *   0  — success; all assets have meta (or --dry-run preview)
 *   1  — --check mode: one or more assets missing .meta
 *   2  — usage / IO error
 */

import { readdir, stat, readFile, writeFile, access, open } from 'node:fs/promises';
import { join, relative, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { parseArgs } from 'node:util';
import {
    EXT_TO_TYPE, metaTypeForExt, metaTypeForContent, needsContentType, CONTENT_SNIFF_BYTES, dataImporterForHead,
} from './assetMetaTable.js';

const META_VERSION = '2.0';

// Directories to skip when scanning.
const SKIP_DIRS = new Set([
    'node_modules', '.git', 'dist', 'build', 'out',
    '.cache', '.turbo', '.vscode', '__pycache__',
]);

// Files to skip (besides *.meta itself).
const SKIP_FILES = new Set([
    '.DS_Store', 'Thumbs.db', 'desktop.ini',
    '.gitkeep', '.gitignore', '.gitattributes',
]);

// File → `.meta` type is single-sourced in ./assetMetaTable.js (shared with the
// editor's mint door, desktop/electron/assetMeta.ts) — extension, name suffix,
// and the content sniff for the formats a name cannot type.

/**
 * Default `importer` settings per type. Shapes match the examples/ meta
 * files that existed before this tool landed; new types err on the side
 * of an empty object so future importer fields can be added additively.
 */
function getImporterDefaults(type) {
    switch (type) {
        case 'texture':
            return {
                maxSize: 2048,
                filterMode: 'linear',
                wrapMode: 'repeat',
                premultiplyAlpha: false,
                sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 },
            };
        case 'prefab':
        case 'scene':
            return { autoMigrate: true };
        case 'spine':
            return { defaultSkin: 'default', premultiplyAlpha: false, scale: 1 };
        case 'audio':
        case 'shader':
        case 'material':
        case 'timeline':
        case 'animation':
        case 'bitmapFont':
        case 'font':
        case 'tilemap':
        case 'tileset':
            return {};
        default:
            return {};
    }
}

/** The first `bytes` of a file as text, or '' if it can't be read. */
async function readHead(filePath, bytes) {
    let handle;
    try {
        handle = await open(filePath, 'r');
        const buf = Buffer.alloc(bytes);
        const { bytesRead } = await handle.read(buf, 0, bytes, 0);
        return buf.subarray(0, bytesRead).toString('utf8');
    } catch {
        return '';
    } finally {
        await handle?.close();
    }
}

/**
 * The asset type for a path on disk, or null if nothing can type it. The name
 * answers for almost everything; the formats it cannot type (Spine's JSON
 * skeleton is a plain `.json`) are typed by a marker in the file's head — the
 * same rule the editor's mint door applies.
 */
async function getAssetType(filePath) {
    const byName = metaTypeForExt(filePath);
    if (byName || !needsContentType(filePath)) return byName;
    return metaTypeForContent(filePath, await readHead(filePath, CONTENT_SNIFF_BYTES));
}

/** The first `bytes` of a file, or null if it can't be read. */
async function readHeadBytes(filePath, bytes) {
    let handle;
    try {
        handle = await open(filePath, 'r');
        const buf = Buffer.alloc(bytes);
        const { bytesRead } = await handle.read(buf, 0, bytes, 0);
        return buf.subarray(0, bytesRead);
    } catch {
        return null;
    } finally {
        await handle?.close();
    }
}

/** Builds the meta object (JSON-shape) for a given type; a texture file that is plainly numbers is adopted as Data. */
async function buildMeta(type, filePath) {
    const data = type === 'texture' && filePath ? dataImporterForHead(filePath, await readHeadBytes(filePath, 32)) : null;
    return {
        uuid: randomUUID(),
        version: META_VERSION,
        type,
        importer: data ?? getImporterDefaults(type),
    };
}

function formatMeta(meta) {
    return JSON.stringify(meta, null, 2) + '\n';
}

async function exists(path) {
    try {
        await access(path);
        return true;
    } catch {
        return false;
    }
}

async function* walk(dir) {
    const entries = await readdir(dir, { withFileTypes: true });
    for (const entry of entries) {
        const full = join(dir, entry.name);
        if (entry.isDirectory()) {
            if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
            yield* walk(full);
        } else if (entry.isFile()) {
            if (SKIP_FILES.has(entry.name) || entry.name.startsWith('.')) continue;
            if (entry.name.endsWith('.meta')) continue;
            yield full;
        }
    }
}

/**
 * Scan `dir` recursively and generate .meta files for any asset that
 * doesn't already have one. Returns a summary.
 *
 * Options:
 *   dryRun  — don't write files
 *   check   — collect missing but also don't write (for CI)
 *   verbose — log every skip and every create
 *   onCreate(absPath, meta) — optional callback per created meta
 */
export async function generateMetaForDir(dir, options = {}) {
    const { dryRun = false, check = false, verbose = false, onCreate } = options;
    const root = resolve(dir);

    try {
        const s = await stat(root);
        if (!s.isDirectory()) {
            throw new Error(`Not a directory: ${root}`);
        }
    } catch (err) {
        throw new Error(`Cannot read directory "${root}": ${err.message}`);
    }

    const created = [];
    const alreadyPresent = [];
    const skipped = [];

    for await (const filePath of walk(root)) {
        const type = await getAssetType(filePath);
        if (type === null) {
            if (verbose) skipped.push({ path: filePath, reason: 'unknown extension' });
            continue;
        }

        const metaPath = filePath + '.meta';
        if (await exists(metaPath)) {
            alreadyPresent.push({ path: filePath, metaPath });
            continue;
        }

        const meta = await buildMeta(type, filePath);
        created.push({ path: filePath, metaPath, meta });

        if (!dryRun && !check) {
            await writeFile(metaPath, formatMeta(meta), 'utf8');
            if (onCreate) await onCreate(metaPath, meta);
        }
    }

    return { root, created, alreadyPresent, skipped };
}

function printSummary(results, { verbose, dryRun, check }) {
    let totalCreated = 0;
    let totalPresent = 0;
    let totalSkipped = 0;

    for (const r of results) {
        const rel = (p) => relative(process.cwd(), p) || '.';
        totalCreated += r.created.length;
        totalPresent += r.alreadyPresent.length;
        totalSkipped += r.skipped.length;

        if (verbose) {
            for (const s of r.skipped) {
                console.log(`  skip:    ${rel(s.path)}  (${s.reason})`);
            }
            for (const p of r.alreadyPresent) {
                console.log(`  exists:  ${rel(p.metaPath)}`);
            }
        }

        for (const c of r.created) {
            const prefix = dryRun || check ? '  would:  ' : '  wrote:  ';
            console.log(`${prefix}${rel(c.metaPath)}  (type: ${c.meta.type}, uuid: ${c.meta.uuid})`);
        }
    }

    const verb = dryRun ? 'would create' : check ? 'missing' : 'created';
    console.log(
        `\n${verb}: ${totalCreated}` +
        `  |  already present: ${totalPresent}` +
        (verbose ? `  |  skipped (unknown ext): ${totalSkipped}` : ''),
    );
}

/**
 * Scan every `.meta` sidecar under `dir` and collect their contents
 * as AssetManifest entries keyed by path relative to `dir`.
 */
export async function buildManifest(dir, options = {}) {
    const { manifestBase } = options;
    const root = resolve(dir);
    const base = manifestBase ? resolve(manifestBase) : root;

    const entries = [];
    const warnings = [];

    for await (const filePath of walk(root)) {
        const type = await getAssetType(filePath);
        if (type === null) continue;

        const metaPath = filePath + '.meta';
        if (!(await exists(metaPath))) continue;

        let raw;
        try {
            raw = await readFile(metaPath, 'utf8');
        } catch (err) {
            warnings.push({ metaPath, reason: `read failed: ${err.message}` });
            continue;
        }

        let meta;
        try {
            meta = JSON.parse(raw);
        } catch (err) {
            warnings.push({ metaPath, reason: `malformed JSON: ${err.message}` });
            continue;
        }

        if (!meta || typeof meta.uuid !== 'string' || !meta.type) {
            warnings.push({ metaPath, reason: 'missing uuid or type' });
            continue;
        }

        // Manifest paths are relative + forward-slashed so the runtime
        // (web / wechat) can treat them as URL-ish without OS-specific
        // backslash handling.
        const relPath = relative(base, filePath).replace(/\\/g, '/');

        entries.push({
            uuid: meta.uuid,
            path: relPath,
            type: meta.type,
            importer: meta.importer ?? {},
        });
    }

    entries.sort((a, b) => a.path.localeCompare(b.path));

    return { manifest: { version: '1.0', entries }, warnings };
}

async function emitManifest(outPath, dirs, manifestBase) {
    const allEntries = [];
    const allWarnings = [];
    for (const dir of dirs) {
        const { manifest, warnings } = await buildManifest(dir, { manifestBase });
        allEntries.push(...manifest.entries);
        allWarnings.push(...warnings);
    }

    // Detect UUID collisions across scanned dirs — caller almost certainly
    // wants to know.
    const byUuid = new Map();
    const collisions = [];
    for (const e of allEntries) {
        const prior = byUuid.get(e.uuid);
        if (prior) collisions.push({ uuid: e.uuid, a: prior.path, b: e.path });
        else byUuid.set(e.uuid, e);
    }

    if (collisions.length > 0) {
        console.error('\nUUID collision(s) detected:');
        for (const c of collisions) {
            console.error(`  ${c.uuid}: ${c.a}  vs  ${c.b}`);
        }
    }
    if (allWarnings.length > 0) {
        console.warn('\nWarnings:');
        for (const w of allWarnings) console.warn(`  ${w.metaPath}  — ${w.reason}`);
    }

    const manifest = { version: '1.0', entries: allEntries };
    await writeFile(outPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
    console.log(`\nwrote manifest: ${outPath}  (${allEntries.length} entries)`);

    return collisions.length === 0;
}

async function main() {
    const { values, positionals } = parseArgs({
        options: {
            'dry-run':        { type: 'boolean', default: false },
            'check':          { type: 'boolean', default: false },
            'verbose':        { type: 'boolean', short: 'v', default: false },
            'help':           { type: 'boolean', short: 'h', default: false },
            'emit-manifest':  { type: 'string' },
            'manifest-base':  { type: 'string' },
        },
        allowPositionals: true,
    });

    if (values.help || positionals.length === 0) {
        console.log(`Usage: node tools/asset-meta.js <dir>... [options]

Options:
  --dry-run                  Show what would be created, write nothing
  --check                    Exit 1 if any asset is missing .meta (CI mode)
  --emit-manifest <file>     After generating, write AssetManifest JSON here
  --manifest-base <dir>      Base dir for manifest paths (default: scanned dir)
  -v, --verbose              Log every asset considered
  -h, --help                 Show this help`);
        process.exit(values.help ? 0 : 2);
    }

    const results = [];
    for (const dir of positionals) {
        try {
            results.push(await generateMetaForDir(dir, {
                dryRun: values['dry-run'],
                check: values.check,
                verbose: values.verbose,
            }));
        } catch (err) {
            console.error(`error: ${err.message}`);
            process.exit(2);
        }
    }

    printSummary(results, {
        verbose: values.verbose,
        dryRun: values['dry-run'],
        check: values.check,
    });

    if (values.check) {
        const anyMissing = results.some(r => r.created.length > 0);
        if (anyMissing) process.exit(1);
    }

    if (values['emit-manifest']) {
        const ok = await emitManifest(
            values['emit-manifest'],
            positionals,
            values['manifest-base'],
        );
        if (!ok) process.exit(1);
    }
}

// Run as CLI when invoked directly; skip when imported as a module.
const isMain = import.meta.url === `file://${process.argv[1]}`
    || import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/'));
if (isMain) {
    main().catch(err => {
        console.error(err);
        process.exit(2);
    });
}

// Exports for reuse (e.g., migration script).
export { EXT_TO_TYPE, META_VERSION, getAssetType, getImporterDefaults, buildMeta };