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.

26.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
//
// The runtime-template store. A native app's compiled half ships as an artifact
// rather than being rebuilt on every user's machine, so what is pinned here is the
// contract between the emitter and the editor:
//
//   1. A template is matched EXACTLY on version — the SDK bundle is compiled into
//      the app binary, so a near-miss fails on a device instead of in the dialog.
//   2. An archive is untrusted input, and an incomplete one must not replace a
//      working install.
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import path from 'node:path';
import {
  resolveNativeTemplate, iosSourcesFromTemplate, installNativeTemplate,
  listNativeTemplates, removeNativeTemplate, downloadNativeTemplate, nativeSpineMismatch,
} from '../src/export/nativeTemplates';
import { listPlatforms } from '../src/export/platformCatalog';
import {
  requiredTemplateFiles, templateLayout, installedTemplateDir, parseTemplateIndex,
  missingTemplateEntries, isTemplatePlatform, builtSpineVersions, templateSpineVersions, SPINE_RELEASES,
  androidSpineLibs, androidSpineLibrary,
  TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_INDEX, TEMPLATE_PLATFORMS,
  type TemplatePlatform,
} from '../../build-tools/utils/nativeTemplate.js';
import { verifyTemplateZip } from '../../build-tools/tasks/verifyTemplate.js';
import { makeZip } from '../../build-tools/utils/zip.js';

const VERSION = '9.9.9';
/** No project root here, so nothing can have promised compilation. */
const NO_TOOLCHAINS = { emcc: null, cc: null };

let store: string;
let scratch: string;

beforeEach(() => {
  scratch = mkdtempSync(path.join(tmpdir(), 'es-tmpl-'));
  store = path.join(scratch, 'templates');
  process.env.ESTELLA_NATIVE_TEMPLATES = store;
});

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

/** Every file the layout declares required, with a stand-in body — so the fixture
 *  follows the contract rather than a copy of it that can go stale. */
function templateEntries(
  version: string, omit?: string, platform: TemplatePlatform = 'ios',
): { name: string; data: Buffer }[] {
  const entries = requiredTemplateFiles(platform)
    .filter((rel) => rel !== omit)
    .map((rel) => ({ name: rel, data: Buffer.from(`stand-in for ${rel}`) }));
  entries.push({
    name: TEMPLATE_MANIFEST,
    data: Buffer.from(JSON.stringify({
      kind: 'estella-native-template',
      formatVersion: TEMPLATE_FORMAT,
      id: platform,
      platform,
      engineVersion: version,
      spineVersion: '4.2',
      deploymentTarget: '17.0',
    })),
  });
  return entries;
}

function writeTemplateZip(version: string, omit?: string, platform: TemplatePlatform = 'ios'): string {
  const file = path.join(scratch, `template-${version}-${platform}.zip`);
  writeFileSync(file, makeZip(templateEntries(version, omit, platform)));
  return file;
}

