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.

29.0 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
//
// The platform catalog: what the Package dialog can offer, and whether each
// target can actually run. Two behaviours worth pinning down —
//
//   1. Readiness is a PROBE, not a constant. The dialog used to carry static
//      "requires the X runtime" prose that was true whether or not you had built
//      it (and, for playable, was simply wrong).
//   2. A project can add a platform the editor never heard of, and a broken one
//      must not take the dialog down with it.
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import {
  listPlatforms, loadProjectPlatform, createProjectPlatform, PROJECT_PLATFORM_DIR,
  listPlayableNetworks, loadPlayableProfile,
} from '../src/export/platformCatalog';
import { BUILTIN_PLATFORMS, compileTargetFor } from '../src/project/platforms';

let root: string;
let webDir: string;
let wxDir: string;

/** The editor version the probes run as. A native runtime template is matched
 *  against it exactly, so the tests own both ends of that comparison. */
const VERSION = '9.9.9';

const dirs = () => ({ web: webDir, minigame: wxDir, quickgame: path.join(wxDir, '..', 'qg') });

/** The catalog with the machine facts this file owns. A machine with NEITHER
 *  compiler is deliberate: a project that marks nothing `@compiled` must be
 *  told it needs no toolchain, which is the half of that rule a machine that
 *  happens to have one cannot check. */
const NONE = { emcc: null, cc: null };
const platforms = (r: string | null) => listPlatforms(r, dirs(), VERSION, NONE);

function writePlatform(name: string, source: string): void {
  const dir = path.join(root, PROJECT_PLATFORM_DIR);
  mkdirSync(dir, { recursive: true });
  writeFileSync(path.join(dir, name), source);
}

beforeEach(() => {
  root = mkdtempSync(path.join(tmpdir(), 'es-platcat-'));
  webDir = path.join(root, 'rt-web');
  wxDir = path.join(root, 'rt-wechat');
  mkdirSync(webDir, { recursive: true });
  mkdirSync(wxDir, { recursive: true });
  // The native probes read the machine's template store; point it at this test's
  // own empty one, or the result would depend on what the developer has installed.
  process.env.ESTELLA_NATIVE_TEMPLATES = path.join(root, 'templates');
});

afterEach(() => {
  delete process.env.ESTELLA_NATIVE_TEMPLATES;
  rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
});

describe('listPlatforms — built-in readiness is probed', () => {
  it('web/desktop/playable are not ready without the web engine glue', async () => {
    const rows = await platforms(root);
    const byId = Object.fromEntries(rows.map((r) => [r.id, r]));

    expect(byId.web.ready).toBe(false);
    expect(byId.desktop.ready).toBe(false);
    expect(byId.playable.ready).toBe(false);
    expect((byId.web.prereq as { command?: string } | undefined)?.command).toContain('build -t web');
  });

  it('the web glue makes playable ready too — it inlines the WEB runtime, not a -t playable one', async () => {
    writeFileSync(path.join(webDir, 'esengine.js'), '//');
    const rows = await platforms(root);
    const byId = Object.fromEntries(rows.map((r) => [r.id, r]));

    expect(byId.web.ready).toBe(true);
    expect(byId.playable.ready).toBe(true);
    expect(byId.playable.prereq).toBeUndefined();
    // WeChat has its own runtime and is unaffected by the web one.
    expect(byId.wechat.ready).toBe(false);
    expect((byId.wechat.prereq as { command?: string } | undefined)?.command).toContain('build -t wechat');
  });

  it('WeChat accepts either its own glue or a web-aligned one', async () => {
    writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
    expect((await platforms(root)).find((r) => r.id === 'wechat')?.ready).toBe(true);

    rmSync(path.join(wxDir, 'esengine.wxgame.js'));
    writeFileSync(path.join(wxDir, 'esengine.js'), '//');
    expect((await platforms(root)).find((r) => r.id === 'wechat')?.ready).toBe(true);
  });

  it('answers for every mini-game vendor from the one engine build they share', async () => {
    // One build, one probe: a vendor with no probe of its own reports ready and
    // then exports a package with an engine it cannot load.
    expect((await platforms(root)).find((r) => r.id === 'douyin')?.ready).toBe(false);
    writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
    const rows = await platforms(root);
    expect(rows.find((r) => r.id === 'douyin')?.ready).toBe(true);
    expect(rows.find((r) => r.id === 'wechat')?.ready).toBe(true);
  });

  it('reports paths with forward slashes, whatever the platform separator', async () => {
    const wx = (await platforms(root)).find((r) => r.id === 'wechat');
    expect((wx?.prereq as { dir?: string } | undefined)?.dir).not.toContain('\\');
  });
});

