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.

feat(editor): download the runtime template from the release

esengine6e203183f48e
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 274639ef7..6f4dbde80 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -84,6 +84,118 @@ jobs:
desktop/public/wasm-wechat
retention-days: 3
+ # The native app's compiled half — the engine, Dawn, QuickJS, the linked-in
+ # runtimes — carries no project data, so it is built ONCE per release and
+ # published as a runtime template the editor installs. This is what frees a
+ # developer from cloning the engine and building Dawn to ship to a phone.
+ #
+ # Dawn is the expensive part (gigabytes to fetch, minutes to build, three
+ # targets), and it is pinned in toolchain.manifest.json — so the fetch AND the
+ # build cache on that commit, and a release that does not move the pin pays for
+ # neither.
+ native-templates:
+ name: Build runtime template (${{ matrix.name }})
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: ios
+ os: macos-latest
+ - name: android
+ os: ubuntu-latest
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@v7
+
+ - uses: ./.github/actions/setup
+
+ # The SDK bundle is compiled INTO the host binary, which is why a template
+ # is matched exactly against the editor version that ships with it.
+ - name: Build SDK
+ run: pnpm --filter ./sdk build
+
+ - name: Read the native dependency pins
+ id: pins
+ shell: bash
+ run: |
+ node -e "const p=require('./toolchain.manifest.json').native;\
+ console.log('dawn='+p.dawn.commit);console.log('quickjs='+p.quickjs.commit)" >> "$GITHUB_OUTPUT"
+
+ # Keyed on the pins and the target: the checkout and the Dawn builds are
+ # reproducible for a given commit, so this is warm on every release that
+ # does not move it.
+ - name: Cache the pinned checkouts + Dawn builds
+ uses: actions/cache@v4
+ with:
+ path: build/native-deps
+ key: native-deps-${{ matrix.name }}-${{ steps.pins.outputs.dawn }}-${{ steps.pins.outputs.quickjs }}
+
+ # Dawn and the host both build with Ninja; neither tool is guaranteed on a
+ # macOS runner (the Android SDK carries its own pair).
+ - name: Set up CMake + Ninja
+ if: matrix.name == 'ios'
+ run: brew install cmake ninja
+
+ - name: Set up the Android NDK
+ if: matrix.name == 'android'
+ uses: nttld/setup-ndk@v1
+ id: ndk
+ with:
+ ndk-version: r28
+
+ - name: Fetch Dawn + QuickJS at their pinned commits
+ run: node build-tools/cli.js native --fetch-deps
+
+ # `native` builds Dawn for the target if the cache did not carry it, then
+ # the host, then emits the template — the same command a contributor runs.
+ - name: Build the iOS template (device + simulator)
+ if: matrix.name == 'ios'
+ run: |
+ node build-tools/cli.js native --target ios --simulator --no-template
+ node build-tools/cli.js native --target ios --template-out artifacts
+
+ - name: Build the Android template
+ if: matrix.name == 'android'
+ env:
+ ANDROID_NDK_HOME: ${{ steps.ndk.outputs.ndk-path }}
+ run: node build-tools/cli.js native --template-out artifacts
+
+ - name: Upload template artifact
+ uses: actions/upload-artifact@v7
+ with:
+ name: native-template-${{ matrix.name }}
+ path: artifacts/*.zip
+ retention-days: 3
+
+ # One job holds every archive, so only it can describe the set: the index
+ # carries a digest per template, and the editor refuses a download that does not
+ # match it.
+ publish-templates:
+ needs: [draft, native-templates]
+ if: github.event_name == 'push' && needs.draft.result == 'success'
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/checkout@v7
+
+ - name: Download every template archive
+ uses: actions/download-artifact@v8
+ with:
+ pattern: native-template-*
+ merge-multiple: true
+ path: artifacts
+
+ - name: Write native-templates.json
+ run: node build-tools/cli.js native --template-index artifacts
+
+ - name: Upload the templates to the release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: gh release upload "$GITHUB_REF_NAME" artifacts/* --repo "$GITHUB_REPOSITORY" --clobber
+
release:
# Platform jobs only package: SDK + renderer builds are quick TS/JS work,
# and electron-builder needs the native OS. No emsdk, no C++ here.
diff --git a/build-tools/tasks/nativeTemplateEmit.js b/build-tools/tasks/nativeTemplateEmit.js
index 1a1c0343c..ef5591e7e 100644
--- a/build-tools/tasks/nativeTemplateEmit.js
+++ b/build-tools/tasks/nativeTemplateEmit.js
@@ -11,6 +11,7 @@
import path from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
+import { createHash } from 'crypto';
import { mkdir, rm, cp, readdir } from 'fs/promises';
import config from '../build.config.js';
import * as logger from '../utils/logger.js';
@@ -19,7 +20,7 @@ import { buildTool, platformJar, ndkTool, ndkLibcxxShared, jdkTool } from '../ut
import { makeZip, zipTree } from '../utils/zip.js';
import {
templateLayout, templateId, DEFAULT_ABI, writeTemplateManifest, missingTemplateFiles,
- installedTemplateDir, templateZipName,
+ installedTemplateDir, templateZipName, TEMPLATE_INDEX, TEMPLATE_FORMAT,
} from '../utils/nativeTemplate.js';
/** The Java shim's sources — the IME's own side of an editable field, which has to
@@ -75,6 +76,52 @@ export async function compileJavaShim(outDir, { sdk, androidPlatform, jdk, root
return existsSync(path.join(outDir, 'classes.dex'));
}
+/**
+ * Write the index a release publishes beside its template archives: what exists
+ * for this version, and what each archive must hash to.
+ *
+ * A separate step from emitting, because the set spans machines — the iOS archive
+ * is built on a Mac and the Android one is not — so only the job that has both
+ * can describe them.
+ *
+ * @param {string} dir Directory holding the archives.
+ * @returns {Promise<{file: string, templates: object[]}>}
+ */
+export async function writeTemplateIndex(dir, options = {}) {
+ const engineVersion = options.engineVersion || readEngineVersion(options.root);
+ const suffix = `-${engineVersion}.zip`;
+ const archives = (await readdir(dir))
+ .filter((f) => f.startsWith('estella-native-') && f.endsWith(suffix))
+ .sort();
+ if (archives.length === 0) {
+ throw new Error(`No template archives for v${engineVersion} in ${dir}.`);
+ }
+
+ const templates = archives.map((file) => {
+ const bytes = readFileSync(path.join(dir, file));
+ const id = file.slice('estella-native-'.length, -suffix.length);
+ const dash = id.indexOf('-');
+ return {
+ id,
+ platform: id.slice(0, dash),
+ abi: id.slice(dash + 1),
+ file,
+ bytes: bytes.length,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ };
+ });
+
+ const out = path.join(dir, TEMPLATE_INDEX);
+ writeFileSync(out, `${JSON.stringify({
+ kind: 'estella-native-templates',
+ formatVersion: TEMPLATE_FORMAT,
+ engineVersion,
+ templates,
+ }, null, 2)}\n`, 'utf8');
+ logger.success(`Template index: ${out} (${templates.map((t) => t.id).join(', ')})`);
+ return { file: out, templates };
+}
+
/**
* Pack a finished native build into a runtime template.
*
diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.ts
index 51bf8c8cf..03c090ce9 100644
--- a/build-tools/utils/nativeTemplate.d.ts
+++ b/build-tools/utils/nativeTemplate.d.ts
@@ -51,6 +51,19 @@ export function templateStoreDir(): string;
export function installedTemplateDir(
engineVersion: string, platform: NativePlatform, abi: string, storeDir?: string): string;
export function findTemplate(want: TemplateWant, storeDir?: string): FoundTemplate | null;
+export interface PublishedTemplate {
+ id: string;
+ platform: NativePlatform;
+ abi: string;
+ /** Archive filename, resolved against the release's asset base. */
+ file: string;
+ bytes: number;
+ sha256: string;
+}
+
+export const TEMPLATE_INDEX: string;
+export function releaseAssetBase(engineVersion: string): string;
+export function parseTemplateIndex(doc: unknown, engineVersion?: string): PublishedTemplate[] | null;
export function iosTemplateSources(dir: string): {
xcframework: string;
mainM: string;
diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.js
index 12d5f144f..41b6b89c9 100644
--- a/build-tools/utils/nativeTemplate.js
+++ b/build-tools/utils/nativeTemplate.js
@@ -155,6 +155,40 @@ export function templateZipName(platform, abi, engineVersion) {
return `estella-native-${templateId(platform, abi)}-${engineVersion}.zip`;
}
+// =============================================================================
+// The published index
+// =============================================================================
+
+/** What a release publishes beside the archives: which templates exist for that
+ * version, and what each one must hash to. */
+export const TEMPLATE_INDEX = 'native-templates.json';
+
+/**
+ * Where a release's assets live. Composed rather than stored in the index, so the
+ * same index works from a mirror, a local directory or a company file share — the
+ * editor is told a base, not a set of absolute URLs.
+ */
+export function releaseAssetBase(engineVersion) {
+ return `https://github.com/esengine/estella/releases/download/v${engineVersion}`;
+}
+
+/**
+ * Validate a published index. Returns its entries, or null when the document is
+ * not one — a 404 page and a truncated download are both "no index", and neither
+ * should reach the code that decides what to install.
+ */
+export function parseTemplateIndex(doc, engineVersion) {
+ if (doc?.kind !== 'estella-native-templates' || doc.formatVersion !== TEMPLATE_FORMAT) return null;
+ if (engineVersion && doc.engineVersion !== engineVersion) return null;
+ if (!Array.isArray(doc.templates)) return null;
+ const entries = doc.templates.filter((t) => typeof t?.id === 'string'
+ && typeof t.platform === 'string' && typeof t.abi === 'string'
+ && typeof t.file === 'string' && /^[\w.-]+$/.test(t.file)
+ && typeof t.sha256 === 'string' && /^[0-9a-f]{64}$/.test(t.sha256)
+ && Number.isInteger(t.bytes) && t.bytes > 0);
+ return entries.length > 0 ? entries : null;
+}
+
// =============================================================================
// Where templates live
// =============================================================================
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 5b160528c..ffd056c52 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -32,7 +32,8 @@ import { startProjectWatch, stopProjectWatch } from './projectWatcher';
import { importAssets, createAsset, IMPORT_EXTENSIONS } from './importAssets';
import { exportGame } from './exportGame';
import {
- iosSourcesFromTemplate, resolveNativeTemplate, installNativeTemplate, listNativeTemplates, removeNativeTemplate,
+ iosSourcesFromTemplate, resolveNativeTemplate, installNativeTemplate, listNativeTemplates,
+ removeNativeTemplate, downloadNativeTemplate,
} from './nativeTemplates';
import { loopbackServer, closeAllLoopbackServers } from './loopbackServer';
import { httpContentType } from './mimeTypes';
@@ -1011,6 +1012,13 @@ ipcMain.handle('nativeTemplates:install', async () => {
ipcMain.handle('nativeTemplates:remove', (_e, platform: 'android' | 'ios', abi: string, version: string) =>
removeNativeTemplate(platform, abi, version),
);
+// Download + install this editor version's template. Progress is pushed rather
+// than polled: the renderer drew the button, so it owns the progress bar.
+ipcMain.handle('nativeTemplates:download', (e, platform: 'android' | 'ios') =>
+ downloadNativeTemplate(platform, app.getVersion(), {
+ onProgress: (p) => e.sender.send('nativeTemplates:downloadProgress', { platform, ...p }),
+ }),
+);
// New-project templates + creation (launcher New tab).
ipcMain.handle('templates:list', () => listTemplates());
diff --git a/desktop/electron/nativeTemplates.ts b/desktop/electron/nativeTemplates.ts
index 5534e75ab..0634e3bc8 100644
--- a/desktop/electron/nativeTemplates.ts
+++ b/desktop/electron/nativeTemplates.ts
@@ -16,11 +16,13 @@
*/
import path from 'node:path';
-import { existsSync, readFileSync, rmSync, renameSync, mkdirSync, readdirSync } from 'node:fs';
-import { randomUUID } from 'node:crypto';
+import { existsSync, readFileSync, rmSync, renameSync, mkdirSync, readdirSync, createWriteStream } from 'node:fs';
+import { once } from 'node:events';
+import { randomUUID, createHash } from 'node:crypto';
import {
findTemplate, readTemplateManifest, missingTemplateFiles, installedTemplateDir,
- templateStoreDir, iosTemplateSources, DEFAULT_ABI,
+ templateStoreDir, iosTemplateSources, DEFAULT_ABI, releaseAssetBase, parseTemplateIndex,
+ TEMPLATE_INDEX,
type NativePlatform, type NativeTemplateManifest,
} from '../../build-tools/utils/nativeTemplate.js';
import { extractZip } from '../../build-tools/utils/zip.js';
@@ -143,6 +145,80 @@ export function installNativeTemplate(zipPath: string, engineVersion: string): I
}
}
+/** How far a download has got, for the row that asked for it. */
+export interface TemplateDownloadProgress {
+ received: number;
+ total: number;
+}
+
+/**
+ * Download this editor version's runtime template for @p platform and install it.
+ *
+ * The release publishes an index beside the archives, so the editor asks what
+ * exists for its own version rather than guessing a filename — and the index
+ * carries a digest, which is checked before anything is unpacked. A download that
+ * was truncated, cached wrong by a proxy or served as somebody's captive-portal
+ * login page fails here, named, instead of installing as a broken template.
+ *
+ * Never throws: every failure is a message on the row that offered the button.
+ */
+export async function downloadNativeTemplate(
+ platform: NativePlatform,
+ engineVersion: string,
+ options: {
+ onProgress?: (progress: TemplateDownloadProgress) => void;
+ fetchImpl?: typeof fetch;
+ /** Where the archives live. Overridable for tests and for an offline mirror. */
+ baseUrl?: string;
+ } = {},
+): Promise<InstallResult> {
+ const fetchImpl = options.fetchImpl ?? fetch;
+ const base = options.baseUrl ?? releaseAssetBase(engineVersion);
+ const staging = path.join(templateStoreDir(), `.download-${randomUUID()}`);
+
+ try {
+ const indexRes = await fetchImpl(`${base}/${TEMPLATE_INDEX}`);
+ if (!indexRes.ok) {
+ return { ok: false, error: `no template index for v${engineVersion} (HTTP ${indexRes.status})` };
+ }
+ const entries = parseTemplateIndex(await indexRes.json(), engineVersion);
+ if (!entries) return { ok: false, error: `the template index for v${engineVersion} is not readable` };
+
+ const abi = DEFAULT_ABI[platform];
+ const entry = entries.find((t) => t.platform === platform && t.abi === abi);
+ if (!entry) return { ok: false, error: `v${engineVersion} publishes no ${platform}-${abi} template` };
+
+ const res = await fetchImpl(`${base}/${entry.file}`);
+ if (!res.ok || !res.body) return { ok: false, error: `download failed (HTTP ${res.status})` };
+
+ mkdirSync(staging, { recursive: true });
+ const file = path.join(staging, entry.file);
+ const digest = createHash('sha256');
+ let received = 0;
+ const sink = createWriteStream(file);
+ for await (const chunk of res.body as AsyncIterable<Uint8Array>) {
+ digest.update(chunk);
+ received += chunk.byteLength;
+ options.onProgress?.({ received, total: entry.bytes });
+ if (!sink.write(chunk)) await once(sink, 'drain');
+ }
+ await new Promise<void>((resolve, reject) => sink.end((err?: Error) => (err ? reject(err) : resolve())));
+
+ if (received !== entry.bytes) {
+ return { ok: false, error: `download is ${received} bytes, the index says ${entry.bytes}` };
+ }
+ const got = digest.digest('hex');
+ if (got !== entry.sha256) {
+ return { ok: false, error: `checksum mismatch — got ${got.slice(0, 16)}…, expected ${entry.sha256.slice(0, 16)}…` };
+ }
+ return installNativeTemplate(file, engineVersion);
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+}
+
/** Delete an installed template. Takes the id + version rather than a path, so a
* renderer can never ask the main process to remove an arbitrary directory. */
export function removeNativeTemplate(platform: NativePlatform, abi: string, engineVersion: string): boolean {
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index df4f229de..76098338d 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -231,6 +231,15 @@ const api = {
install: (): Promise<InstallResult & { canceled?: boolean }> => ipcRenderer.invoke('nativeTemplates:install'),
remove: (platform: 'android' | 'ios', abi: string, version: string): Promise<boolean> =>
ipcRenderer.invoke('nativeTemplates:remove', platform, abi, version),
+ /** Fetch this editor version's template from the release and install it. */
+ download: (platform: 'android' | 'ios'): Promise<InstallResult> =>
+ ipcRenderer.invoke('nativeTemplates:download', platform),
+ /** Subscribe to download progress; returns an unsubscribe. */
+ onDownloadProgress: (cb: (p: { platform: string; received: number; total: number }) => void): (() => void) => {
+ const h = (_e: unknown, p: { platform: string; received: number; total: number }) => cb(p);
+ ipcRenderer.on('nativeTemplates:downloadProgress', h);
+ return () => ipcRenderer.removeListener('nativeTemplates:downloadProgress', h);
+ },
},
// Recent projects (launcher), persisted in userData.
recents: {
diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsx
index 68394697b..73b3feba9 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -242,6 +242,12 @@ export function BuildDialog() {
// installed), so the rows re-probe instead of the dialog having to be reopened.
const [probeTick, setProbeTick] = useState(0);
const [templateNote, setTemplateNote] = useState<{ text: string; error: boolean } | null>(null);
+ const [downloading, setDownloading] = useState<{ received: number; total: number } | null>(null);
+
+ // Progress is pushed from main while a template downloads.
+ useEffect(() => window.estella.nativeTemplates?.onDownloadProgress?.((p) => {
+ setDownloading({ received: p.received, total: p.total });
+ }), []);
useEffect(() => {
let alive = true;
@@ -409,11 +415,9 @@ export function BuildDialog() {
setTimeout(() => setCopiedFix(false), 1600);
};
- /** Install a runtime template the user downloaded, then re-probe: the row that
- * asked for it becomes ready without reopening the dialog. */
- const installTemplate = async () => {
- const res = await window.estella.nativeTemplates?.install?.();
- if (!res || res.canceled) return;
+ /** Report the outcome of getting a template, and re-probe when it worked: the
+ * row that asked for it becomes ready without reopening the dialog. */
+ const afterTemplate = (res: { ok: boolean; id?: string; engineVersion?: string; versionMismatch?: boolean; error?: string }) => {
if (!res.ok) {
setTemplateNote({ text: res.error ?? '', error: true });
return;
@@ -434,6 +438,26 @@ export function BuildDialog() {
setProbeTick((n) => n + 1);
};
+ /** Install an archive the user already has (offline, a mirror, a company share). */
+ const installTemplate = async () => {
+ const res = await window.estella.nativeTemplates?.install?.();
+ if (!res || res.canceled) return;
+ afterTemplate(res);
+ };
+
+ /** Fetch it from this version's release. */
+ const downloadTemplate = async (platform: string) => {
+ if (platform !== 'android' && platform !== 'ios') return;
+ setTemplateNote(null);
+ setDownloading({ received: 0, total: 0 });
+ try {
+ const res = await window.estella.nativeTemplates?.download?.(platform);
+ if (res) afterTemplate(res);
+ } finally {
+ setDownloading(null);
+ }
+ };
+
const browse = async () => {
const dir = await window.estella.project?.chooseDirectory?.();
if (dir) setOutDir(dir);
@@ -669,8 +693,18 @@ export function BuildDialog() {
</span>
{def.prereqKind === 'template-missing' && (
<div className="build__fix">
- <Button onClick={() => void installTemplate()}>
- <Package size={12} /> {t('build.installTemplate')}
+ <Button variant="primary" disabled={!!downloading} onClick={() => void downloadTemplate(def.id)}>
+ {downloading
+ ? <><Loader2 size={12} className="spin" /> {downloading.total > 0
+ ? t('build.downloadingTemplatePct', {
+ pct: String(Math.round((downloading.received / downloading.total) * 100)),
+ size: mb(downloading.total),
+ })
+ : t('build.downloadingTemplate')}</>
+ : <><Package size={12} /> {t('build.downloadTemplate')}</>}
+ </Button>
+ <Button disabled={!!downloading} onClick={() => void installTemplate()}>
+ {t('build.installTemplate')}
</Button>
{templateNote && (
<span className={templateNote.error ? 'is-error selectable' : 'selectable'}>
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index 5da12a5e9..d01ca8764 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -48,9 +48,12 @@ export const projectMessages = defineMessages({
zh: '本机没有 v{version} 的 {id} 运行时模板。',
},
'build.templateHint': {
- en: 'It is the prebuilt engine the app is assembled around — download it from this release and install it here, once per editor version. Building it yourself needs the engine sources.',
- zh: '它是应用装配所围绕的预编译引擎——从本版本的发布页下载并在此安装,每个编辑器版本装一次即可。自行构建它需要引擎源码。',
+ en: 'It is the prebuilt engine the app is assembled around, downloaded once per editor version. Already have the archive? Install it from a file instead.',
+ zh: '它是应用装配所围绕的预编译引擎,每个编辑器版本下载一次即可。已经有归档文件了?也可以直接从文件安装。',
},
+ 'build.downloadTemplate': { en: 'Download', zh: '下载' },
+ 'build.downloadingTemplate': { en: 'Downloading…', zh: '下载中…' },
+ 'build.downloadingTemplatePct': { en: 'Downloading {pct}% of {size}', zh: '下载中 {pct}%(共 {size})' },
'build.installTemplate': { en: 'Install from file…', zh: '从文件安装…' },
'build.templateInstalled': {
en: 'Installed the {id} runtime template (v{version}).',
diff --git a/desktop/tests/native-template.test.ts b/desktop/tests/native-template.test.ts
index 7645c825f..21f644033 100644
--- a/desktop/tests/native-template.test.ts
+++ b/desktop/tests/native-template.test.ts
@@ -10,16 +10,18 @@
// 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, rmSync, writeFileSync, existsSync } from 'node:fs';
+import { mkdtempSync, 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,
+ listNativeTemplates, removeNativeTemplate, downloadNativeTemplate,
} from '../electron/nativeTemplates';
import { listPlatforms } from '../electron/platformCatalog';
import {
- requiredTemplateFiles, installedTemplateDir, TEMPLATE_FORMAT, TEMPLATE_MANIFEST,
+ requiredTemplateFiles, installedTemplateDir, parseTemplateIndex,
+ TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_INDEX,
} from '../../build-tools/utils/nativeTemplate.js';
import { makeZip } from '../../build-tools/utils/zip.js';
@@ -140,6 +142,109 @@ describe('installing a runtime template', () => {
});
});
+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-arm64', platform: 'ios', abi: 'arm64',
+ file: `estella-native-ios-arm64-${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 };
+ }
+
+ 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-arm64', versionMismatch: false });
+ expect(resolveNativeTemplate('ios', VERSION)).not.toBeNull();
+ expect(served).toEqual([
+ `https://example.test/r/${TEMPLATE_INDEX}`,
+ `https://example.test/r/estella-native-ios-arm64-${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-arm64-v8a 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-arm64', platform: 'ios', abi: 'arm64', 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-arm64', platform: 'ios', abi: 'arm64', 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'), wechat: path.join(scratch, 'wx') });
const iosRow = async () => (await listPlatforms(null, dirs(), VERSION)).find((r) => r.id === 'ios')!;