// #115: a host carries every vendored Spine release, each reading the skeletons
// exported from it. The template says which it carries, read off the build, and
// an Android package takes only the releases its skeletons need.
describe('the Spine releases a template carries', () => {
  function manifestDir(fields: Record<string, unknown> = {}): string {
    const dir = mkdtempSync(path.join(scratch, 'tmpl-'));
    writeFileSync(path.join(dir, TEMPLATE_MANIFEST), JSON.stringify({
      kind: 'estella-native-template', formatVersion: TEMPLATE_FORMAT, id: 'android', platform: 'android',
      engineVersion: VERSION, ...fields,
    }));
    return dir;
  }
  const ALL = { spineVersions: [...SPINE_RELEASES] };
  function hostCache(rel: string, line: string | null): void {
    mkdirSync(path.join(scratch, rel), { recursive: true });
    writeFileSync(path.join(scratch, rel, 'CMakeCache.txt'),
      `CMAKE_BUILD_TYPE:STRING=Release
${line ?? ''}
`);
  }

  it('lists every vendored release, and the ones the SDK can ask for', async () => {
    const { readdirSync } = await import('node:fs');
    const vendored = readdirSync(path.join(__dirname, '../../third_party'))
      .filter((d) => d.startsWith('spine-runtimes-')).map((d) => d.slice('spine-runtimes-'.length)).sort();
    expect([...SPINE_RELEASES]).toEqual(vendored);
    const { SPINE_VERSIONS } = await import('esengine');
    expect([...SPINE_RELEASES]).toEqual([...SPINE_VERSIONS].sort());
  });

  it('reads the releases the host build carried from its CMake cache', () => {
    hostCache('build/cmake/native-windows', 'ESTELLA_SPINE_VERSIONS:STRING=4.2;3.8');
    expect(builtSpineVersions(scratch, 'windows')).toEqual(['3.8', '4.2']);
    hostCache('build/cmake/native/arm64-v8a', 'ESTELLA_SPINE_VERSIONS:STRING=3.8;4.2');
    expect(builtSpineVersions(scratch, 'android', ['arm64-v8a'])).toEqual(['3.8', '4.2']);
  });

  it('reads a single-release build as the one release it linked, and says nothing without a build', () => {
    hostCache('build/cmake/native-linux', 'ESTELLA_SPINE_VERSION:STRING=3.8');
    expect(builtSpineVersions(scratch, 'linux')).toEqual(['3.8']);
    expect(builtSpineVersions(scratch, 'macos')).toBeNull();
  });

  it('refuses to pack ABIs that carried different releases into one template', () => {
    hostCache('build/cmake/native/arm64-v8a', 'ESTELLA_SPINE_VERSIONS:STRING=3.8');
    hostCache('build/cmake/native/x86_64', 'ESTELLA_SPINE_VERSIONS:STRING=4.2');
    expect(() => builtSpineVersions(scratch, 'android', ['arm64-v8a', 'x86_64'])).toThrow(/same --spine/);
  });

  it('reads an older template as the one release it linked', () => {
    expect(templateSpineVersions({})).toEqual(['4.2']);
    expect(templateSpineVersions({ spineVersion: '3.8' })).toEqual(['3.8']);
    expect(templateSpineVersions(ALL)).toEqual([...SPINE_RELEASES]);
  });

  it('plays skeletons of every release on a current template', () => {
    const skeletons = new Map([['3.8', ['a.skel']], ['4.1', ['b.json']], ['4.2', ['c.skel']]]);
    expect(nativeSpineMismatch(skeletons, manifestDir(ALL), 'android')).toBeNull();
    expect(nativeSpineMismatch(new Map(), manifestDir(), 'android')).toBeNull();
  });

  // The reporter's case on a template from before: named, and fixed by installing
  // the editor's own template — not by a build only a source checkout can run.
  it('names the skeletons an older template cannot play, and the template that can', () => {
    const why = nativeSpineMismatch(
      new Map([['4.2', ['ok.skel']], ['3.8', ['a.json', 'b.json', 'c.json', 'd.json']]]), manifestDir(), 'android');
    expect(why).toContain('4 Spine skeletons are 3.8 (a.json, b.json, c.json, and 1 more)');
    expect(why).toContain('carries Spine 4.2 only');
    expect(why).not.toContain('ok.skel');
    expect(why).toContain('runtime template from Package Project');
    expect(why).not.toContain('build-tools');
  });

  it('gives an Android package the libraries of the releases its skeletons need, and no others', () => {
    const dir = manifestDir(ALL);
    for (const abi of ['arm64-v8a', 'x86_64']) {
      mkdirSync(path.join(dir, 'plugins', abi), { recursive: true });
      for (const v of SPINE_RELEASES) writeFileSync(path.join(dir, 'plugins', abi, androidSpineLibrary(v)), 'so');
    }
    const libs = androidSpineLibs(dir, ['arm64-v8a'], ['3.8', '4.2']);
    expect(Object.keys(libs)).toEqual(['arm64-v8a']);
    expect(libs['arm64-v8a'].map((f) => path.basename(f))).toEqual(['libestella_spine38.so', 'libestella_spine42.so']);
  });

  // v0.101.0 shipped this: the export passes a Map's keys, which the first ABI
  // used up, so an emulator package carried no Spine on x86_64.
  it('gives every ABI its libraries when the releases come as an iterator', () => {
    const dir = manifestDir(ALL);
    for (const abi of ['arm64-v8a', 'x86_64']) {
      mkdirSync(path.join(dir, 'plugins', abi), { recursive: true });
      for (const v of SPINE_RELEASES) writeFileSync(path.join(dir, 'plugins', abi, androidSpineLibrary(v)), 'so');
    }
    const libs = androidSpineLibs(dir, ['arm64-v8a', 'x86_64'], new Map([['4.1', []], ['4.2', []]]).keys());
    expect(Object.keys(libs).sort()).toEqual(['arm64-v8a', 'x86_64']);
    expect(libs['x86_64'].map((f) => path.basename(f))).toEqual(['libestella_spine41.so', 'libestella_spine42.so']);
  });
});