describe('listPlatforms — platforms the project defines', () => {
  it('finds a profile and lifts its display data', async () => {
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'ACME Play', blurb: 'ACME package.', defaultOut: 'dist-acme',
      emitConfigFiles: () => [{ file: 'game.json', content: '{}' }],
    };`);
    writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');

    const rows = await platforms(root);
    const acme = rows.find((r) => r.id === 'acme');
    expect(acme).toBeDefined();
    expect(acme!.source).toBe('project');
    expect(acme!.label).toBe('ACME Play');
    expect(acme!.defaultOut).toBe('dist-acme');
    // No wasmDir of its own → the mini-game runtime, which exists here.
    expect(acme!.ready).toBe(true);
  });

  it('probes the profile\'s own runtime dir when it names one', async () => {
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'ACME Play', wasmDir: 'build/wasm/acme',
      emitConfigFiles: () => [],
    };`);
    writeFileSync(path.join(webDir, 'esengine.js'), '//');

    const acme = (await platforms(root)).find((r) => r.id === 'acme');
    expect(acme!.ready).toBe(false);
    expect((acme!.prereq as { dir?: string } | undefined)?.dir).toBe('build/wasm/acme');
    // The editor does not know how a project builds its own runtime, so it
    // reports where it looked and offers no command.
    expect((acme!.prereq as { command?: string } | undefined)?.command).toBeUndefined();
  });

  it('a broken profile is listed with its error, not silently dropped', async () => {
    writePlatform('bad.mjs', 'export default { this is not valid javascript');
    const rows = await platforms(root);
    const bad = rows.find((r) => r.id === 'bad');
    expect(bad).toBeDefined();
    expect(bad!.ready).toBe(false);
    expect(bad!.error).toBeTruthy();
    // Every built-in still came through.
    expect(rows.filter((r) => r.source === 'builtin').map((r) => r.id)).toEqual([...BUILTIN_PLATFORMS]);
  });

  it('rejects a profile that shadows a built-in, or has no id/label/emitter', async () => {
    writePlatform('a.mjs', `export default { id: 'wechat', label: 'Fake', emitConfigFiles: () => [] };`);
    writePlatform('b.mjs', `export default { id: 'Bad Id', label: 'X', emitConfigFiles: () => [] };`);
    writePlatform('c.mjs', `export default { id: 'ok-id', emitConfigFiles: () => [] };`);
    writePlatform('d.mjs', `export default { id: 'ok-id2', label: 'X' };`);

    const rows = await platforms(root);
    const errs = rows.filter((r) => r.source === 'project').map((r) => r.error);
    expect(errs).toHaveLength(4);
    expect(errs[0]).toContain('built-in');
    expect(errs[1]).toContain('lowercase');
    expect(errs[2]).toContain('label');
    expect(errs[3]).toContain('emitConfigFiles');
    // The real WeChat row is untouched by the impostor.
    expect(rows.filter((r) => r.id === 'wechat' && r.source === 'builtin')).toHaveLength(1);
  });

  it('lists only built-ins when no project is open', async () => {
    const rows = await platforms(null);
    expect(rows.every((r) => r.source === 'builtin')).toBe(true);
  });
});