describe('installing a runtime template', () => {
  it('installs an archive and makes the platform resolvable', () => {
    expect(resolveNativeTemplate('ios', VERSION)).toBeNull();

    const res = installNativeTemplate(writeTemplateZip(VERSION), VERSION);

    expect(res.ok).toBe(true);
    expect(res.versionMismatch).toBe(false);
    expect(res.dir).toBe(installedTemplateDir(VERSION, 'ios', store));

    const resolved = resolveNativeTemplate('ios', VERSION);
    expect(resolved?.manifest.engineVersion).toBe(VERSION);
    const sources = iosSourcesFromTemplate(VERSION)!;
    expect(existsSync(sources.xcframework)).toBe(true);
    expect(existsSync(sources.mainM)).toBe(true);
    expect(existsSync(sources.infoPlistIn)).toBe(true);
  });

  it('stores a template built for another release, but does not offer it', () => {
    const res = installNativeTemplate(writeTemplateZip('1.0.0'), VERSION);

    expect(res.ok).toBe(true);
    // Named, so the dialog can say which version the archive was for.
    expect(res.versionMismatch).toBe(true);
    expect(res.engineVersion).toBe('1.0.0');
    expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
    expect(listNativeTemplates(VERSION)).toEqual([
      expect.objectContaining({ id: 'ios', engineVersion: '1.0.0', current: false }),
    ]);
  });

  it('rejects an incomplete archive, and leaves the installed one alone', () => {
    installNativeTemplate(writeTemplateZip(VERSION), VERSION);

    const res = installNativeTemplate(writeTemplateZip(VERSION, 'App/main.m'), VERSION);

    expect(res.ok).toBe(false);
    expect(res.error).toContain('App/main.m');
    // The working install survived the bad one.
    expect(resolveNativeTemplate('ios', VERSION)).not.toBeNull();
  });

  it('rejects an archive that is not a template at all', () => {
    const file = path.join(scratch, 'random.zip');
    writeFileSync(file, makeZip([{ name: 'readme.txt', data: Buffer.from('hi') }]));

    expect(installNativeTemplate(file, VERSION).error).toContain('template.json');
  });

  it('refuses an archive that would write outside the store', () => {
    const file = path.join(scratch, 'evil.zip');
    writeFileSync(file, makeZip([{ name: '../escaped.txt', data: Buffer.from('x') }]));

    expect(installNativeTemplate(file, VERSION).error).toContain('unsafe');
    expect(existsSync(path.join(scratch, 'escaped.txt'))).toBe(false);
  });

  it('treats a half-deleted install as absent rather than usable', () => {
    installNativeTemplate(writeTemplateZip(VERSION), VERSION);
    rmSync(path.join(installedTemplateDir(VERSION, 'ios', store), 'App', 'main.m'));

    expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
  });

  it('removes an installed template', () => {
    installNativeTemplate(writeTemplateZip(VERSION), VERSION);

    expect(removeNativeTemplate('ios', VERSION)).toBe(true);
    expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
    expect(removeNativeTemplate('ios', VERSION)).toBe(false);
  });
});

describe('downloading a template from a release', () => {
  /** A stand-in release: the published index plus the archive it describes. */
  function release(overrides: { sha256?: string; bytes?: number; templates?: unknown[] } = {}) {
    const zip = readFileSync(writeTemplateZip(VERSION));
    const index = {
      kind: 'estella-native-templates',
      formatVersion: TEMPLATE_FORMAT,
      engineVersion: VERSION,
      templates: overrides.templates ?? [{
        id: 'ios', platform: 'ios',
        file: `estella-native-ios-${VERSION}.zip`,
        bytes: overrides.bytes ?? zip.length,
        sha256: overrides.sha256 ?? createHash('sha256').update(zip).digest('hex'),
      }],
    };
    const served: string[] = [];
    const fetchImpl = (async (url: string) => {
      served.push(url);
      if (url.endsWith(TEMPLATE_INDEX)) {
        return { ok: true, status: 200, json: async () => index } as unknown as Response;
      }
      return {
        ok: true,
        status: 200,
        // Two chunks, so progress is reported more than once.
        body: (async function* () {
          yield zip.subarray(0, 100);
          yield zip.subarray(100);
        })(),
      } as unknown as Response;
    }) as unknown as typeof fetch;
    return { fetchImpl, served, zip };
  }

  // Desktop templates are published per OS, and the download path takes them by
  // that name rather than by the one export target they share.
  it('installs a DESKTOP template, which is published per OS', async () => {
    const zip = readFileSync(writeTemplateZip(VERSION, undefined, 'windows'));
    const index = {
      kind: 'estella-native-templates',
      formatVersion: TEMPLATE_FORMAT,
      engineVersion: VERSION,
      templates: [{
        id: 'windows', platform: 'windows',
        file: `estella-native-windows-${VERSION}.zip`,
        bytes: zip.length,
        sha256: createHash('sha256').update(zip).digest('hex'),
      }],
    };
    const fetchImpl = (async (url: string) => (url.endsWith(TEMPLATE_INDEX)
      ? { ok: true, status: 200, json: async () => index } as unknown as Response
      : { ok: true, status: 200, body: (async function* () { yield zip; })() } as unknown as Response
    )) as unknown as typeof fetch;

    const res = await downloadNativeTemplate('windows', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });
    expect(res).toMatchObject({ ok: true, id: 'windows' });
    expect(resolveNativeTemplate('windows', VERSION)).not.toBeNull();
  });

  // `desktop` is an export target, not a template platform: the index publishes
  // three desktop templates and none of them under that name.
  it('says so when asked for a platform no template is published for', async () => {
    const { fetchImpl } = release();
    const res = await downloadNativeTemplate('desktop' as TemplatePlatform, VERSION, {
      fetchImpl, baseUrl: 'https://example.test/r',
    });
    expect(res.ok).toBe(false);
    expect(res.error).toContain('no desktop template');
  });

  it('installs what the index describes, and reports progress on the way', async () => {
    const { fetchImpl, served, zip } = release();
    const progress: number[] = [];

    const res = await downloadNativeTemplate('ios', VERSION, {
      fetchImpl, baseUrl: 'https://example.test/r', onProgress: (p) => progress.push(p.received),
    });

    expect(res).toMatchObject({ ok: true, id: 'ios', versionMismatch: false });
    expect(resolveNativeTemplate('ios', VERSION)).not.toBeNull();
    expect(served).toEqual([
      `https://example.test/r/${TEMPLATE_INDEX}`,
      `https://example.test/r/estella-native-ios-${VERSION}.zip`,
    ]);
    expect(progress).toEqual([100, zip.length]);
  });

  it('refuses an archive whose checksum does not match the index', async () => {
    const { fetchImpl } = release({ sha256: 'f'.repeat(64) });

    const res = await downloadNativeTemplate('ios', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });

    expect(res.ok).toBe(false);
    expect(res.error).toContain('checksum mismatch');
    expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
  });

  it('refuses a truncated download before it is unpacked', async () => {
    const { fetchImpl } = release({ bytes: 999_999 });

    const res = await downloadNativeTemplate('ios', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });

    expect(res.error).toContain('999999');
    expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
  });

  it('says so when this version publishes no template for the platform', async () => {
    const { fetchImpl } = release();

    const res = await downloadNativeTemplate('android', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });

    expect(res.error).toContain('no android template');
  });

  it('treats an unreadable index as no index — a 404 page is not a template list', async () => {
    const fetchImpl = (async () => ({
      ok: true, status: 200, json: async () => ({ error: 'Not Found' }),
    } as unknown as Response)) as unknown as typeof fetch;

    const res = await downloadNativeTemplate('ios', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });

    expect(res.error).toContain('not readable');
  });

  it('rejects an index published for another version', () => {
    expect(parseTemplateIndex({
      kind: 'estella-native-templates', formatVersion: TEMPLATE_FORMAT, engineVersion: '1.0.0',
      templates: [{ id: 'ios', platform: 'ios', file: 'x.zip', bytes: 1, sha256: 'a'.repeat(64) }],
    }, VERSION)).toBeNull();
  });

  it('drops an entry whose filename could escape the download directory', () => {
    expect(parseTemplateIndex({
      kind: 'estella-native-templates', formatVersion: TEMPLATE_FORMAT, engineVersion: VERSION,
      templates: [{ id: 'ios', platform: 'ios', file: '../evil.zip', bytes: 1, sha256: 'a'.repeat(64) }],
    }, VERSION)).toBeNull();
  });
});