describe('createProjectPlatform — scaffolding', () => {
  it('writes both halves, already joined, and the result is discoverable', async () => {
    const res = await createProjectPlatform(root, 'acme-play', 'ACME Play', 'src');
    expect(res.ok).toBe(true);
    expect(res.packagingFile).toBe('.esengine/platforms/acme-play.mjs');
    expect(res.runtimeFile).toBe('src/platforms/acme-play.runtime.ts');
    // Reported with forward slashes, like every other path the dialog shows.
    expect(res.packagingFile).not.toContain('\\');

    const packaging = readFileSync(path.join(root, res.packagingFile!), 'utf8');
    const runtime = readFileSync(path.join(root, res.runtimeFile!), 'utf8');
    // THE JOIN: the packaging half names the runtime half.
    expect(packaging).toContain(`runtimeProfile: 'src/platforms/acme-play.runtime.ts'`);
    expect(runtime).toContain(`id: 'acme-play'`);
    expect(runtime).toContain(`hostLabel: 'ACME Play'`);
    // The overrides a vendor might want are present as guidance, commented out.
    expect(runtime).toContain('createVideoBackend');
    expect(runtime).toContain('instantiateWasm');

    // What was scaffolded is immediately a real platform.
    writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
    const rows = await platforms(root);
    const acme = rows.find((r) => r.id === 'acme-play');
    expect(acme?.source).toBe('project');
    expect(acme?.label).toBe('ACME Play');
    expect(acme?.error).toBeUndefined();
    expect(acme?.ready).toBe(true);

    // And it loads into a complete export profile.
    const loaded = await loadProjectPlatform(root, 'acme-play', dirs());
    expect(loaded!.profile.runtimeProfileModule).toBe(path.join(root, 'src', 'platforms', 'acme-play.runtime.ts'));
    expect(loaded!.defaultOut).toBe('dist-acme-play');
    expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', versionCode: 1, icon: null, orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })[0].file)
      .toBe('game.json');
  });

  it('refuses an id that shadows a built-in or is malformed', async () => {
    expect((await createProjectPlatform(root, 'wechat', 'Fake', 'src')).error).toContain('built-in');
    expect((await createProjectPlatform(root, 'Bad Id', 'X', 'src')).error).toContain('lowercase');
    expect((await createProjectPlatform(root, 'ok-id', '  ', 'src')).error).toContain('label');
  });

  it('never clobbers an existing platform, or a runtime half already written', async () => {
    await createProjectPlatform(root, 'acme', 'ACME', 'src');
    const runtimeAbs = path.join(root, 'src', 'platforms', 'acme.runtime.ts');
    writeFileSync(runtimeAbs, 'export default { mine: true };');

    const again = await createProjectPlatform(root, 'acme', 'ACME', 'src');
    expect(again.ok).toBe(false);
    expect(again.error).toContain('already exists');
    expect(readFileSync(runtimeAbs, 'utf8')).toBe('export default { mine: true };');
  });
});

describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {
  it('merges over the family defaults, so a minimal profile is complete', async () => {
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'ACME Play',
      emitConfigFiles: (ctx) => [{ file: 'game.json', content: JSON.stringify({ t: ctx.title }) }],
    };`);

    const loaded = await loadProjectPlatform(root, 'acme', dirs());
    expect(loaded).not.toBeNull();
    const p = loaded!.profile;

    // Supplied by the project.
    expect(p.id).toBe('acme');
    // Defaulted — a standard mini-game host needs none of these spelled out.
    expect(p.sdkEntryFile).toBe('index.minigame.js');
    expect(p.runtimeInit).toBe('initMiniGameRuntime');
    // The engine build every mini-game host takes, under either of its names —
    // NOT the browser artifact, which a `require` cannot even parse.
    expect(p.engineGlueCandidates).toEqual(['esengine.wxgame.js', 'esengine.js']);
    expect(p.esTarget).toBe('es2017');
    expect(p.subpackageDir).toBe('subpackages');
    expect(typeof p.emitEntry).toBe('function');

    // The default entry is the same CommonJS shape WeChat ships.
    const entry = p.emitEntry({ sideModules: [{ id: 'physics', file: 'physics' }], engineGlueFile: 'esengine.js', runtimeDir: 'wasm', engineSubpackage: null, hostGlobal: 'wx' });
    expect(entry).toContain("require('./wasm/esengine.js')");
    expect(entry).toContain(`"physics": asFactory(require('./wasm/physics.js'))`);
    expect(entry).toContain("require('./game-bundle.js')");

    // The shared entry carries no vendor's API name: the host global is a profile
    // fact, so a 分包 is asked for through whichever object that vendor exposes.
    const wxEntry = p.emitEntry({
      sideModules: [], engineGlueFile: 'esengine.js', runtimeDir: 'wasm',
      engineSubpackage: 'engine', hostGlobal: 'wx',
    });
    expect(wxEntry).toContain('= wx;');
    const ttEntry = p.emitEntry({
      sideModules: [], engineGlueFile: 'esengine.js', runtimeDir: 'wasm',
      engineSubpackage: 'engine', hostGlobal: 'tt',
    });
    expect(ttEntry).toContain('= tt;');
    expect(ttEntry).not.toContain('wx');

    // And the project's own emitter is what runs for config.
    expect(p.emitConfigFiles({ title: 'T', appid: '', version: '1.0.0', versionCode: 1, icon: null, orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' }))
      .toEqual([{ file: 'game.json', content: '{"t":"T"}' }]);
  });

  // A project's own vendor is a mini-game host like the built-in ones, so saying
  // nothing gets it their engine build — the browser one is an ES module its
  // package cannot require at all.
  it('resolves wasmDir against the project root, defaulting to the mini-game runtime', async () => {
    writePlatform('a.mjs', `export default { id: 'a', label: 'A', wasmDir: 'rt/a', emitConfigFiles: () => [] };`);
    writePlatform('b.mjs', `export default { id: 'b', label: 'B', emitConfigFiles: () => [] };`);

    expect((await loadProjectPlatform(root, 'a', dirs()))!.wasmDir).toBe(path.join(root, 'rt', 'a'));
    expect((await loadProjectPlatform(root, 'b', dirs()))!.wasmDir).toBe(wxDir);
    expect((await loadProjectPlatform(root, 'b', dirs()))!.defaultOut).toBe('dist-b');
  });

  // A vendor has two halves: the .mjs describes packaging, a runtime module
  // describes the host (and any capability it replaces — its own video decoder,
  // audio backend, socket). Naming the second from the first is what joins them,
  // and the generated entry installs it before booting.
  it('resolves the runtime half to an absolute module path', async () => {
    mkdirSync(path.join(root, 'src'), { recursive: true });
    writeFileSync(path.join(root, 'src', 'acme-runtime.ts'), 'export default {};');
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'ACME Play', runtimeProfile: 'src/acme-runtime.ts',
      emitConfigFiles: () => [],
    };`);

    const loaded = await loadProjectPlatform(root, 'acme', dirs());
    expect(loaded!.profile.runtimeProfileModule).toBe(path.join(root, 'src', 'acme-runtime.ts'));
  });

  it('leaves runtimeProfileModule undefined when the project installs its own platform', async () => {
    writePlatform('acme.mjs', `export default { id: 'acme', label: 'A', emitConfigFiles: () => [] };`);
    const loaded = await loadProjectPlatform(root, 'acme', dirs());
    expect(loaded!.profile.runtimeProfileModule).toBeUndefined();
  });

  it('flags a runtime half that points nowhere, instead of shipping a broken import', async () => {
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'ACME Play', runtimeProfile: 'src/missing.ts',
      emitConfigFiles: () => [],
    };`);
    const acme = (await platforms(root)).find((r) => r.id === 'acme');
    expect(acme!.ready).toBe(false);
    expect(acme!.error).toContain('runtimeProfile');
  });

  it('accepts a runtime half written without its extension', async () => {
    mkdirSync(path.join(root, 'src'), { recursive: true });
    writeFileSync(path.join(root, 'src', 'rt.ts'), 'export default {};');
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'A', runtimeProfile: 'src/rt', emitConfigFiles: () => [],
    };`);
    writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
    const acme = (await platforms(root)).find((r) => r.id === 'acme');
    expect(acme!.error).toBeUndefined();
    expect(acme!.ready).toBe(true);
  });

  // A cap nobody can see until the package exists is a cap nobody builds
  // against, so the row carries the vendor's own — the built-ins' come from
  // sizeBudget.ts, which the dialog reads directly.
  it('carries the caps a project vendor declared, so the dialog can state them', async () => {
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'A', emitConfigFiles: () => [],
      sizeBudgets: [{ scope: 'initial', maxBytes: 3145728, note: 'ACME caps the main package at 3MB' }],
    };`);
    const acme = (await platforms(root)).find((r) => r.id === 'acme');
    expect(acme?.sizeBudgets).toEqual([
      { scope: 'initial', maxBytes: 3145728, note: 'ACME caps the main package at 3MB' },
    ]);
  });

  it('is null for a built-in id, so the built-in pipeline keeps it', async () => {
    expect(await loadProjectPlatform(root, 'wechat', dirs())).toBeNull();
    expect(await loadProjectPlatform(root, 'nope', dirs())).toBeNull();
  });
});

// A playable ad network is a variant of the built-in `playable` target, not a rival
// platform: it is chosen inside that target, and a project-defined one must reach the
// export through exactly the path a built-in does.
describe('playable ad networks', () => {
  it('lists the built-ins, then the project\'s own', async () => {
    writePlatform('acme-ads.mjs', `export default {
      id: 'acme-ads', kind: 'playable', label: 'Acme Ads',
      maxBytes: 3145728, limitNote: 'Acme docs say 3MB',
    };`);
    const rows = await listPlayableNetworks(root);
    expect(rows.filter((r) => r.source === 'builtin').map((r) => r.id))
      .toEqual(['generic', 'meta', 'google', 'mraid', 'unity', 'applovin', 'mintegral', 'tiktok', 'pangle']);
    // A project network names the file that defines it, so the dialog can point at it
    // (and at the error, when one fails to load). Built-ins have no file.
    expect(rows.find((r) => r.id === 'acme-ads')).toMatchObject({
      label: 'Acme Ads', source: 'project', file: '.esengine/platforms/acme-ads.mjs',
    });
    expect(rows.find((r) => r.id === 'meta')!.file).toBeUndefined();
  });

  it('resolves a project network to a profile the export can run with', async () => {
    writePlatform('acme-ads.mjs', `export default {
      id: 'acme-ads', kind: 'playable', label: 'Acme Ads',
      maxBytes: 3145728, limitNote: 'Acme docs say 3MB',
      emitHead: (ctx) => '<meta name="acme" content="' + ctx.orientation + '">',
      emitBridge: () => 'window.__ESTELLA_PLAYABLE__={cta:function(){}};',
    };`);
    const profile = await loadPlayableProfile(root, 'acme-ads');
    expect(profile).toMatchObject({ id: 'acme-ads', maxBytes: 3145728 });
    expect(profile!.emitHead!({ title: 'T', orientation: 'portrait' })).toBe('<meta name="acme" content="portrait">');
    expect(profile!.emitBridge!({ title: 'T', orientation: 'portrait' })).toContain('__ESTELLA_PLAYABLE__');
  });

  it('resolves the built-ins, and nothing for an unknown id', async () => {
    expect((await loadPlayableProfile(root, 'meta'))!.emitBridge!({ title: 'T', orientation: 'landscape' }))
      .toContain('FbPlayableAd.onCTAClick');
    // Google's exit API must be a LITERAL head script (its docs forbid injecting it
    // from JS), and its upload is a ZIP this export does not produce — hence the note.
    const google = (await loadPlayableProfile(root, 'google'))!;
    expect(google.emitHead!({ title: 'T', orientation: 'portrait' }))
      .toContain('<script src="https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js"></script>');
    expect(google.emitHead!({ title: 'T', orientation: 'portrait' })).toContain('content="portrait"');
    expect(google.emitBridge!({ title: 'T', orientation: 'portrait' })).toContain('ExitApi.exit');
    // Google takes an archive, and the export writes one for it.
    expect(google.delivery).toBe('zip');
    // The MRAID family clicks through with mraid.open() and needs nothing in head —
    // the host webview injects mraid itself.
    for (const id of ['mraid', 'unity', 'applovin']) {
      const p = (await loadPlayableProfile(root, id))!;
      expect(p.emitBridge!({ title: 'T', orientation: 'landscape' })).toContain('mraid.open(');
      expect(p.emitHead).toBeUndefined();
    }
    // No selection ⇒ generic, so a project that never chose still exports.
    expect((await loadPlayableProfile(root, undefined))!.id).toBe('generic');
    // An id naming nothing is NOT silently generic — the caller reports it.
    expect(await loadPlayableProfile(root, 'nope')).toBeNull();
  });

  it('carries a project profile\'s zip delivery through to the export', async () => {
    writePlatform('zipnet.mjs', `export default {
      id: 'zipnet', kind: 'playable', label: 'Zip Net',
      maxBytes: 5242880, limitNote: 'Zip Net docs', delivery: 'zip',
      deliveryNote: 'name the archive after the campaign',
    };`);
    const profile = await loadPlayableProfile(root, 'zipnet');
    expect(profile).toMatchObject({ delivery: 'zip', deliveryNote: 'name the archive after the campaign' });
  });

  it('rejects a delivery mode that is neither shape', async () => {
    writePlatform('oddnet.mjs', `export default {
      id: 'oddnet', kind: 'playable', label: 'Odd Net',
      maxBytes: 1, limitNote: 'x', delivery: 'tarball',
    };`);
    const row = (await listPlayableNetworks(root)).find((r) => r.id === 'oddnet');
    expect(row!.error).toMatch(/delivery/);
  });

  it('rejects ZIP filenames that escape the export directory', async () => {
    writePlatform('unsafe-zip.mjs', `export default {
      id: 'unsafe-zip', kind: 'playable', label: 'Unsafe ZIP', maxBytes: 100, limitNote: 'x',
      delivery: 'zip', zipFileName: '../escape.zip',
    };`);
    const row = (await listPlayableNetworks(root)).find((r) => r.id === 'unsafe-zip');
    expect(row!.error).toMatch(/zipFileName/);
  });

  it('rejects an invalid mandatory SDK policy before exporting', async () => {
    writePlatform('bad-sdk-policy.mjs', `export default {
      id: 'bad-sdk-policy', kind: 'playable', label: 'Bad SDK policy', maxBytes: 100, limitNote: 'x',
      requiredSdk: { url: 'https://example.com/sdk.js', placement: 'anywhere' }
    };`);
    const row = (await listPlayableNetworks(root)).find(r => r.id === 'bad-sdk-policy');
    expect(row!.error).toMatch(/requiredSdk/);
  });

  it('reports malformed host hooks before attempting export', async () => {
    writePlatform('bad-hook.mjs', `export default {
      id: 'bad-hook', kind: 'playable', label: 'Bad Hook', maxBytes: 100, limitNote: 'x', emitZipFiles: 'config.json'
    };`);
    const row = (await listPlayableNetworks(root)).find(r => r.id === 'bad-hook');
    expect(row!.error).toMatch(/emitZipFiles.*function/);
  });

  it('rejects a playable profile missing the facts the warning needs', async () => {
    writePlatform('bad.mjs', "export default { id: 'bad', kind: 'playable', label: 'Bad' };");
    const row = (await listPlayableNetworks(root)).find((r) => r.id === 'bad');
    expect(row!.error).toMatch(/maxBytes/);
    // Named WITH its file — an error you cannot locate is barely an error report.
    expect(row!.file).toBe('.esengine/platforms/bad.mjs');
  });

  it('keeps networks out of the platform list, and platforms out of the network list', async () => {
    writePlatform('acme-ads.mjs', `export default {
      id: 'acme-ads', kind: 'playable', label: 'Acme Ads', maxBytes: 100, limitNote: 'x',
    };`);
    writePlatform('acme-mini.mjs', `export default {
      id: 'acme-mini', label: 'Acme MiniGame', emitConfigFiles: () => [],
    };`);
    expect((await platforms(root)).map((r) => r.id)).not.toContain('acme-ads');
    expect((await listPlayableNetworks(root)).map((r) => r.id)).not.toContain('acme-mini');
    // And a network id must not shadow a network the editor ships.
    writePlatform('meta.mjs', "export default { id: 'meta', kind: 'playable', label: 'Mine', maxBytes: 1, limitNote: 'x' };");
    expect((await listPlayableNetworks(root)).find((r) => r.label === 'Mine')).toBeUndefined();
  });

  it('scaffolds a playable network as one file (the host is still the browser)', async () => {
    const res = await createProjectPlatform(root, 'acme-ads', 'Acme Ads', 'src', 'playable');
    expect(res.ok).toBe(true);
    expect(res.runtimeFile).toBeUndefined();
    const written = readFileSync(path.join(root, res.packagingFile!), 'utf8');
    expect(written).toContain("kind: 'playable'");
    expect(written).toContain('__ESTELLA_PLAYABLE__');
    // The scaffold must satisfy its own contract, or the first export after
    // scaffolding reports an error the developer did not write.
    const row = (await listPlayableNetworks(root)).find((r) => r.id === 'acme-ads');
    expect(row?.error).toBeUndefined();
  });
});

describe('listPlatforms — the AOT toolchain, only where it is owed', () => {
  /** A project that promises compilation, and a web runtime so the row is
   *  otherwise ready. */
  const promising = (): void => {
    mkdirSync(path.join(root, 'src'), { recursive: true });
    writeFileSync(path.join(root, 'src', 'move.ts'), '/** @compiled */ export const x = 1;');
    writeFileSync(path.join(webDir, 'esengine.js'), '//');
    writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
  };
  const rows = (t: { emcc: string | null; cc: string | null }) =>
    listPlatforms(root, dirs(), VERSION, t);

  it('says nothing to a project that promised nothing, on a machine with no emcc', async () => {
    mkdirSync(path.join(root, 'src'), { recursive: true });
    writeFileSync(path.join(root, 'src', 'move.ts'), 'export const x = 1;');
    writeFileSync(path.join(webDir, 'esengine.js'), '//');
    const byId = Object.fromEntries((await rows(NONE)).map((r) => [r.id, r]));

    expect(byId.web.ready).toBe(true);
    expect(byId.web.prereq).toBeUndefined();
  });

  it('blocks the targets that would compile, and names emsdk', async () => {
    promising();
    const byId = Object.fromEntries((await rows(NONE)).map((r) => [r.id, r]));

    expect(byId.web.ready).toBe(false);
    expect(byId.web.prereq).toEqual({ kind: 'toolchain-missing', tool: 'emsdk' });
    expect(byId.wechat.ready).toBe(false);
    expect(byId.wechat.prereq).toEqual({ kind: 'toolchain-missing', tool: 'emsdk' });
  });

  it('leaves alone the targets whose export never compiles', async () => {
    promising();
    const byId = Object.fromEntries((await rows(NONE)).map((r) => [r.id, r]));

    // A playable inlines everything and has nowhere to put a module; iOS and
    // Android would need a cross-compiler. None runs the step, so none is
    // blocked by a toolchain it will not spawn.
    expect(byId.playable.ready).toBe(true);
    expect(byId.playable.prereq).toBeUndefined();
  });

  it('asks each road for its OWN compiler', async () => {
    promising();
    const webRow = async (t: { emcc: string | null; cc: string | null }) =>
      (await rows(t)).find((r) => r.id === 'web')!;

    // Web is the row that reaches the AOT question here rather than a harder
    // blocker. Pinned: the question is emcc's, and the OTHER compiler does not
    // answer it — a machine with only a host cc cannot package for the web.
    expect((await webRow(NONE)).prereq).toEqual({ kind: 'toolchain-missing', tool: 'emsdk' });
    expect((await webRow({ emcc: null, cc: 'cc' })).prereq)
      .toEqual({ kind: 'toolchain-missing', tool: 'emsdk' });
    expect((await webRow({ emcc: '/emcc', cc: null })).prereq).toBeUndefined();

    // And the desktop asks the other one. Its row is blocked by a missing runtime
    // template here, which is the harder answer and the one it must keep.
    expect(compileTargetFor('desktop')).toBe('native');
    expect(compileTargetFor('web')).toBe('wasm');
    expect(compileTargetFor('playable')).toBeNull();
  });

  it('a project platform rides the same rule — it packages through the mini-game path', async () => {
    promising();
    writePlatform('acme.mjs', `export default {
      id: 'acme', label: 'ACME', emitConfigFiles: () => [],
    };`);
    const acme = (await rows(NONE)).find((r) => r.id === 'acme');

    expect(acme!.ready).toBe(false);
    expect(acme!.prereq).toEqual({ kind: 'toolchain-missing', tool: 'emsdk' });
  });

  it('clears once the machine has one', async () => {
    promising();
    const byId = Object.fromEntries((await rows({ emcc: '/opt/emsdk/emcc', cc: 'cc' })).map((r) => [r.id, r]));

    expect(byId.web.ready).toBe(true);
    expect(byId.wechat.ready).toBe(true);
  });

  it('does not speak over a harder blocker — no runtime means no package at all', async () => {
    mkdirSync(path.join(root, 'src'), { recursive: true });
    writeFileSync(path.join(root, 'src', 'move.ts'), '/** @compiled */ export const x = 1;');
    const web = (await rows(NONE)).find((r) => r.id === 'web');

    expect(web!.ready).toBe(false);
    expect(web!.prereq?.kind).toBe('runtime-missing');
  });
});