describe('the iOS row reports what is missing', () => {
  const dirs = () => ({ web: path.join(scratch, 'web'), minigame: path.join(scratch, 'wx'), quickgame: path.join(scratch, 'qg') });
  const iosRow = async () => (await listPlatforms(null, dirs(), VERSION, NO_TOOLCHAINS)).find((r) => r.id === 'ios')!;

  it('asks for the runtime template before anything about Xcode', async () => {
    const row = await iosRow();

    expect(row.ready).toBe(false);
    expect(row.prereq).toEqual({ kind: 'template-missing', id: 'ios', version: VERSION });
  });

  it('moves on to the toolchain once a template is installed', async () => {
    installNativeTemplate(writeTemplateZip(VERSION), VERSION);

    const row = await iosRow();

    // On a Mac with Xcode that is everything; elsewhere the toolchain is the
    // remaining gap — and the export still writes a project to carry to a Mac.
    if (row.ready) expect(row.prereq).toBeUndefined();
    else expect(row.prereq?.kind).toBe('toolchain-missing');
  });
});

describe('the template layout is the one source of filenames', () => {
  it('assembles the iOS project from paths inside the installed template', () => {
    installNativeTemplate(writeTemplateZip(VERSION), VERSION);
    const dir = installedTemplateDir(VERSION, 'ios', store);

    const sources = iosSourcesFromTemplate(VERSION)!;

    expect(sources.xcframework).toBe(path.join(dir, 'Estella.xcframework'));
    expect(sources.mainM).toBe(path.join(dir, 'App', 'main.m'));
    expect(sources.infoPlistIn).toBe(path.join(dir, 'App', 'Info.plist.in'));
    // And every one of them is a file the layout declares — including the
    // bytecode, which is optional (a build machine without a host compiler ships a
    // template without it, and the app compiles on first launch instead).
    const declared = templateLayout('ios').map((e) => e.rel);
    for (const file of Object.values(sources)) {
      expect(declared).toContain(path.relative(dir, file).split(path.sep).join('/'));
    }
    expect(requiredTemplateFiles('ios')).not.toContain(
      path.relative(dir, sources.bytecode).split(path.sep).join('/'));
  });
});

describe('what a PUBLISHED template must carry', () => {
  // The bytecode is optional for a local build and not for a release, and reading
  // "optional" as one answer to both is what let v0.36.0 ship an Android template
  // without it — every game packaged from that template opened on a black screen
  // while the host compiled the bundle on the device.
  const BYTECODE = 'assets/esengine.native.qjsbc';

  // What v0.36.0 actually published, minus the bytecode: complete by the rule a
  // contributor's build is held to.
  const shipped = (extra: string[] = []) => [
    'AndroidManifest.xml.in', 'classes.dex', 'icon.png',
    'java/com/estella/host/TextEditor.java',
    'lib/arm64-v8a/libestella_js_host.so', 'lib/arm64-v8a/libwebgpu_dawn.so',
    'lib/arm64-v8a/libc++_shared.so',
    'lib/x86_64/libestella_js_host.so', 'lib/x86_64/libwebgpu_dawn.so',
    'lib/x86_64/libc++_shared.so',
    'template.json', ...extra,
  ];

  it('accepts a template without bytecode, and refuses to publish it', () => {
    expect(missingTemplateEntries(shipped(), 'android')).toEqual([]);
    expect(missingTemplateEntries(shipped(), 'android', { release: true })).toEqual([BYTECODE]);
    expect(missingTemplateEntries(shipped([BYTECODE]), 'android', { release: true })).toEqual([]);
  });

  it('owes no QuickJS bytecode from a template whose host runs V8', () => {
    // A V8 host compiles the bundle on the device and caches it; the bytecode is
    // the interpreter's first-launch fix and means nothing to a JIT.
    const v8 = shipped(['lib/arm64-v8a/libv8android.so', 'lib/x86_64/libv8android.so']);
    expect(missingTemplateEntries(v8, 'android', { release: true })).toEqual([]);
    const windows = ['estella_desktop.exe', 'icon.png', 'd3dcompiler_47.dll', 'template.json'];
    expect(missingTemplateEntries(windows, 'windows', { release: true })).toEqual(['esengine.native.qjsbc']);
    expect(missingTemplateEntries([...windows, 'v8.dll'], 'windows', { release: true })).toEqual([]);
  });

  it('reads the JS engine off the files a template carries', async () => {
    const { templateJsEngine, V8_WINDOWS_RUNTIME } = await import('../../build-tools/utils/nativeTemplate.js');
    const dir = path.join(scratch, 'engine');
    mkdirSync(path.join(dir, 'lib', 'arm64-v8a'), { recursive: true });
    expect(templateJsEngine(dir, 'windows')).toBe('quickjs');
    expect(templateJsEngine(dir, 'android')).toBe('quickjs');
    writeFileSync(path.join(dir, 'v8.dll'), '');
    writeFileSync(path.join(dir, 'lib', 'arm64-v8a', 'libv8android.so'), '');
    expect(templateJsEngine(dir, 'windows')).toBe('v8');
    expect(templateJsEngine(dir, 'android')).toBe('v8');
    expect(templateJsEngine(dir, 'ios')).toBe('quickjs');
    // Every file the V8 host loads is one the Windows layout carries.
    const rels = templateLayout('windows').map((e: { rel: string }) => e.rel);
    for (const f of V8_WINDOWS_RUNTIME) expect(rels).toContain(f);
  });

  it('holds a release to every ABI the template claims', () => {
    // One ABI is a usable template; a release builds both, and losing the emulator
    // one leaves everybody without a phone unable to run the game at all.
    const oneAbi = shipped([BYTECODE]).filter((n) => !n.startsWith('lib/x86_64/'));
    expect(missingTemplateEntries(oneAbi, 'android')).toEqual([]);
    expect(missingTemplateEntries(oneAbi, 'android', { release: true }))
      .toEqual(expect.arrayContaining(['lib/x86_64/libestella_js_host.so']));
  });

  it('strips every native library of the template, libc++ included', async () => {
    // The NDK's own libc++_shared carries 7.5 MB of debug info per ABI, which was 8 of its
    // 9.2 MB in a shipped APK.
    const { templateLayout } = await import('../../build-tools/utils/nativeTemplate.js');
    const libs = templateLayout('android').filter((e: { rel: string }) => e.rel.startsWith('lib/'));
    expect(libs.length).toBeGreaterThan(0);
    for (const e of libs as { rel: string; strip?: boolean }[]) {
      expect(e.strip, `${e.rel} ships with its debug info`).toBe(true);
    }
  });

  it('counts a directory entry as held when something inside it is', () => {
    // A zip stores files, never the folder — so `java` is present because
    // `java/com/...` is, and absent when nothing under it shipped.
    const noJava = shipped([BYTECODE]).filter((n) => !n.startsWith('java/'));
    expect(missingTemplateEntries(noJava, 'android', { release: true })).toEqual(['java']);
  });

  it('reads Windows separators, since that is where an archive may be listed', () => {
    const win = shipped([BYTECODE]).map((n) => n.split('/').join(String.fromCharCode(92)));
    expect(missingTemplateEntries(win, 'android', { release: true })).toEqual([]);
  });
});

describe('the platforms templates are published for', () => {
  /** A release-complete archive for any platform, built from that platform's own
   *  layout so the fixture follows the contract instead of restating it. */
  function releaseZip(platform: TemplatePlatform): Buffer {
    const entries = requiredTemplateFiles(platform, { release: true })
      .map((rel: string) => ({ name: rel, data: Buffer.from(`stand-in for ${rel}`) }));
    entries.push({
      name: TEMPLATE_MANIFEST,
      data: Buffer.from(JSON.stringify({
        kind: 'estella-native-template',
        formatVersion: TEMPLATE_FORMAT,
        id: platform,
        platform,
        engineVersion: VERSION,
      })),
    });
    return makeZip(entries);
  }

  it('all have a layout, and the list is what asks', () => {
    // The release gate kept its own pair of names while three desktop platforms
    // landed in templateLayout, so v0.47.0 built five templates correctly and
    // then refused to publish three. One list, and the layouts cannot part from it.
    for (const p of TEMPLATE_PLATFORMS) {
      expect(isTemplatePlatform(p)).toBe(true);
      expect(templateLayout(p).length).toBeGreaterThan(0);
    }
    expect(isTemplatePlatform('playstation')).toBe(false);
    expect(() => templateLayout('playstation' as TemplatePlatform)).toThrow();
  });

  it('are each accepted by the release verifier', () => {
    // Through the verifier's own entry point, not a copy of its rule — having a
    // copy was the defect.
    for (const p of TEMPLATE_PLATFORMS) {
      const zip = path.join(scratch, `t-${p}.zip`);
      writeFileSync(zip, releaseZip(p));
      const res = verifyTemplateZip(zip);
      expect(res.platform).toBe(p);
      expect(res.problems).toEqual([]);
      expect(res.ok).toBe(true);
    }
  });
});

/**
 * The crash-record check builds for the device it found.
 *
 * It named one ABI, so an x86_64 emulator — the only Android most machines can
 * offer — was pushed a binary it cannot execute, and a release criterion that
 * an emulator CAN answer read as "needs a phone plugged in".
 */
describe('the on-device crash record check', () => {
  const src = readFileSync(path.resolve(__dirname, '../../tools/verify-bootlog-crash.mjs'), 'utf8');

  it('has an NDK driver for every ABI an Android device reports', () => {
    // The TRIPLE, not the ABI name: `x86_64` also appears in the host-platform
    // ternary, so looking for the key matched a line that compiles nothing.
    const triples = {
      'arm64-v8a': 'aarch64-linux-android',
      'armeabi-v7a': 'armv7a-linux-androideabi',
      x86_64: 'x86_64-linux-android',
      x86: 'i686-linux-android',
    };
    const missing = Object.entries(triples)
      .filter(([, triple]) => !src.includes(`'${triple}'`))
      .map(([abi]) => abi);
    expect(missing, 'a device reporting one of these gets no compiler').toEqual([]);
  });

  it('asks the device rather than assuming a phone', () => {
    expect(src).toContain('ro.product.cpu.abi');
    expect(src, 'the driver is still pinned to one ABI').not.toMatch(/aarch64-linux-android33-clang/);
  });
});