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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(native): the Windows and Android hosts run the game's JS on V8, with its JIT
yhhf159162bf1a1
diff --git a/bench/aot-native/README.md b/bench/aot-native/README.mdindex 236ca7079..5f1439dc7 100644--- a/bench/aot-native/README.md+++ b/bench/aot-native/README.md@@ -48,6 +48,22 @@ same-machine ratio sees it: an engine that stopped dispatching reads ~1x. A millceiling would not — one calibrated on this machine fails on slower ones and passes onfaster ones regardless of the code.+## The JIT host (2026-11-04, i5-14600K, Windows)++The Windows and Android hosts now embed V8 (`native/host/js/esjs.hpp`), so on them the+*interpreted* export is a JIT frame. The same bench, the same tree, the two hosts side+by side (`BENCH_TEMPLATE` points at the QuickJS template; the desktop host runs with+`ESTELLA_HIDDEN_WINDOW=1`, which the bench sets):++| body | build | QuickJS-ng host | V8 host |+|---|---|---|---|+| thin | interpreted | 76.28 ms | **8.33 ms** |+| thin | compiled | 2.46 ms | **1.35 ms** |++5000 entities, 300 frames after 120, best of 3. A game that marks nothing `@compiled`+gets the 9.2x with no change; a compiled system still takes ~6x off the JIT's frame.+The QuickJS column is the iOS road (and macOS / Linux, which embed no V8 yet).+## What was measured (2026-08-27, i5-14600K, Windows, QuickJS-ng in the native host)5000 entities, each with `Transform` + `Sprite` + a script component, 200 timed framesdiff --git a/bench/aot-native/frame-bench.mjs b/bench/aot-native/frame-bench.mjsindex 8d75f4a80..3c8dd491b 100644--- a/bench/aot-native/frame-bench.mjs+++ b/bench/aot-native/frame-bench.mjs@@ -127,7 +127,9 @@ const BODY = {const os = process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : 'linux';const version = JSON.parse(spawnSync(process.execPath, ['-p', 'JSON.stringify(require("./package.json"))'],{ cwd: ROOT, encoding: 'utf8' }).stdout || '{}').version;-const template = installedTemplateDir(version, os);+// BENCH_TEMPLATE runs a template that is not the installed one — how two builds of+// the host (a JIT one and an interpreter one) are measured against each other.+const template = process.env.BENCH_TEMPLATE || installedTemplateDir(version, os);if (!template || !existsSync(template)) {// Saying so was not enough: this exited 0, so the release gate read three// criteria as answered on every runner that never had a template. 2 is the@@ -290,6 +292,9 @@ function run(exe, label) {ESTELLA_BENCH_WARMUP: String(WARMUP),ESTELLA_BENCH_LABEL: label,ESTELLA_BENCH_DT: String(1 / 60),+ // Drawn and presented as in a visible run, never put on the screen:+ // a bench is a measurement, not an app in front of whoever is working.+ ESTELLA_HIDDEN_WINDOW: process.env.ESTELLA_HIDDEN_WINDOW ?? '1',},});requireNativeHostSuccess(r, label);@@ -306,6 +311,8 @@ function run(exe, label) {checksum: checksum ? checksum[1] : null,// Installed is not enough: a module can load and never be dispatched to.running: /AOT: (\w+) is running compiled/.exec(log)?.[1] ?? null,+ // What ran the JS, as the host says at boot (Runtime.cpp).+ engine: /JS engine: ([^\r\n]+)/.exec(log)?.[1]?.trim() ?? null,};}@@ -368,7 +375,10 @@ try {// --------------------------------------------------------------------- report-console.log(`\nno-JIT frame — QuickJS-ng in the native host, ${ENTITIES} entities, `+// The host names its engine: a V8 host's interpreted build is the JIT frame, a+// QuickJS host's the no-JIT one, and the two are not the same comparison.+const engine = rows.find((r) => r.engine)?.engine ?? 'an unnamed JS engine';+console.log(`\nnative frame — ${engine} in the native host, ${ENTITIES} entities, `+ `${FRAMES} frames after ${WARMUP}, best of ${PAIR_REPS}\n`);// `tick` is the microtask drain, not the `update` call: that one only schedules an// async tick. `draws` is a column because a body can move the render's cost —diff --git a/build-tools/cli.js b/build-tools/cli.jsindex f3d430aca..e94fd65ac 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -161,11 +161,13 @@ program.command('native').description('Build the native (embedded-Dawn) host for Android, iOS or the desktop').option('--target <target>', 'android, ios or macos', 'android')- .option('--fetch-deps', 'Check out Dawn + QuickJS-ng at the pinned commits, then stop', false)+ .option('--fetch-deps', 'Check out Dawn, QuickJS-ng and SDL at the pinned commits and fetch the pinned V8, then stop', false).option('--build-deps', 'Build Dawn for every ABI/slice the target needs, then stop (for warming a cache)', false).option('--dawn <dir>', 'Dawn source dir (default: the pinned checkout; or ESTELLA_DAWN_DIR)').option('--dawn-build <dir>', 'Dawn build dir for this target (default: <dawn>/out-<target>, built if absent)').option('--quickjs <dir>', 'QuickJS-ng source dir (default: the pinned checkout; or ESTELLA_QUICKJS_DIR)')+ .option('--js-engine <engine>', 'JS engine the host embeds: v8 (default where pinned: Windows, Android) or quickjs (iOS always; or ESTELLA_JS_ENGINE)')+ .option('--v8 <dir>', 'A prebuilt V8 (include/ + libraries) instead of the pinned one (or ESTELLA_V8_DIR)').option('--sdl <dir>', 'Desktop: SDL3 source dir or install prefix (default: the pinned checkout; or ESTELLA_SDL_DIR)').option('--steam-sdk <dir>', 'Desktop: a Steamworks SDK on this machine; its redistributable ships in the package (and in a template built with --template-out)').option('--macos-archs <archs>', 'Desktop: CMAKE_OSX_ARCHITECTURES (arm64, or "arm64;x86_64" for a universal build)')@@ -205,6 +207,8 @@ programdawn: options.dawn,dawnBuild: options.dawnBuild,quickjs: options.quickjs,+ jsEngine: options.jsEngine,+ v8: options.v8,sdl: options.sdl,steamSdk: options.steamSdk,macosArchs: options.macosArchs,diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex 58dc2678b..fd4fe8e63 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -18,7 +18,7 @@ import { requireSdk, requireNdk, sdkCmake } from '../utils/android.js';import { emitNativeTemplate, writeTemplateIndex, readEngineVersion } from './nativeTemplateEmit.js';import {fetchNativeDeps, pinnedDep, ensureDawnBuild, ensureSdlBuild, dawnLibrary,- isDesktopTarget, depsCacheKey, DAWN_TARGETS, MACOS_MIN,+ isDesktopTarget, depsCacheKey, DAWN_TARGETS, MACOS_MIN, fetchV8, v8Platform,} from './nativeDeps.js';import {ANDROID_ABIS, BYTECODE_FILE, findTemplate, iosTemplateSources, templateStoreDir,@@ -269,7 +269,7 @@ async function stageEditorHeaders(rootDir, quickjs) {// Every generated artifact goes in the build tree; nothing committed can drift// from the reflection / SDK / bootstrap source.-async function prepareGenerated(rootDir, buildDir, quickjs) {+async function prepareGenerated(rootDir, buildDir, quickjs, engine = 'quickjs') {if (!existsSync(quickjs)) {throw new Error(`QuickJS source dir not found: ${quickjs}. Clone `+ 'https://github.com/quickjs-ng/quickjs (see native/README.md).');@@ -285,8 +285,14 @@ async function prepareGenerated(rootDir, buildDir, quickjs) {await generateSdkBundle(rootDir, genDir);logger.step('Embedding the host bootstrap (native/host/bootstrap.js)...');await generateBootstrap(rootDir, genDir);- logger.step('Precompiling the bundle to bytecode (so the first launch need not)...');- await precompileBundleBytecode(rootDir, genDir, quickjs);+ if (engine === 'quickjs') {+ logger.step('Precompiling the bundle to bytecode (so the first launch need not)...');+ await precompileBundleBytecode(rootDir, genDir, quickjs);+ } else {+ // A V8 host compiles the bundle itself and caches the result on the device;+ // QuickJS bytecode beside it would be dead weight in every package.+ await rm(path.join(genDir, BYTECODE_FILE), { force: true });+ }await stageEditorHeaders(rootDir, quickjs);return genDir;}@@ -325,6 +331,31 @@ function quickjsDir(options) {return options.quickjs || process.env.ESTELLA_QUICKJS_DIR || pinnedDep('quickjs');}+/**+ * The JS engine a target's host embeds, and the V8 it embeds when that is V8.+ *+ * V8 wherever one is pinned (the Windows desktop, Android) — a JIT, so the SDK and+ * the game run compiled as they do in a browser; QuickJS everywhere else, and on+ * iOS always. `--js-engine quickjs` (or ESTELLA_JS_ENGINE) builds the interpreter+ * anywhere, which is how the no-JIT road stays measurable on a desktop. The same+ * "nothing has to be passed" rule as Dawn: a V8 that is not fetched yet is fetched.+ */+async function jsEngineFor(options, target) {+ const want = (options.jsEngine || process.env.ESTELLA_JS_ENGINE || '').toLowerCase();+ if (want && want !== 'v8' && want !== 'quickjs') {+ throw new Error(`--js-engine must be v8 or quickjs (got "${want}").`);+ }+ const platform = v8Platform(target);+ if (want === 'quickjs' || (!want && !platform)) return { engine: 'quickjs', v8: null };+ if (!platform) {+ throw new Error(`No V8 is pinned for ${target}: its host embeds QuickJS (drop --js-engine v8).`);+ }+ // fetchV8 answers at once when the pinned version is already there, and+ // replaces one that is not — so a cached deps dir can never hand over a stale V8.+ const dir = options.v8 || process.env.ESTELLA_V8_DIR || await fetchV8(platform);+ return { engine: 'v8', v8: dir };+}+/** SDL's install prefix for a desktop target, built if it is not built yet — the* same "nothing has to be passed" rule as {@link dawnPaths}. */async function sdlPrefix(options, target) {@@ -367,7 +398,8 @@ async function buildDesktopHost(options) {const buildDir = path.join(rootDir, DESKTOP_BUILD_DIR[target]);await mkdir(buildDir, { recursive: true });- const genDir = await prepareGenerated(rootDir, buildDir, quickjs);+ const js = await jsEngineFor(options, target);+ const genDir = await prepareGenerated(rootDir, buildDir, quickjs, js.engine);const deploymentTarget = options.macosMin || MACOS_MIN;logger.step(`Configuring desktop host (${target})...`);@@ -386,6 +418,8 @@ async function buildDesktopHost(options) {`-DESTELLA_QUICKJS_DIR=${fwd(quickjs)}`,`-DESTELLA_SDL_DIR=${fwd(sdl)}`,`-DESTELLA_NATIVE_GEN_DIR=${fwd(genDir)}`,+ `-DESTELLA_JS_ENGINE=${js.engine}`,+ `-DESTELLA_V8_DIR=${js.v8 ? fwd(js.v8) : ''}`,], { cwd: rootDir });logger.step('Building desktop host...');@@ -435,9 +469,11 @@ async function buildAndroidHost(options) {// the QuickJS host — a game script driving the engine through the generated// bindings + the real SDK ptrAccessors.const quickjs = quickjsDir(options);+ const js = quickjs ? await jsEngineFor(options, 'android') : null;// The generated sources are the same for every ABI (bindings, the SDK bundle,// its bytecode), so they live once beside the per-ABI trees.- const genDir = quickjs ? await prepareGenerated(rootDir, path.join(rootDir, 'build/cmake/native'), quickjs) : null;+ const genDir = quickjs+ ? await prepareGenerated(rootDir, path.join(rootDir, 'build/cmake/native'), quickjs, js.engine) : null;logger.step(`Configuring native host (${abi}, ${platform})...`);const configureArgs = [@@ -458,7 +494,8 @@ async function buildAndroidHost(options) {];if (ninja) configureArgs.push(`-DCMAKE_MAKE_PROGRAM=${ninja}`);if (quickjs) {- configureArgs.push(`-DESTELLA_QUICKJS_DIR=${fwd(quickjs)}`, `-DESTELLA_NATIVE_GEN_DIR=${fwd(genDir)}`);+ configureArgs.push(`-DESTELLA_QUICKJS_DIR=${fwd(quickjs)}`, `-DESTELLA_NATIVE_GEN_DIR=${fwd(genDir)}`,+ `-DESTELLA_JS_ENGINE=${js.engine}`, `-DESTELLA_V8_DIR=${js.v8 ? fwd(js.v8) : ''}`);}await runCommand(cmake, configureArgs, { cwd: rootDir });diff --git a/build-tools/tasks/nativeDeps.js b/build-tools/tasks/nativeDeps.jsindex 357f3029e..a60945e9b 100644--- a/build-tools/tasks/nativeDeps.js+++ b/build-tools/tasks/nativeDeps.js@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team//-// Dawn and QuickJS, checked out at the commits this release builds against.+// Dawn, QuickJS, SDL and V8, at the versions this release builds against.//// A runtime template is a binary other people install, so it has to be// reproducible: `git clone --depth 1` of a branch gives whatever landed today,@@ -10,8 +10,9 @@// without a flag.import path from 'path';-import { existsSync, readFileSync } from 'fs';-import { mkdir } from 'fs/promises';+import { createHash } from 'crypto';+import { existsSync, readFileSync, readdirSync } from 'fs';+import { cp, mkdir, readFile, rm, writeFile } from 'fs/promises';import config from '../build.config.js';import * as logger from '../utils/logger.js';import { runCommand, resolvePython } from '../utils/emscripten.js';@@ -46,6 +47,8 @@ export function depsCacheKey(target, rootDir = config.paths.root) {const pins = nativePins(rootDir);const parts = [pins.dawn.commit, pins.quickjs.commit];if (isDesktopTarget(target)) parts.push(pins.sdl?.commit ?? 'no-sdl-pin');+ // No V8 here, on purpose: it is downloaded, not built, and fetchV8 checks its+ // own stamp against the pin — keying on it would only rebuild Dawn for nothing.return `native-deps-${target}-${parts.join('-')}`;}@@ -98,12 +101,111 @@ export async function fetchNativeDeps(options = {}) {// to remember to ask for is one the next person's build is missing.const sdl = await fetchAt(path.join(deps, 'sdl'), pins.sdl.repo, pins.sdl.commit, 'SDL3');+ // Prebuilt archives rather than checkouts: V8 builds only with Chromium's own+ // toolchain. Both are fetched, like SDL, so no build has to remember to ask.+ const v8 = {};+ for (const platform of ['windows', 'android']) {+ if (pins.v8?.[platform]) v8[platform] = await fetchV8(platform, { root: rootDir, depsDir: deps });+ }+logger.success(`Native dependencies ready in ${path.relative(rootDir, deps) || deps}`);logger.info('Build with: node build-tools/cli.js native (Android)');logger.info(' node build-tools/cli.js native --target ios');logger.info(' node build-tools/cli.js native --target macos');logger.info(' node build-tools/cli.js native --target windows (from a vcvars64 shell)');- return { dawn, quickjs, sdl };+ return { dawn, quickjs, sdl, v8 };+}++/**+ * The prebuilt V8 a target embeds, keyed by what the archive is built for: the+ * Windows build serves the Windows desktop host, the NDK build every Android ABI.+ * Null where the host embeds QuickJS (iOS, and the desktops no V8 is pinned for).+ */+export function v8Platform(target) {+ return target === 'windows' || target === 'android' ? target : null;+}++/** Where a fetched V8 lands: `include/` plus the platform's libraries. */+export function v8Dir(platform, rootDir = config.paths.root) {+ return path.join(nativeDepsDir(rootDir), `v8-${platform}`);+}++async function download(url, sha256, label) {+ logger.step(`Downloading ${label}...`);+ const res = await fetch(url);+ if (!res.ok) throw new Error(`${label}: ${url} answered ${res.status}`);+ const bytes = Buffer.from(await res.arrayBuffer());+ const got = createHash('sha256').update(bytes).digest('hex');+ if (got !== sha256) {+ throw new Error(`${label}: sha256 ${got} is not the pinned ${sha256} — refusing an archive `+ + 'that is not the one this release was built against.');+ }+ return bytes;+}++/** Unpack a zip or a .tgz with Python's standard library: one spelling for every+ * OS a build runs on, where `tar` and `unzip` disagree about zips. */+async function extract(archive, into, kind) {+ const script = kind === 'zip'+ ? 'import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])'+ : 'import sys, tarfile; tarfile.open(sys.argv[1]).extractall(sys.argv[2])';+ await runCommand(await resolvePython(), ['-c', script, archive, into], { silent: true });+}++/**+ * Fetch and lay out the pinned V8 for @p platform, once per version.+ *+ * windows include/ + lib/Release/{v8,v8_libbase,v8_libplatform}.dll(.lib), the+ * ICU and zlib DLLs, icudtl.dat — the two NuGet packages, merged.+ * android include/ + jni/<abi>/libv8android.so — out of the npm package's AAR.+ *+ * @returns {Promise<string>} the directory to hand CMake as ESTELLA_V8_DIR.+ */+export async function fetchV8(platform, options = {}) {+ const rootDir = options.root || config.paths.root;+ const pin = nativePins(rootDir).v8;+ if (!pin?.[platform]) throw new Error(`toolchain.manifest.json pins no V8 for ${platform}.`);+ const deps = options.depsDir || nativeDepsDir(rootDir);+ const dir = path.join(deps, `v8-${platform}`);+ const stamp = path.join(dir, '.estella-v8');+ const want = `${pin.version}\n${JSON.stringify(pin[platform])}`;+ if (existsSync(stamp) && (await readFile(stamp, 'utf8')) === want) {+ logger.info(`V8 ${pin.version} (${platform}) already fetched`);+ return dir;+ }+ await rm(dir, { recursive: true, force: true });+ const scratch = path.join(deps, `v8-${platform}.download`);+ await rm(scratch, { recursive: true, force: true });+ await mkdir(scratch, { recursive: true });++ if (platform === 'windows') {+ for (const [i, part] of pin.windows.entries()) {+ const archive = path.join(scratch, `part${i}.zip`);+ await writeFile(archive, await download(part.url, part.sha256, `V8 ${pin.version} (windows, ${i + 1}/${pin.windows.length})`));+ await extract(archive, dir, 'zip');+ }+ } else {+ const archive = path.join(scratch, 'v8.tgz');+ await writeFile(archive, await download(pin.android.url, pin.android.sha256, `V8 ${pin.version} (android)`));+ await extract(archive, scratch, 'tgz');+ const dist = path.join(scratch, 'package', 'dist');+ const aar = path.join(dist, 'org', 'chromium', 'v8-android');+ const versions = existsSync(aar)+ ? readdirSync(aar, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name) : [];+ const aarFile = versions.length === 1+ ? path.join(aar, versions[0], `v8-android-${versions[0]}.aar`) : null;+ if (!aarFile || !existsSync(aarFile)) throw new Error(`V8 (android): no AAR under ${aar}`);+ await mkdir(dir, { recursive: true });+ await extract(aarFile, dir, 'zip');+ await cp(path.join(dist, 'include'), path.join(dir, 'include'), { recursive: true });+ }+ if (!existsSync(path.join(dir, 'include', 'v8.h'))) {+ throw new Error(`V8 (${platform}): the archive laid out no include/v8.h under ${dir}`);+ }+ await rm(scratch, { recursive: true, force: true });+ await writeFile(stamp, want);+ logger.success(`V8 ${pin.version} (${platform}): ${dir}`);+ return dir;}/**diff --git a/build-tools/tasks/nativeTemplateEmit.js b/build-tools/tasks/nativeTemplateEmit.jsindex b46299182..798f97a1f 100644--- a/build-tools/tasks/nativeTemplateEmit.js+++ b/build-tools/tasks/nativeTemplateEmit.js@@ -20,7 +20,8 @@ import { buildTool, platformJar, ndkTool, ndkLibcxxShared, jdkTool } from '../utimport { makeZip, zipTree } from '../utils/zip.js';import {templateLayout, templateId, ANDROID_ABIS, templateAbis, writeTemplateManifest,- missingTemplateFiles, installedTemplateDir, templateZipName, TEMPLATE_INDEX, TEMPLATE_FORMAT,+ missingTemplateFiles, installedTemplateDir, templateZipName, TEMPLATE_INDEX, TEMPLATE_FORMAT, templateJsEngine,+ BYTECODE_FILE,} from '../utils/nativeTemplate.js';/** The Java shim's sources — the IME's own side of an editable field, which has to@@ -133,6 +134,21 @@ export async function writeTemplateIndex(dir, options = {}) {* @param {string} [options.zipTo] Also write the distributable archive here.* @returns {Promise<{dir: string, manifest: object, zip: string|null}>}*/+/**+ * The identity of the SDK bundle a host was built with: FNV-1a 64 of the bytes it+ * compiles (gen/esengine_bundle.embedded.js), as Runtime.cpp computes it. The gen+ * dir is wherever this platform's bytecode entry points, built or not.+ */+function embeddedSdkIdentity(layout, ctx) {+ const entry = layout.find((e) => e.rel.endsWith(BYTECODE_FILE));+ const from = entry?.from(ctx);+ const embedded = from ? path.join(path.dirname(from), 'esengine_bundle.embedded.js') : null;+ if (!embedded || !existsSync(embedded)) return {};+ let hash = 1469598103934665603n;+ for (const byte of readFileSync(embedded)) hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 1099511628211n);+ return { sdkBundle: hash.toString(16).padStart(16, '0') };+}+export async function emitNativeTemplate(options) {const root = options.root || config.paths.root;const platform = options.platform;@@ -169,12 +185,20 @@ export async function emitNativeTemplate(options) {}}- for (const entry of templateLayout(platform, { abis: options.abis })) {+ const layout = templateLayout(platform, { abis: options.abis });+ const built = (rel) => {+ const other = layout.find((e) => e.rel === rel);+ const from = other && !other.produced ? other.from(ctx) : null;+ return !!from && existsSync(from);+ };+ for (const entry of layout) {if (entry.produced) continue;const src = entry.from(ctx);const dest = path.join(dir, entry.rel);if (!src || !existsSync(src)) {if (entry.optional) {+ // Not owed at all — a V8 host's template carries no QuickJS bytecode.+ if (entry.excusedBy && built(entry.excusedBy)) continue;if (!kept.includes(entry.abi)) {logger.warn(`Template omits ${entry.rel} (not built): ${src ?? 'no source'}`);}@@ -208,6 +232,13 @@ export async function emitNativeTemplate(options) {platform,engineVersion,spineVersion: options.spineVersion || '4.2',+ // What runs the game's JS, so the editor (and a person) can tell a JIT+ // template from an interpreter one without opening the binary.+ jsEngine: templateJsEngine(dir, platform),+ // Which SDK the host embeds — the identity its compile cache is keyed by —+ // so a stale template can be told from a current one whichever engine runs+ // it (a V8 template has no bytecode to read that off).+ ...embeddedSdkIdentity(layout, ctx),...(platform === 'ios' ? { deploymentTarget: options.deploymentTarget || '17.0' } : {}),...(platform === 'android'? { androidPlatform: options.androidPlatform || 'android-29', abis: templateAbis(dir) }diff --git a/build-tools/utils/desktopApp.js b/build-tools/utils/desktopApp.jsindex e111f7d70..3bc6f06e1 100644--- a/build-tools/utils/desktopApp.js+++ b/build-tools/utils/desktopApp.js@@ -128,7 +128,7 @@ export async function assembleDesktopApp(options) {+ 'at redistributable_bin/<os>/. This build reaches no store.');}let steamLibrary = null;- for (const lib of [sources.d3dCompiler, steamLib]) {+ for (const lib of [sources.d3dCompiler, steamLib, ...sources.v8Runtime]) {if (!lib || !existsSync(lib)) continue;const shipped = path.join(besideExe, path.basename(lib));await cp(lib, shipped);diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.tsindex aba8b1180..099eb13d3 100644--- a/build-tools/utils/nativeTemplate.d.ts+++ b/build-tools/utils/nativeTemplate.d.ts@@ -47,6 +47,12 @@ export interface FoundTemplate {export const TEMPLATE_FORMAT: number;export const TEMPLATE_MANIFEST: string;export const BYTECODE_FILE: string;+/** What a V8 desktop host loads beside itself on Windows (all or none). */+export const V8_WINDOWS_RUNTIME: readonly string[];+/** The V8 an Android V8 host links, one per ABI beside the host library. */+export const V8_ANDROID_LIBRARY: string;+/** The JS engine a template's host embeds, read off the files it carries. */+export function templateJsEngine(dir: string, platform: TemplatePlatform): 'v8' | 'quickjs';export const ANDROID_ABIS: readonly string[];/** The ABIs a phone can run; a package carries only these unless asked for the emulator's. */export const ANDROID_DEVICE_ABIS: readonly string[];@@ -71,6 +77,8 @@ export interface TemplateEntry {optional?: boolean;/** Produced by the emitter rather than copied (the Java shim's dex). */produced?: boolean;+ /** Not owed when this other entry is present (a V8 template owes no QuickJS bytecode). */+ excusedBy?: string;}export function templateLayout(platform: TemplatePlatform, options?: { abis?: readonly string[] }): TemplateEntry[];@@ -141,6 +149,8 @@ export function desktopTemplateSources(dir: string, platform?: TemplatePlatform)bytecode: string;/** Windows only. */d3dCompiler: string;+ /** A V8 host's runtime, beside the executable; empty in a QuickJS template. */+ v8Runtime: string[];/** Steam's redistributable, when the template was emitted with an SDK. */steamRedist: string;};diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.jsindex 01ec03f62..03bfb299b 100644--- a/build-tools/utils/nativeTemplate.js+++ b/build-tools/utils/nativeTemplate.js@@ -47,6 +47,29 @@ export const DEFAULT_ICON = 'icon.png';*/export const D3D_COMPILER = 'd3dcompiler_47.dll';+/**+ * What a V8 desktop host loads beside itself on Windows: V8 is a set of DLLs plus+ * the Intl data its build carries. All or none — a QuickJS host has none of them,+ * and a V8 host missing one does not start (see native/host/js/esjs_v8.cpp).+ */+export const V8_WINDOWS_RUNTIME = [+ 'v8.dll', 'v8_libbase.dll', 'v8_libplatform.dll', 'icuuc.dll', 'icui18n.dll', 'zlib.dll', 'icudtl.dat',+];++/** The V8 an Android V8 host links, one per ABI beside the host library. */+export const V8_ANDROID_LIBRARY = 'libv8android.so';++/** The JS engine a template's host embeds, read off the files it carries: 'v8'+ * when the V8 runtime is there, 'quickjs' otherwise. */+export function templateJsEngine(dir, platform) {+ if (platform === 'windows') return existsSync(path.join(dir, 'v8.dll')) ? 'v8' : 'quickjs';+ if (platform === 'android') {+ return ANDROID_ABIS.some((abi) => existsSync(path.join(dir, 'lib', abi, V8_ANDROID_LIBRARY)))+ ? 'v8' : 'quickjs';+ }+ return 'quickjs';+}+/** Steam's redistributable, per platform — the filename the host dlopens. */export const STEAM_REDIST = {windows: 'steam_api64.dll',@@ -166,10 +189,17 @@ export function templateLayout(platform, options = {}) {// Beside the game's own files, not in a directory of its own: the host// reads it through Platform::readAsset, which is one namespace — the// same one the APK's assets/ is.+ // QuickJS only: a V8 host compiles the bundle on the device (and caches+ // it), so its template carries the V8 runtime instead and owes no bytecode.{rel: BYTECODE_FILE, optional: true, releaseRequired: true,+ excusedBy: platform === 'windows' ? 'v8.dll' : undefined,from: (ctx) => path.join(ctx.root, buildDir, 'gen', BYTECODE_FILE),},+ ...(platform === 'windows' ? V8_WINDOWS_RUNTIME.map((rel) => ({+ rel, optional: true,+ from: (ctx) => path.join(ctx.root, buildDir, rel),+ })) : []),// The bundle description macOS wants; Windows has no counterpart, and// an entry every consumer would have to check for is worse than a// layout that differs where the platforms do.@@ -214,6 +244,13 @@ export function templateLayout(platform, options = {}) {rel: `lib/${abi}/libc++_shared.so`, strip: true, abi, optional: n > 0, releaseRequired: true,from: (ctx) => ctx.libcxxShared?.(abi),},+ {+ // The JIT a V8 host runs on — placed beside the host by its build+ // (native/CMakeLists.txt). Absent from a QuickJS build, which is why+ // it is optional: the host it belongs to cannot load without it.+ rel: `lib/${abi}/${V8_ANDROID_LIBRARY}`, strip: true, abi, optional: true,+ from: (ctx) => path.join(ctx.root, 'build/cmake/native', abi, V8_ANDROID_LIBRARY),+ },]);return [...libs,@@ -235,6 +272,7 @@ export function templateLayout(platform, options = {}) {// built from that template opened black.{rel: `assets/${BYTECODE_FILE}`, optional: true, releaseRequired: true,+ excusedBy: `lib/${abis[0]}/${V8_ANDROID_LIBRARY}`,from: (ctx) => path.join(ctx.root, 'build/cmake/native', 'gen', BYTECODE_FILE),},{@@ -312,9 +350,13 @@ export function noPackageAbisMessage(dir, options = {}) {+ `${options.emulator ? '' : ', or ask for the emulator ABI (emulatorAbi / --emulator-abi) to package an emulator-only template'}.`;}-/** What a template is missing, if anything — the one readiness test. */+/** What a template is missing, if anything — the one readiness test. An entry+ * `excusedBy` another is not owed when that other is there: a V8 host's template+ * owes no QuickJS bytecode. */export function missingTemplateFiles(dir, platform, options) {- return requiredTemplateFiles(platform, options).filter((rel) => !existsSync(path.join(dir, rel)));+ const has = (rel) => existsSync(path.join(dir, rel));+ return requiredTemplateEntries(platform, options)+ .filter((e) => !has(e.rel) && !(e.excusedBy && has(e.excusedBy))).map((e) => e.rel);}/**@@ -331,7 +373,8 @@ export function missingTemplateEntries(names, platform, options = {}) {const has = (e) => (e.kind === 'dir'? held.some((n) => n === e.rel || n.startsWith(`${e.rel}/`)): set.has(e.rel));- return requiredTemplateEntries(platform, options).filter((e) => !has(e)).map((e) => e.rel);+ return requiredTemplateEntries(platform, options)+ .filter((e) => !has(e) && !(e.excusedBy && set.has(e.excusedBy))).map((e) => e.rel);}// =============================================================================@@ -526,6 +569,8 @@ export function desktopTemplateSources(dir, platform = 'macos') {bytecode: path.join(dir, BYTECODE_FILE),/** Windows only; absent elsewhere. */d3dCompiler: path.join(dir, D3D_COMPILER),+ /** A V8 host's runtime, beside the executable; none of it in a QuickJS template. */+ v8Runtime: platform === 'windows' ? V8_WINDOWS_RUNTIME.map((rel) => path.join(dir, rel)) : [],/** Steam's redistributable, when the template was emitted with an SDK. */steamRedist: path.join(dir, STEAM_REDIST[platform] ?? STEAM_REDIST.macos),};diff --git a/docs/astro/src/content/docs/publishing/android-ios.mdx b/docs/astro/src/content/docs/publishing/android-ios.mdxindex a8f5a5350..62a869d16 100644--- a/docs/astro/src/content/docs/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/publishing/android-ios.mdx@@ -8,9 +8,11 @@ import { Aside, Steps } from '@astrojs/starlight/components';**Android** and **iOS** package your project as a **real native app**: the engine'sC++ core compiled to arm64, rendering through an embedded[Dawn](https://dawn.googlesource.com/dawn) (WebGPU → **Metal** on iOS, **Vulkan** on-Android), with your game scripts running on an embedded JS engine-([QuickJS-ng](https://github.com/quickjs-ng/quickjs)). It is **not** a WebView and-not a wrapper around the web build — there is no browser in the process.+Android), with your game scripts running on an embedded JS engine —+[V8](https://v8.dev/), the JIT Chrome runs, on Android, and+[QuickJS-ng](https://github.com/quickjs-ng/quickjs) on iOS, where Apple allows no+JIT. It is **not** a WebView and not a wrapper around the web build — there is no+browser in the process.The authoring model is identical to every other target. The same scenes, the samecomponents, the same TypeScript. Nothing in a project is mobile-specific.@@ -213,7 +215,7 @@ behaves exactly as it does in a browser.| Audio | Native mixer ([miniaudio](https://miniaud.io/)) — CoreAudio / AAudio || Text input | The platform's **soft keyboard** is the field's editing surface || Networking | The OS network stack (`NSURLSession` / `HttpURLConnection`) |-| Terrain and streamed worlds | Run on the native runtime. A terrain's layer textures go to the device as bytes, as every other texture does (a device has no wasm heap to copy them through), and a chunked world's maker uses a cancellation handle of its own, because QuickJS has no `AbortController` |+| Terrain and streamed worlds | Run on the native runtime. A terrain's layer textures go to the device as bytes, as every other texture does (a device has no wasm heap to copy them through), and a chunked world's maker uses a cancellation handle of its own, because the native runtime has no `AbortController` || Compressed textures | KTX2 transcoded to the device's format (ASTC → ETC2 → BC), with mip chains || Lifecycle | `onShow` / `onHide` and OS memory warnings reach the app |@@ -261,20 +263,28 @@ Per-asset **Import Settings** have a tab per platform, mobile targets includedso a texture can be compressed harder for a phone than for the web withouttouching the source PNG. See [Assets](/docs/assets/overview/).-### Your game script is interpreted+### How fast your game script runs-The engine runs native at full speed; **only your game script** runs on QuickJS,-which has no JIT (Apple's rules leave no other option, and Android is kept-identical rather than divergent). A per-entity loop written in TypeScript is the-one thing that costs meaningfully more here than in a browser — prefer the-engine's own systems and bulk APIs over hand-written per-entity iteration in the-hot path.+The engine runs native at full speed everywhere. Your game script does too on+**Android**: it runs on V8 with its JIT, the engine Chrome runs — the same script+is compiled to machine code as it would be in a browser, with nothing to change in+the project. Measured with the same host on a desktop CPU, a frame of 5,000 scripted+entities that took 76 ms on the interpreter takes 8 ms on V8; a phone is slower in+both columns, by about the same factor.-**On Android, a system marked `@compiled` runs as machine code instead.** The+On **iOS** your game script is interpreted, by QuickJS: Apple's rules allow no JIT+outside its own browser. A per-entity loop written in TypeScript is the one thing+that costs meaningfully more there than in a browser — prefer the engine's own+systems and bulk APIs over hand-written per-entity iteration in the hot path.++**On Android, a system marked `@compiled` runs as machine code before the JIT has+seen it.** Theexport cross-compiles every `/** @compiled */` system with the Android NDK, once per64-bit ABI the package carries (arm64-v8a, and x86_64 for the emulator), and theAPK carries each build in `lib/<abi>/`. Where the interpreter spends microseconds-per entity, the compiled system spends tens of nanoseconds. The NDK must be+per entity, the compiled system spends tens of nanoseconds — and it still takes+about six times off what the JIT leaves of a frame (8.3 ms → 1.4 ms in the+measurement above). The NDK must beinstalled on the exporting machine (Android Studio's SDK Manager, or`ANDROID_NDK_HOME`); the Package dialog says so when a project promises compiledsystems and it is missing. A system the host cannot bind falls back to the@@ -283,16 +293,20 @@ still runs every system interpreted.### The first launch after an install-Parsing the SDK bundle on a device takes ~14 s, and a compile cache does not exist-until one launch has paid for it — which would be the launch right after an-install. So the **bytecode is built with the app** and rides along in its assets:-fresh-install-to-first-frame is ~0.1 s rather than ~10 s.+On **Android**, V8 compiles the SDK bundle at launch — a fraction of a second — and+keeps the result in the app's cache, so later launches skip even that.++On **iOS**, parsing the SDK bundle on the interpreter takes ~14 s, and a compile+cache does not exist until one launch has paid for it — which would be the launch+right after an install. So the **bytecode is built with the app** and rides along in+its assets: fresh-install-to-first-frame is ~0.1 s rather than ~10 s.A build machine without a C compiler cannot produce it, and the app then compileson first run instead: it still works, but that one launch spends ten seconds on ascreen that a player reads as a hang. The boot record says which happened —-`SDK bundle: loaded from bytecode shipped with the app`, or `bundle: NO bytecode`-— so a slow first launch is a question with an answer rather than a mystery.+`SDK bundle: loaded from the cache shipped with the app`, or `bundle: no compile+cache` — so a slow first launch is a question with an answer rather than a mystery.+The record's first lines also name the engine (`engine: V8 …` or `engine: QuickJS-ng …`).### When something goes wrong on a devicediff --git a/docs/astro/src/content/docs/publishing/steam.mdx b/docs/astro/src/content/docs/publishing/steam.mdxindex 2689271d7..c0786e821 100644--- a/docs/astro/src/content/docs/publishing/steam.mdx+++ b/docs/astro/src/content/docs/publishing/steam.mdx@@ -12,8 +12,8 @@ also writes what SteamPipe needs.The desktop build is a **native app** — the engine's C++ core with an embedded[Dawn](https://dawn.googlesource.com/dawn) (Metal on macOS, D3D12 on Windows,-Vulkan on Linux) and-[QuickJS-ng](https://github.com/quickjs-ng/quickjs), on SDL3. There is no browser+Vulkan on Linux) and a JS engine — [V8](https://v8.dev/), with its JIT, on Windows;+[QuickJS-ng](https://github.com/quickjs-ng/quickjs) on macOS and Linux — on SDL3. There is no browserin the process, which is also why the Steam overlay, Steam Input and exclusivefullscreen behave the way players expect them to.diff --git a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdxindex b63d87de4..b34af3044 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx@@ -7,8 +7,8 @@ import { Aside, Steps } from '@astrojs/starlight/components';**Android** 和 **iOS** 把你的项目打包成**真正的原生应用**:引擎的 C++ 核心编译到 arm64,经内嵌的 [Dawn](https://dawn.googlesource.com/dawn) 渲染(WebGPU → iOS 上是 **Metal**、-Android 上是 **Vulkan**),游戏脚本跑在内嵌的 JS 引擎-([QuickJS-ng](https://github.com/quickjs-ng/quickjs))上。它**不是** WebView,+Android 上是 **Vulkan**),游戏脚本跑在内嵌的 JS 引擎上——Android 上是 [V8](https://v8.dev/)(Chrome 用的那个 JIT),+iOS 上是 [QuickJS-ng](https://github.com/quickjs-ng/quickjs)(Apple 不允许 JIT)。它**不是** WebView,也不是网页构建的壳——这个进程里没有浏览器。创作模型和其他任何目标完全一致。同样的场景、同样的组件、同样的 TypeScript。@@ -177,7 +177,7 @@ Android 的下限是 29,因为引擎的字体路径调用 `AFontMatcher_create`,| 音频 | 原生混音器([miniaudio](https://miniaud.io/))—— CoreAudio / AAudio || 文本输入 | 平台**软键盘**就是输入框的编辑面 || 网络 | 系统网络栈(`NSURLSession` / `HttpURLConnection`) |-| 地形与流式世界 | 在原生运行时上运行。地形的图层纹理和其他纹理一样以字节送到设备(设备上没有可供拷贝的 wasm 堆);分块世界的生成器使用自己的取消句柄,因为 QuickJS 没有 `AbortController` |+| 地形与流式世界 | 在原生运行时上运行。地形的图层纹理和其他纹理一样以字节送到设备(设备上没有可供拷贝的 wasm 堆);分块世界的生成器使用自己的取消句柄,因为原生运行时没有 `AbortController` || 压缩纹理 | KTX2 转码到设备支持的格式(ASTC → ETC2 → BC),含 mip 链 || 生命周期 | `onShow` / `onHide` 与系统内存警告都能到达应用 |@@ -221,30 +221,39 @@ Android 的下限是 29,因为引擎的字体路径调用 `AFontMatcher_create`,逐资产的**导入设置**每个平台一个页签,移动目标也在其中——所以一张纹理可以为手机压得比网页端更狠,而不用动源 PNG。见[资源](/docs/zh-cn/assets/overview/)。-### 你的游戏脚本是解释执行的+### 游戏脚本跑多快-引擎以原生全速运行;**只有你的游戏脚本**跑在 QuickJS 上,它没有 JIT-(Apple 的规则不留别的选项,Android 这边保持一致而不是分叉)。-用 TypeScript 写的逐实体循环,是这里比浏览器里明显更贵的那一样东西——+引擎在各平台都以原生全速运行。**Android** 上游戏脚本也一样:它跑在带 JIT 的 V8 上,+和 Chrome 是同一个引擎——同一份脚本会像在浏览器里那样编译成机器码,项目里什么都不用改。+用同一个宿主在桌面 CPU 上测:5000 个脚本实体的一帧,解释器要 76 毫秒,V8 上是 8 毫秒;+手机上两列都更慢,倍数大致相同。++**iOS** 上游戏脚本由 QuickJS 解释执行:Apple 不允许自家浏览器以外的 JIT。+用 TypeScript 写的逐实体循环,是那里比浏览器里明显更贵的那一样东西——热路径上优先用引擎自己的系统和批量 API,而不是手写逐实体迭代。-**在 Android 上,标记了 `@compiled` 的系统改为以机器码运行。** 导出时会用 Android NDK+**在 Android 上,标记了 `@compiled` 的系统不等 JIT 就以机器码运行。** 导出时会用 Android NDK把每个 `/** @compiled */` 系统交叉编译,包里每个 64 位 ABI 各一份(arm64-v8a,模拟器还有-x86_64),APK 把它们放在 `lib/<abi>/`。解释器每个实体要花微秒级,编译后只要几十纳秒。导出机器+x86_64),APK 把它们放在 `lib/<abi>/`。解释器每个实体要花微秒级,编译后只要几十纳秒——在 JIT 之上它仍能把一帧再快约 6 倍+(上面那组测量里 8.3 毫秒 → 1.4 毫秒)。导出机器需要装好 NDK(Android Studio 的 SDK Manager,或设置 `ANDROID_NDK_HOME`);项目承诺了编译系统而缺少 NDK 时,打包对话框会提示。宿主绑定不了的系统会在那一帧退回解释器,所以缺模块只影响速度,不影响正确性。iOS 目前仍全部解释执行。### 安装后的第一次启动-在设备上解析 SDK bundle 要约 14 秒,而编译缓存要等一次启动付过账才存在——+**Android** 上,V8 在启动时编译 SDK bundle——不到一秒——并把结果存进应用缓存,+之后的启动连这一步也省了。++**iOS** 上,解释器解析 SDK bundle 要约 14 秒,而编译缓存要等一次启动付过账才存在——那次启动恰好就是刚装完的那一次。所以**字节码是随应用一起构建**的,跟着资产一起走:全新安装到第一帧从约 10 秒变成约 0.1 秒。构建机上没有 C 编译器就产不出它,应用会退回到首次运行时现编译:能用,但那一次启动会有十秒停在一块被玩家读成「卡死」的画面上。启动记录会说明是哪种情况——-`SDK bundle: loaded from bytecode shipped with the app`,或者 `bundle: NO bytecode`-——所以首次启动慢是一个有答案的问题,而不是一桩悬案。+`SDK bundle: loaded from the cache shipped with the app`,或者 `bundle: no compile cache`+——所以首次启动慢是一个有答案的问题,而不是一桩悬案。记录开头还会写明用的是哪个引擎+(`engine: V8 …` 或 `engine: QuickJS-ng …`)。### 真机上出问题时diff --git a/docs/astro/src/content/docs/zh-cn/publishing/steam.mdx b/docs/astro/src/content/docs/zh-cn/publishing/steam.mdxindex 2556bbd4e..0bfa12b88 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/steam.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/steam.mdx@@ -10,8 +10,8 @@ Steam 是**桌面目标下的一个发行渠道**,不是一个单独的平台。外加一个开关,让导出顺带写出 SteamPipe 需要的东西。桌面构建是**原生应用**——引擎的 C++ 核心,内嵌-[Dawn](https://dawn.googlesource.com/dawn)(macOS 走 Metal,Windows 走 D3D12,Linux 走 Vulkan)与-[QuickJS-ng](https://github.com/quickjs-ng/quickjs),窗口与输入来自 SDL3。进程里没有浏览器,+[Dawn](https://dawn.googlesource.com/dawn)(macOS 走 Metal,Windows 走 D3D12,Linux 走 Vulkan)与 JS 引擎——Windows 上是带 JIT 的 [V8](https://v8.dev/),macOS 与 Linux 上是+[QuickJS-ng](https://github.com/quickjs-ng/quickjs)——窗口与输入来自 SDL3。进程里没有浏览器,这也是 Steam 覆盖层、Steam Input 和独占全屏能如玩家预期那样工作的原因。<Aside type="note" title="每个编辑器版本下载一次">diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex 5b1e6f510..8a213dec5 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -303,6 +303,68 @@ if(ESTELLA_QUICKJS_DIR)target_compile_definitions(qjs PRIVATE _GNU_SOURCE)es_silence_warnings(qjs)+ # The JS engine the host embeds, behind host/js/esjs.hpp. V8 where a JIT is+ # allowed and a prebuilt V8 was handed in (ESTELLA_V8_DIR, staged by+ # `cli native`); QuickJS otherwise — and always on iOS, which allows no JIT.+ # One build carries one engine, so the choice is a source file, not a branch.+ set(ESTELLA_JS_ENGINE "" CACHE STRING+ "JS engine for the native host: v8 | quickjs (empty: v8 when ESTELLA_V8_DIR is set and the platform allows a JIT)")+ set(ESTELLA_V8_DIR "" CACHE PATH "A prebuilt V8 (include/ + the platform's libraries)")+ set(ESJS_ENGINE "${ESTELLA_JS_ENGINE}")+ if(NOT ESJS_ENGINE)+ if(ESTELLA_V8_DIR AND NOT ESTELLA_IOS)+ set(ESJS_ENGINE v8)+ else()+ set(ESJS_ENGINE quickjs)+ endif()+ endif()+ add_library(esjs_engine INTERFACE)+ set(ESTELLA_V8_RUNTIME "")+ if(ESJS_ENGINE STREQUAL "v8")+ if(ESTELLA_IOS)+ message(FATAL_ERROR "iOS allows no JIT: the native host embeds QuickJS there.")+ endif()+ if(NOT EXISTS "${ESTELLA_V8_DIR}/include/v8.h")+ message(FATAL_ERROR "ESTELLA_JS_ENGINE=v8 needs ESTELLA_V8_DIR with include/v8.h (got '${ESTELLA_V8_DIR}').")+ endif()+ target_include_directories(esjs_engine INTERFACE "${ESTELLA_V8_DIR}/include")+ # The embedder must be compiled as V8 was, or V8::Initialize refuses it:+ # both prebuilts compress pointers on 64-bit targets.+ if(CMAKE_SIZEOF_VOID_P EQUAL 8)+ target_compile_definitions(esjs_engine INTERFACE V8_COMPRESS_POINTERS V8_31BIT_SMIS_ON_64BIT_ARCH)+ endif()+ if(ANDROID)+ set(_v8_so "${ESTELLA_V8_DIR}/jni/${ANDROID_ABI}/libv8android.so")+ if(NOT EXISTS "${_v8_so}")+ message(FATAL_ERROR "No V8 for ${ANDROID_ABI}: ${_v8_so} is missing.")+ endif()+ add_library(esjs_v8 SHARED IMPORTED)+ set_target_properties(esjs_v8 PROPERTIES IMPORTED_LOCATION "${_v8_so}")+ target_link_libraries(esjs_engine INTERFACE esjs_v8)+ elseif(WIN32)+ set(_v8_lib "${ESTELLA_V8_DIR}/lib/Release")+ # The Windows build carries Intl, whose data file ships beside the exe.+ target_compile_definitions(esjs_engine INTERFACE ESJS_V8_ICU)+ target_link_libraries(esjs_engine INTERFACE+ "${_v8_lib}/v8.dll.lib" "${_v8_lib}/v8_libbase.dll.lib" "${_v8_lib}/v8_libplatform.dll.lib"+ winmm dbghelp shlwapi)+ file(GLOB ESTELLA_V8_RUNTIME "${_v8_lib}/*.dll" "${_v8_lib}/icudtl.dat")+ else()+ message(FATAL_ERROR "No prebuilt V8 is wired for this platform yet: configure with -DESTELLA_JS_ENGINE=quickjs.")+ endif()+ set(ESJS_BACKEND host/js/esjs_v8.cpp)+ if(MSVC)+ # V8's headers test __cplusplus, which MSVC reports as C++98 without this.+ set_source_files_properties(host/js/esjs_v8.cpp PROPERTIES COMPILE_OPTIONS "/Zc:__cplusplus")+ endif()+ elseif(ESJS_ENGINE STREQUAL "quickjs")+ target_link_libraries(esjs_engine INTERFACE qjs)+ set(ESJS_BACKEND host/js/esjs_quickjs.cpp)+ else()+ message(FATAL_ERROR "ESTELLA_JS_ENGINE must be v8 or quickjs (got '${ESJS_ENGINE}').")+ endif()+ message(STATUS "Native host JS engine: ${ESJS_ENGINE}")+# basis_universal transcoder (KTX2 -> ETC2/ASTC/BC), one big vendored TU behind# host/media/ktx2_decode.cpp, plus basis's bundled single-file zstd decoder (KTX2# zstd supercompression). Third-party, so silence their warnings.@@ -321,6 +383,7 @@ if(ESTELLA_QUICKJS_DIR)host/Shot.cpphost/Bench.cpphost/EsnShim.cpp+ ${ESJS_BACKEND}host/bindings/HeapBindings.cpphost/bindings/EcsBindings.cpphost/bindings/RenderBindings.cpp@@ -360,7 +423,7 @@ if(ESTELLA_QUICKJS_DIR)COMPILE_OPTIONS "-x;objective-c++")target_link_libraries(estella_js_host esengine estella_physics estella_physics3destella_video estella_spine- estella_dragonbones qjs+ estella_dragonbones esjs_engine"-framework UIKit" "-framework QuartzCore" "-framework Foundation""-framework CoreMotion" "-framework CoreHaptics""-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox"@@ -396,7 +459,23 @@ if(ESTELLA_QUICKJS_DIR)set_target_properties(estella_js_host PROPERTIES OUTPUT_NAME estella_desktop)target_compile_definitions(estella_js_host PRIVATE ESTELLA_DESKTOP)target_link_libraries(estella_js_host esengine estella_physics estella_physics3d- estella_video estella_spine estella_dragonbones qjs SDL3::SDL3)+ estella_video estella_spine estella_dragonbones esjs_engine SDL3::SDL3)+ if(ESTELLA_V8_RUNTIME)+ # V8 is a set of DLLs plus its Intl data; the exe finds them beside it.+ add_custom_command(TARGET estella_js_host POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E copy_if_different ${ESTELLA_V8_RUNTIME} $<TARGET_FILE_DIR:estella_js_host>+ COMMENT "Placing the V8 runtime beside the desktop host")+ elseif(ESTELLA_WINDOWS)+ # A QuickJS host in a tree that once built V8: what that build placed+ # here would otherwise ride into this host's template as dead weight.+ add_custom_command(TARGET estella_js_host POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E rm -f+ $<TARGET_FILE_DIR:estella_js_host>/v8.dll $<TARGET_FILE_DIR:estella_js_host>/v8_libbase.dll+ $<TARGET_FILE_DIR:estella_js_host>/v8_libplatform.dll $<TARGET_FILE_DIR:estella_js_host>/icuuc.dll+ $<TARGET_FILE_DIR:estella_js_host>/icui18n.dll $<TARGET_FILE_DIR:estella_js_host>/zlib.dll+ $<TARGET_FILE_DIR:estella_js_host>/icudtl.dat+ COMMENT "Clearing a V8 runtime a previous build left beside the host")+ endif()if(ESTELLA_WINDOWS)# Dawn's D3D12 backend, DirectWrite for the font match, WinHTTP for the# fetch. miniaudio reaches WASAPI through the COM headers it includes.@@ -430,8 +509,19 @@ if(ESTELLA_QUICKJS_DIR)add_library(estella_js_host SHARED ${HOST_SOURCES} host/platform/android.cpp host/platform/android_device.cpp)target_link_libraries(estella_js_host esengine estella_physics estella_physics3destella_video estella_spine- estella_dragonbones qjs native_app_glue android log)+ estella_dragonbones esjs_engine native_app_glue android log)set_target_properties(estella_js_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")+ if(ESJS_ENGINE STREQUAL "v8")+ # The host links libv8android.so by name; the template takes it from+ # beside the host library (build-tools/utils/nativeTemplate.js).+ add_custom_command(TARGET estella_js_host POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_v8_so}" $<TARGET_FILE_DIR:estella_js_host>+ COMMENT "Placing libv8android.so beside the Android host")+ else()+ add_custom_command(TARGET estella_js_host POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E rm -f $<TARGET_FILE_DIR:estella_js_host>/libv8android.so+ COMMENT "Clearing a V8 a previous build left beside the host")+ endif()endif()# host/ is the include root: every host TU spells its siblings from there# ("Bindings.hpp", "media/glyph_raster.hpp"), and the generated TUs includediff --git a/native/README.md b/native/README.mdindex e29fe3c8e..3de839dde 100644--- a/native/README.md+++ b/native/README.md@@ -4,20 +4,31 @@ A native iOS/Android runtime for Estella: the **same** engine C++ core and thesame authoring model as the web build, compiled to arm64 and rendering through an**embedded [Dawn](https://dawn.googlesource.com/dawn)** (WebGPU → Metal on iOS /Vulkan on Android) — a real native app, **not a WebView**. Game scripts run on an-embedded JS engine ([QuickJS-ng](https://github.com/quickjs-ng/quickjs)); the-engine runs native (full speed), so only the game script is interpreted.+embedded JS engine: [V8](https://v8.dev/) with its JIT where one is allowed (Android,+the Windows desktop) and [QuickJS-ng](https://github.com/quickjs-ng/quickjs) where it+is not (iOS) — and on the desktops no V8 is pinned for yet (macOS, Linux). The engine+itself runs native, full speed, on all of them.This directory holds the host and the build recipe:-- **`host/`** — the app. A QuickJS runtime drives the engine through the **real+- **`host/`** — the app. A JS runtime drives the engine through the **realesengine SDK**, bundled to one file (`dist/index.native.bundled.js`, installing`ESEngine`); an editor export boots on it through the same `App` and `World` theweb build uses. One host with a platform seam, not one per OS:- `Host.{hpp,cpp}` — the contract a platform implements (`eshost::Platform`) andthe entry points its event loop drives: boot, the frame, lifecycle.- - `Runtime.{hpp,cpp}` — the QuickJS runtime and the state the host shares: the+ - `Runtime.{hpp,cpp}` — the JS runtime and the state the host shares: theenvironment the language does not ship (console, timers, a clock), the eval +- bytecode cache, and the layered boot (SDK bundle → bootstrap → project).+ compile cache, and the layered boot (SDK bundle → bootstrap → project).+ - `js/esjs.hpp` — the engine, behind one small surface every binding (hand-written+ and generated) is written against: values, objects, byte buffers, functions,+ calls, and V8's lifetime rule (a value lives as long as the scope that made it;+ `esjs::Ref` keeps one longer). `js/esjs_v8.cpp` and `js/esjs_quickjs.cpp` are the+ two backends; one build compiles one of them (`ESTELLA_JS_ENGINE`, chosen by+ `cli native --js-engine`). V8 comes prebuilt and pinned by sha256+ (`toolchain.manifest.json` → `native.v8`, fetched with `--fetch-deps`): version+ 10.0.139.9 on both Windows and Android, neither with V8's sandbox, which is what+ lets the host hand JS zero-copy views of engine memory.- `bootstrap.js` — the host's own JavaScript (the bridge install and the defaultinit/update), embedded at build time. A real .js file, not a C++ literal.- `bindings/` — the `es_*` surface, one TU per pillar (Ecs, Render, Assets,@@ -76,7 +87,7 @@ runs exactly the commands below; nothing about producing a template is CI-only.On the web, Box2D, the Spine runtime and the MPEG-1 decoder ship as standalone wasmside modules a realm fetches. A device has no dynamic-linking story and no reason forone, so the **same C sources** link straight into the host binary — all three are-vendored — and the SDK reaches them through the QuickJS wrappers EHT generates from+vendored — and the SDK reaches them through the native wrappers EHT generates fromtheir binding headers. `app.sideModules` still answers them, so the runtime's owngating installs physics or spine exactly as it does in a browser (see`sdk/src/ecs/nativeSideModules.ts`).@@ -103,7 +114,7 @@ the tree:| GL gate | `EstellaContext` under `ES_PLATFORM_WEB` | native drops the WebGL entry || Glyph source | `Platform::loadFont` + `host/media/glyph_raster.cpp` | the device has no 2D canvas: the OS names a font file, stb_truetype rasterizes, the engine's own `sdfFromAlpha` encodes || Bindings | `python -m eht --native-output` | `es_set_<C>` / `es_<C>_buffer` from the same reflection as the web embind bindings |-| Entry points | `python -m eht --native-functions` | `es_renderer_*`, `es_uiLayout_*`, `es_rm_*` — QuickJS wrappers over the SAME `bindings/*.hpp` declarations embind registers |+| Entry points | `python -m eht --native-functions` | `es_renderer_*`, `es_uiLayout_*`, `es_rm_*` — native wrappers (written against `js/esjs.hpp`) over the SAME `bindings/*.hpp` declarations embind registers || Data marshalling | `sdk/src/ecs/ptrAccessors.generated.ts` | POD components are wasm32/arm64 layout-identical → the generated accessors write native component memory unchanged (via a zero-copy `ArrayBuffer`) || Host platform | `eshost::Platform` (`host/Host.hpp`) | packaged assets, cache dir, backend, window surface + size, log — the only things the two OS glue files answer differently |@@ -132,8 +143,8 @@ NDK / CMake automatically — `ANDROID_HOME`, `ANDROID_NDK_HOME`, or AndroidStudio's default install), a JDK for the Java shim, and the SDK bundle(`pnpm --filter ./sdk build`) — the host embeds it.-**One-time: fetch the dependencies.** Dawn and QuickJS-ng are multi-GB / separate-projects, PINNED in `toolchain.manifest.json` rather than vendored or tracked as+**One-time: fetch the dependencies.** Dawn, QuickJS-ng, SDL and the prebuilt V8 are+multi-GB / separate projects, PINNED in `toolchain.manifest.json` rather than vendored or tracked assubmodules — a `--depth 1` clone of a branch makes a template unreproducible, andDawn fetches its own dependencies with a script anyway, so a submodule would savenobody the fetch while putting a huge clone in front of everyone who only buildsdiff --git a/native/host/Bench.hpp b/native/host/Bench.hppindex c9c8b5f9d..dd0db2b0b 100644--- a/native/host/Bench.hpp+++ b/native/host/Bench.hpp@@ -11,10 +11,11 @@* Bun/JavaScriptCore.** The proxy stopped being necessary the day this host learned to dispatch- * to compiled systems. It embeds QuickJS-ng, which has no JIT — the same- * constraint iOS puts on JavaScriptCore — so a desktop build IS a no-JIT+ * to compiled systems. A desktop build that embeds QuickJS-ng has no JIT —+ * the same constraint iOS puts on JavaScriptCore — so it IS a no-JIT* measurement of the real engine, the real SDK and a real exported- * project. What was missing was not a harness. It was a clock.+ * project; one that embeds V8 measures the JIT road the same way. What+ * was missing was not a harness. It was a clock.** Four spans, because one number cannot say what it is a share OF:* - `update` — the `update` call itself, which on this host onlydiff --git a/native/host/Bindings.hpp b/native/host/Bindings.hppindex 9d8dd6491..3066f770a 100644--- a/native/host/Bindings.hpp+++ b/native/host/Bindings.hpp@@ -32,43 +32,43 @@ namespace eshost {/** The linear heap bulk data crosses through — `es_heap` / `es_malloc` / `es_free`.* What makes a `…Ptr` argument mean the same thing here as it does on the web* (see heap.hpp), so an SDK subsystem module needs no native-only backend. */-void registerHeapBindings(HostState& h, JSValue global);+void registerHeapBindings(HostState& h, esjs::Val global);/** Entity + hierarchy: the base Registry surface the SDK's World drives. */-void registerEcsBindings(HostState& h, JSValue global);+void registerEcsBindings(HostState& h, esjs::Val global);/** Textures, the clear colour, the surface size, the camera list and the text* batch — what the SDK's renderer and glyph atlas need from the device. */-void registerRenderBindings(HostState& h, JSValue global);+void registerRenderBindings(HostState& h, esjs::Val global);/** Packaged assets, image decode, the on-disk cache and UTF-8 decoding. */-void registerAssetBindings(HostState& h, JSValue global);+void registerAssetBindings(HostState& h, esjs::Val global);/** es_audio* over the native engine — bound ONLY when a sound device came up, so* the SDK's hasAudioBindings() gates the native backend on real availability. */-void registerAudioBindings(HostState& h, JSValue global);+void registerAudioBindings(HostState& h, esjs::Val global);/** es_pollGamepads — the one half of input the engine pulls rather than is* pushed; see InputBindings.cpp. */-void registerInputBindings(HostState& h, JSValue global);+void registerInputBindings(HostState& h, esjs::Val global);/** es_steam_* — the store's half of achievements. Desktop only: bound where a* Steam client can exist, and answering `available: false` where one cannot. */-void registerSteamBindings(HostState& h, JSValue global);+void registerSteamBindings(HostState& h, esjs::Val global);/** es_fetch over the platform's native networking. */-void registerNetBindings(HostState& h, JSValue global);-void registerDeviceBindings(HostState& h, JSValue global);+void registerNetBindings(HostState& h, esjs::Val global);+void registerDeviceBindings(HostState& h, esjs::Val global);/** es_aot_* — the compiled systems a shipped build loads, and the naming a* host does for them. Absent on the web, where the module shares the engine's* memory and the rows are packed in JS. */-void registerAotBindings(HostState& h, JSValue global);+void registerAotBindings(HostState& h, esjs::Val global);/** es_textEditor_* over the platform's soft keyboard — bound ONLY when the* platform has one, so the SDK gates its editing surface on real availability* exactly as it does audio. */-void registerTextEditorBindings(HostState& h, JSValue global);+void registerTextEditorBindings(HostState& h, esjs::Val global);/** Run the JS callbacks for HTTP replies that arrived since the last frame. JS* thread only; {@link deliverFetch} queued them from the completion thread. */diff --git a/native/host/EsnShim.cpp b/native/host/EsnShim.cppindex 734860dfe..7d1acf7b8 100644--- a/native/host/EsnShim.cpp+++ b/native/host/EsnShim.cpp@@ -35,45 +35,34 @@ esengine::resource::ResourceManager& esn_rm() {// — Entity ids cross the boundary as the native Entity's raw u32. —-esengine::Entity esn_entity(JSContext* ctx, JSValueConst v) {- uint32_t raw = Entity::INVALID_RAW;- JS_ToUint32(ctx, &raw, v);- return Entity::fromRaw(raw);+esengine::Entity esn_entity(esjs::Val v) {+ return Entity::fromRaw(esjs::toUint32(v));}-// — Field readers the per-component marshalling is emitted against. —--bool esn_getnum(JSContext* ctx, JSValueConst obj, const char* key, double* out) {- JSValue p = JS_GetPropertyStr(ctx, obj, key);- bool ok = !JS_IsUndefined(p) && !JS_IsNull(p) && JS_ToFloat64(ctx, out, p) == 0;- JS_FreeValue(ctx, p);- return ok;+bool esn_getnum(esjs::Val obj, const char* key, double* out) {+ const esjs::Val p = esjs::get(obj, key);+ if (esjs::isNullish(p)) return false;+ *out = esjs::toNumber(p);+ return true;}-bool esn_getbool(JSContext* ctx, JSValueConst obj, const char* key, int* out) {- JSValue p = JS_GetPropertyStr(ctx, obj, key);- if (JS_IsUndefined(p) || JS_IsNull(p)) { JS_FreeValue(ctx, p); return false; }- *out = JS_ToBool(ctx, p);- JS_FreeValue(ctx, p);+bool esn_getbool(esjs::Val obj, const char* key, int* out) {+ const esjs::Val p = esjs::get(obj, key);+ if (esjs::isNullish(p)) return false;+ *out = esjs::toBool(p) ? 1 : 0;return true;}-void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, int n) {- JSValue arr = JS_GetPropertyStr(ctx, obj, key);- if (JS_IsArray(arr)) {- for (int i = 0; i < n; ++i) {- JSValue el = JS_GetPropertyUint32(ctx, arr, (uint32_t)i);- double d = 0;- JS_ToFloat64(ctx, &d, el);- dst[i] = (float)d;- JS_FreeValue(ctx, el);- }+void esn_getvec(esjs::Val obj, const char* key, float* dst, int n) {+ const esjs::Val arr = esjs::get(obj, key);+ if (!esjs::isArray(arr)) return;+ for (int i = 0; i < n; ++i) {+ dst[i] = static_cast<float>(esjs::toNumber(esjs::getAt(arr, static_cast<uint32_t>(i))));}- JS_FreeValue(ctx, arr);}-void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out) {- eshost::readByteSource(ctx, v, out);+void esn_bytes(esjs::Val v, std::vector<esengine::u8>& out) {+ eshost::readByteSource(v, out);}// — The heap a `uintptr_t` argument addresses. A number IS the offset (the SDK@@ -81,14 +70,10 @@ void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out) {// straight across, which we copy into the arena so the binding still receives// memory inside the region BoundarySpan validates against. —-uint32_t esn_argOffset(JSContext* ctx, JSValueConst v) {- if (JS_IsNumber(v)) {- uint32_t offset = 0;- JS_ToUint32(ctx, &offset, v);- return offset;- }+uint32_t esn_argOffset(esjs::Val v) {+ if (esjs::isNumber(v)) return esjs::toUint32(v);std::vector<esengine::u8> bytes;- eshost::readByteSource(ctx, v, bytes);+ eshost::readByteSource(v, bytes);if (bytes.empty()) return 0;const uint32_t offset = eshost::heapAlloc(bytes.size());void* dst = eshost::heapPtr(offset, bytes.size());@@ -97,8 +82,8 @@ uint32_t esn_argOffset(JSContext* ctx, JSValueConst v) {return offset;}-void esn_argRelease(JSContext* ctx, JSValueConst v, uint32_t offset) {- if (JS_IsNumber(v)) return; // the caller owns it+void esn_argRelease(esjs::Val v, uint32_t offset) {+ if (esjs::isNumber(v)) return; // the caller owns iteshost::heapFree(offset);}@@ -119,6 +104,6 @@ uint32_t esn_publish(EsnSlot& slot, const void* src, size_t bytes) {return slot.offset;}-JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size) {- return JS_NewArrayBuffer(ctx, reinterpret_cast<uint8_t*>(ptr), size, nullptr, nullptr, false);+esjs::Val esn_arraybuffer(void* ptr, size_t size) {+ return esjs::arrayBufferWrap(ptr, size);}diff --git a/native/host/Host.cpp b/native/host/Host.cppindex ac70b4695..5dd7d047f 100644--- a/native/host/Host.cpp+++ b/native/host/Host.cpp@@ -50,12 +50,8 @@ std::string svText(const WGPUStringView& v) {/** Has the SDK's render pipeline taken over the frame? It declares itself through* `es_jsOwnsFrame` (see HOST_FLAGS in the SDK's nativeBindings) once installed. */bool jsOwnsFrame(HostState& h) {- JSValue global = JS_GetGlobalObject(h.js);- JSValue v = JS_GetPropertyStr(h.js, global, "es_jsOwnsFrame");- const bool owns = JS_ToBool(h.js, v) != 0;- JS_FreeValue(h.js, v);- JS_FreeValue(h.js, global);- return owns;+ esjs::Enter enter;+ return esjs::toBool(esjs::get(esjs::global(), "es_jsOwnsFrame"));}/** The clear colour of the host's fallback pass. A game's own clear colour comes@@ -350,22 +346,24 @@ void frame(long long vsyncNanos) {// renderer's own endFrame (see Shot.hpp).shotBeforeFrame(*h.gfx, h.frame, (u32)h.w, (u32)h.h);- JSValue dt = JS_NewFloat64(h.js, deltaSeconds);benchUpdateBegin();- callJs(h, "update", 1, &dt);+ {+ esjs::Enter enter;+ const esjs::Val dt = esjs::number(deltaSeconds);+ callJs(h, "update", 1, &dt);+ }benchUpdateEnd();- JS_FreeValue(h.js, dt);benchPumpBegin();pumpJs(h); // run the App tick's async systems and any timers they setbenchPumpEnd();// Notify JS of voices that ended on their own (the audio thread never touches- // QuickJS; we poll on this thread and push, like touch). onEnd handlers may+ // the JS engine; we poll on this thread and push, like touch). onEnd handlers may// start new sounds synchronously — safe, pumpEnded iterates a snapshot.h.audio.pumpEnded([&h](int voiceId) {- JSValue arg = JS_NewInt32(h.js, voiceId);+ esjs::Enter enter;+ const esjs::Val arg = esjs::int32(voiceId);callJs(h, "es_onNativeAudioEnded", 1, &arg);- JS_FreeValue(h.js, arg);});// Run the callbacks for any HTTP replies that landed since last frame, then@@ -420,39 +418,39 @@ bool quitRequested() { return hostAlive() && host().quitRequested; }void touch(int type, int id, float x, float y) {if (!booted()) return;HostState& h = host();- JSValue args[4] = {- JS_NewInt32(h.js, type), JS_NewInt32(h.js, id),- JS_NewFloat64(h.js, x), JS_NewFloat64(h.js, y),+ esjs::Enter enter;+ const esjs::Val args[4] = {+ esjs::int32(type), esjs::int32(id),+ esjs::number(x), esjs::number(y),};callJs(h, "es_onNativeTouch", 4, args);- for (JSValue& v : args) JS_FreeValue(h.js, v);}void pointer(int type, int button, float x, float y) {if (!booted()) return;HostState& h = host();- JSValue args[4] = {- JS_NewInt32(h.js, type), JS_NewInt32(h.js, button),- JS_NewFloat64(h.js, x), JS_NewFloat64(h.js, y),+ esjs::Enter enter;+ const esjs::Val args[4] = {+ esjs::int32(type), esjs::int32(button),+ esjs::number(x), esjs::number(y),};callJs(h, "es_onNativePointer", 4, args);- for (JSValue& v : args) JS_FreeValue(h.js, v);}void wheel(float dx, float dy) {if (!booted()) return;HostState& h = host();- JSValue args[2] = {JS_NewFloat64(h.js, dx), JS_NewFloat64(h.js, dy)};+ esjs::Enter enter;+ const esjs::Val args[2] = {esjs::number(dx), esjs::number(dy)};callJs(h, "es_onNativeWheel", 2, args);- for (JSValue& v : args) JS_FreeValue(h.js, v);}void key(bool down, const char* code) {if (!booted() || !code || !code[0]) return;HostState& h = host();- JSValue args[2] = {JS_NewBool(h.js, down), JS_NewString(h.js, code)};+ esjs::Enter enter;+ const esjs::Val args[2] = {esjs::boolean(down), esjs::string(code)};callJs(h, "es_onNativeKey", 2, args);- for (JSValue& v : args) JS_FreeValue(h.js, v);}// The app went to background (visible=false) or returned. Suspend/resume the@@ -462,9 +460,11 @@ void setVisible(bool visible) {if (!booted()) return;HostState& h = host();if (visible) h.audio.resumeAll(); else h.audio.suspendAll();- JSValue arg = JS_NewBool(h.js, visible);- callJs(h, "es_onNativeVisibility", 1, &arg);- JS_FreeValue(h.js, arg);+ {+ esjs::Enter enter;+ const esjs::Val arg = esjs::boolean(visible);+ callJs(h, "es_onNativeVisibility", 1, &arg);+ }pumpJs(h);}diff --git a/native/host/Host.hpp b/native/host/Host.hppindex 31e8a6c28..cb213f837 100644--- a/native/host/Host.hpp+++ b/native/host/Host.hpp@@ -13,8 +13,8 @@* scenes) packaged with the app, booted by bootstrap.js through* ESEngine.initNativeGame.*- * The host itself is split by concern: Runtime.hpp owns the QuickJS- * runtime and the shared state, bindings/ owns the es_* surface (one TU+ * The host itself is split by concern: Runtime.hpp owns the JS runtime+ * (the engine is behind js/esjs.hpp) and the shared state, bindings/ owns the es_* surface (one TU* per pillar), and Host.cpp owns boot, the frame and lifecycle.* Everything that differs between Android and iOS lives behind* {@link eshost::Platform}; the glue (platform/android.cpp,@@ -293,7 +293,7 @@ void deliverTextEditorSubmit();/** The keyboard was dismissed without committing (back gesture, done). Thread-safe. */void deliverTextEditorCancel();-/** @brief Boots Dawn, EstellaContext, QuickJS, the SDK bundle and the packaged+/** @brief Boots Dawn, EstellaContext, the JS engine, the SDK bundle and the packaged* project. Call once, when a window first exists; @p platform must* outlive the host.* @return false if any stage failed (the reason is already logged). */diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cppindex bf1d2b59d..52f4a8183 100644--- a/native/host/Runtime.cpp+++ b/native/host/Runtime.cpp@@ -2,12 +2,13 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file Runtime.cpp- * @brief The QuickJS runtime the host owns: the environment the language does- * not ship, the binding installation, and the boot of the SDK + game.- * @details QuickJS is a language, not a runtime — no console, no timers, no+ * @brief The JS runtime the host owns: the environment the language does not+ * ship, the binding installation, and the boot of the SDK + game.+ * @details A JS engine is a language, not a runtime — no console, no timers, no* clock. Those are the host's job and they live here, beside the eval- * helpers and the bytecode cache that makes a ~700 KB SDK bundle load in- * milliseconds instead of seconds.+ * helpers and the compile cache that makes a ~700 KB SDK bundle load in+ * milliseconds instead of seconds. The engine itself (V8, or QuickJS+ * where no JIT is allowed) is behind js/esjs.hpp.** Three layers are stacked here, in order: the SDK bundle (embedded,* installs `ESEngine`), bootstrap.js (embedded, installs the bridge and@@ -79,129 +80,88 @@ double nowMs() {// Value readers// =============================================================================-void readByteSource(JSContext* ctx, JSValueConst v, std::vector<u8>& out) {- // Raw ArrayBuffer first — a typed-array view is not one, so it falls through.- size_t rawSize = 0;- if (uint8_t* raw = JS_GetArrayBuffer(ctx, &rawSize, v)) {- out.assign(raw, raw + rawSize);+void readByteSource(esjs::Val v, std::vector<u8>& out) {+ // An ArrayBuffer or any view of one (texture pixels, audio clip bytes, cache+ // writes) is read straight out of the engine's memory…+ esjs::Bytes bytes;+ if (esjs::bytesOf(v, &bytes)) {+ out.assign(bytes.data, bytes.data + bytes.size);return;}- JS_FreeValue(ctx, JS_GetException(ctx)); // not a raw ArrayBuffer — try a view-- size_t byteOffset = 0, byteLen = 0, bytesPerEl = 0;- JSValue ab = JS_GetTypedArrayBuffer(ctx, v, &byteOffset, &byteLen, &bytesPerEl);- if (!JS_IsException(ab)) {- size_t abSize = 0;- uint8_t* base = JS_GetArrayBuffer(ctx, &abSize, ab);- if (base && byteOffset + byteLen <= abSize) {- out.assign(base + byteOffset, base + byteOffset + byteLen);- }- JS_FreeValue(ctx, ab);- return;- }- JS_FreeValue(ctx, ab);- JS_FreeValue(ctx, JS_GetException(ctx)); // not a typed array — clear + index it- uint32_t len = 0;- JSValue lv = JS_GetPropertyStr(ctx, v, "length");- JS_ToUint32(ctx, &len, lv);- JS_FreeValue(ctx, lv);+ // …and a plain JS number array element by element.+ const uint32_t len = esjs::isObject(v) ? esjs::lengthOf(v) : 0;out.resize(len);- for (uint32_t i = 0; i < len; ++i) {- JSValue el = JS_GetPropertyUint32(ctx, v, i);- int32_t iv = 0;- JS_ToInt32(ctx, &iv, el);- out[i] = (u8)iv;- JS_FreeValue(ctx, el);- }+ esjs::Scope scope;+ for (uint32_t i = 0; i < len; ++i) out[i] = static_cast<u8>(esjs::toInt32(esjs::getAt(v, i)));}// =============================================================================-// The environment QuickJS does not ship: console, timers, a clock+// The environment an engine does not ship: console, timers, a clock// =============================================================================namespace {-JSValue jsConsoleWrite(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, bool error) {+esjs::Val consoleWrite(const esjs::Args& a, bool error) {std::string line;- for (int i = 0; i < argc; ++i) {- const char* s = JS_ToCString(ctx, argv[i]);- if (!s) continue;+ for (int i = 0; i < a.size(); ++i) {if (!line.empty()) line += ' ';- line += s;- JS_FreeCString(ctx, s);+ line += esjs::toString(a[i]);}hostLog(error, "%s", line.c_str());- return JS_UNDEFINED;-}-JSValue js_consoleLog(JSContext* ctx, JSValueConst t, int argc, JSValueConst* argv) {- return jsConsoleWrite(ctx, t, argc, argv, false);-}-JSValue js_consoleError(JSContext* ctx, JSValueConst t, int argc, JSValueConst* argv) {- return jsConsoleWrite(ctx, t, argc, argv, true);+ return esjs::undefined();}+esjs::Val js_consoleLog(const esjs::Args& a) { return consoleWrite(a, false); }+esjs::Val js_consoleError(const esjs::Args& a) { return consoleWrite(a, true); }-JSValue jsAddTimer(JSContext* ctx, int argc, JSValueConst* argv, bool repeat) {- if (argc < 1 || !JS_IsFunction(ctx, argv[0])) return JS_NewInt64(ctx, 0);- double delay = 0;- if (argc > 1) JS_ToFloat64(ctx, &delay, argv[1]);+esjs::Val addTimer(const esjs::Args& a, bool repeat) {+ if (!esjs::isFunction(a[0])) return esjs::int64(0);+ double delay = a.size() > 1 ? esjs::toNumber(a[1]) : 0;if (!(delay >= 0)) delay = 0; // also catches NaNHostState& h = host();const int64_t id = h.nextTimerId++;// A zero-delay interval would fire forever within one pump; clamp as browsers do.- h.timers.push_back(Timer{id, nowMs() + delay, repeat ? (delay > 1 ? delay : 1) : 0,- JS_DupValue(ctx, argv[0])});- return JS_NewInt64(ctx, id);-}-JSValue js_setTimeout(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- return jsAddTimer(ctx, argc, argv, false);-}-JSValue js_setInterval(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- return jsAddTimer(ctx, argc, argv, true);+ h.timers.push_back(Timer{id, nowMs() + delay, repeat ? (delay > 1 ? delay : 1) : 0, esjs::Ref(a[0])});+ return esjs::int64(id);}-JSValue js_clearTimer(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int64_t id = 0;- if (argc > 0) JS_ToInt64(ctx, &id, argv[0]);+esjs::Val js_setTimeout(const esjs::Args& a) { return addTimer(a, false); }+esjs::Val js_setInterval(const esjs::Args& a) { return addTimer(a, true); }+esjs::Val js_clearTimer(const esjs::Args& a) {+ const int64_t id = esjs::toInt64(a[0]);HostState& h = host();for (auto it = h.timers.begin(); it != h.timers.end(); ++it) {if (it->id != id) continue;- JS_FreeValue(h.js, it->fn);h.timers.erase(it);break;}- return JS_UNDEFINED;+ return esjs::undefined();}-JSValue js_performanceNow(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewFloat64(ctx, nowMs());-}--/** Drain QuickJS's microtask queue. app.tick() is async: its synchronous prefix- * (finishPlugins, resource inserts) runs on call, but the systems run in jobs. */-void pumpJobs(HostState& h) {- JSContext* c;- while (JS_ExecutePendingJob(h.rt, &c) > 0) { /* ran a job */ }-}+esjs::Val js_performanceNow(const esjs::Args&) { return esjs::number(nowMs()); }/** Fire the timers that came due. Callbacks may add or clear timers, so they run- * off a snapshot rather than while iterating. */+ * off a snapshot — each holding its own reference, so a callback that clears its+ * own interval does not release the function it is running. */void pumpTimers(HostState& h) {const double now = nowMs();- std::vector<Timer> due;+ std::vector<esjs::Ref> due;for (auto it = h.timers.begin(); it != h.timers.end();) {if (it->due > now) { ++it; continue; }- due.push_back(*it);- if (it->interval > 0) { it->due = now + it->interval; ++it; }- else it = h.timers.erase(it);+ if (it->interval > 0) {+ due.emplace_back(it->fn.get());+ it->due = now + it->interval;+ ++it;+ } else {+ due.push_back(std::move(it->fn));+ it = h.timers.erase(it);+ }}- for (Timer& t : due) {- JSValue r = JS_Call(h.js, t.fn, JS_UNDEFINED, 0, nullptr);- if (JS_IsException(r)) logJsError(h.js, "timer callback");- JS_FreeValue(h.js, r);- if (t.interval <= 0) JS_FreeValue(h.js, t.fn); // the erased entry's reference+ for (esjs::Ref& fn : due) {+ esjs::Scope scope;+ esjs::call(fn.get(), esjs::undefined(), 0, nullptr, "timer callback");}}-// FNV-1a of the bundle — a changed SDK invalidates its bytecode cache.+// FNV-1a of the bundle — a changed SDK invalidates its compile cache.uint64_t hashBytes(const char* p, size_t n) {uint64_t h = 1469598103934665603ull;for (size_t i = 0; i < n; i++) { h ^= (uint8_t)p[i]; h *= 1099511628211ull; }@@ -209,173 +169,134 @@ uint64_t hashBytes(const char* p, size_t n) {}/**- * Read a [8-byte hash][bytecode] blob, if its hash is the one we want. A blob that- * does not match, or does not load, is simply not used — the caller falls through- * to the next source and ultimately to compiling.+ * The payload of a [8-byte hash][cache] blob, if its hash is the one we want. A+ * blob that does not match is simply not used — the caller falls through to the+ * next source and ultimately to compiling.*/-bool tryBytecode(HostState& h, const u8* blob, size_t size, uint64_t want,- const char* origin, JSValue& out) {- // Every rejection says why. Falling back to a parse is CORRECT but costs- // seconds of black screen on first launch, so a build that shipped bytecode- // the host then declined has to be able to say so — silence here is how such a- // build passes for a working one.- if (size <= sizeof(uint64_t)) {- ESHOST_LOGI("SDK bundle: ignoring %s — %zu bytes is not a [hash][bytecode] blob", origin, size);+bool cachePayload(const std::vector<u8>& blob, uint64_t want, const char* origin,+ const u8** data, size_t* size) {+ // Every rejection says why. Falling back to a compile is CORRECT but can cost+ // seconds of black screen on an interpreter's first launch, so a build that+ // shipped a cache the host then declined has to be able to say so — silence+ // here is how such a build passes for a working one.+ if (blob.empty()) return false;+ if (blob.size() <= sizeof(uint64_t)) {+ ESHOST_LOGI("SDK bundle: ignoring %s — %zu bytes is not a [hash][cache] blob", origin, blob.size());return false;}uint64_t got = 0;- std::memcpy(&got, blob, sizeof(got));+ std::memcpy(&got, blob.data(), sizeof(got));if (got != want) {ESHOST_LOGI("SDK bundle: ignoring %s — built against a different bundle ""(%016llx, want %016llx)", origin,(unsigned long long)got, (unsigned long long)want);return false;}+ *data = blob.data() + sizeof(got);+ *size = blob.size() - sizeof(got);+ return true;+}- JSValue fn = JS_ReadObject(h.js, blob + sizeof(got), size - sizeof(got), JS_READ_OBJ_BYTECODE);- if (JS_IsException(fn)) {- JSValue e = JS_GetException(h.js);- const char* msg = JS_ToCString(h.js, e);- ESHOST_LOGE("SDK bundle: %s did not load (%s) — falling back to a parse", origin, msg ? msg : "?");- if (msg) JS_FreeCString(h.js, msg);- JS_FreeValue(h.js, e);- return false;+std::vector<u8> readFile(const std::string& path) {+ std::vector<u8> blob;+ FILE* f = path.empty() ? nullptr : fopen(path.c_str(), "rb");+ if (!f) return blob;+ fseek(f, 0, SEEK_END);+ const long sz = ftell(f);+ fseek(f, 0, SEEK_SET);+ if (sz > 0) {+ blob.resize((size_t)sz);+ if (fread(blob.data(), 1, blob.size(), f) != blob.size()) blob.clear();}- ESHOST_LOGI("SDK bundle: loaded from %s", origin);- bootNote("bundle: %s", origin);- out = JS_EvalFunction(h.js, fn);- return true;+ fclose(f);+ return blob;}/**- * Evaluate a global script, skipping the parse whenever bytecode for it exists.- * QuickJS is an interpreter: parsing the ~700 KB SDK bundle costs ~14 s on a- * device, and that parse is the black screen after an install. Three sources, in- * order of how early they are available:+ * Evaluate the SDK bundle, skipping the compile whenever a cache for it exists.+ * On an interpreter that compile is the black screen after an install (~14 s for+ * the ~700 KB bundle on a phone); on a JIT it is far less, but still not nothing.+ * Two sources, in order of how early they are available:*- * 1. Bytecode built with the app (`assets/esengine.native.bc`), so the FIRST- * launch is already fast. Present only if the build machine could produce it.- * 2. Bytecode this device compiled on an earlier launch.- * 3. The source, parsed — and cached on the way out, so step 2 works next time.+ * 1. A cache built with the app (`assets/esengine.native.<tag>`), so the FIRST+ * launch is already fast. Present only where the build machine can produce+ * one for the engine the device runs.+ * 2. The cache this device wrote on an earlier launch.*- * Every source is tagged with a hash of the bundle it was built from, so a stale- * one is skipped rather than trusted. Cache file: [8-byte hash][bytecode].+ * With neither, the source is compiled — and the cache written on the way out, so+ * the second source works next time. Every blob is tagged with a hash of the+ * bundle it was built from, so a stale one is skipped rather than trusted; the+ * engine checks its own build on top. File: [8-byte hash][cache].*/-JSValue evalCachedScript(HostState& h, const char* src, size_t srcLen, const char* filename,- const std::string& cachePath, const char* shippedAsset) {+bool evalCachedScript(HostState& h, const char* src, size_t srcLen, const char* filename,+ const std::string& cachePath, const std::string& shippedAsset) {const uint64_t want = hashBytes(src, srcLen);- JSValue out;-- if (shippedAsset) {- const std::vector<u8> blob = readAsset(h, shippedAsset);- if (!blob.empty() && tryBytecode(h, blob.data(), blob.size(), want,- "bytecode shipped with the app", out)) {- return out;- }+ const u8* data = nullptr;+ size_t size = 0;+ const char* origin = nullptr;++ const std::vector<u8> shipped = readAsset(h, shippedAsset.c_str());+ const std::vector<u8> cached = readFile(cachePath);+ if (cachePayload(shipped, want, "the cache shipped with the app", &data, &size)) {+ origin = "the cache shipped with the app";+ } else if (cachePayload(cached, want, "the cache this device wrote", &data, &size)) {+ origin = "the cache this device wrote";}- if (!cachePath.empty()) {- FILE* f = fopen(cachePath.c_str(), "rb");- if (f) {- std::vector<u8> blob;- fseek(f, 0, SEEK_END);- const long sz = ftell(f);- fseek(f, 0, SEEK_SET);- if (sz > 0) {- blob.resize((size_t)sz);- if (fread(blob.data(), 1, blob.size(), f) != blob.size()) blob.clear();- }- fclose(f);- if (!blob.empty() && tryBytecode(h, blob.data(), blob.size(), want,- "bytecode cache", out)) {- return out;- }- }+ if (!origin) bootNote("bundle: no compile cache — compiling on device, expect a slower first launch");+ esjs::CacheUse use = esjs::CacheUse::None;+ std::string why;+ std::vector<u8> fresh;+ const bool ok = esjs::runCached(std::string_view(src, srcLen), filename, data, size,+ &use, &why, cachePath.empty() ? nullptr : &fresh);+ if (use == esjs::CacheUse::Used) {+ ESHOST_LOGI("SDK bundle: loaded from %s", origin);+ bootNote("bundle: %s", origin);+ } else if (use == esjs::CacheUse::Rejected) {+ ESHOST_LOGE("SDK bundle: %s did not load (%s) — compiled instead", origin, why.c_str());+ bootNote("bundle: %s rejected — compiled on device", origin);}-- // Parse once (slow), cache the bytecode, run.- // No bytecode from either source: this launch pays the parse. Said plainly,- // because it is seconds of black screen and the question it raises ("did it- // crash?") is the one the record exists to answer.- bootNote("bundle: NO bytecode — parsing on device, expect a slow first launch");- JSValue fn = JS_Eval(h.js, src, srcLen, filename, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);- if (JS_IsException(fn)) return fn;- if (!cachePath.empty()) {- size_t bcLen = 0;- uint8_t* bc = JS_WriteObject(h.js, &bcLen, fn, JS_WRITE_OBJ_BYTECODE);- if (bc) {- FILE* f = fopen(cachePath.c_str(), "wb");- if (f) { fwrite(&want, sizeof(want), 1, f); fwrite(bc, 1, bcLen, f); fclose(f); }- js_free(h.js, bc);- ESHOST_LOGI("SDK bundle: compiled + cached bytecode (%zu bytes)", bcLen);+ if (!fresh.empty()) {+ if (FILE* f = fopen(cachePath.c_str(), "wb")) {+ fwrite(&want, sizeof(want), 1, f);+ fwrite(fresh.data(), 1, fresh.size(), f);+ fclose(f);+ ESHOST_LOGI("SDK bundle: compiled + cached (%zu bytes)", fresh.size());}}- return JS_EvalFunction(h.js, fn); // consumes fn+ return ok;}+void engineLog(bool error, const char* message) { hostLog(error, "%s", message); }+} // namespace// =============================================================================// Eval helpers// =============================================================================-void logJsError(JSContext* ctx, const char* where) {- JSValue e = JS_GetException(ctx);- const char* s = JS_ToCString(ctx, e);- ESHOST_LOGE("JS error in %s: %s", where, s ? s : "?");- if (s) JS_FreeCString(ctx, s);- // The stack too: a bare message ("Maximum call stack size exceeded") says- // nothing about which SDK path produced it, and a device is where you find out.- JSValue stack = JS_GetPropertyStr(ctx, e, "stack");- if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {- const char* st = JS_ToCString(ctx, stack);- if (st) { ESHOST_LOGE(" stack: %s", st); JS_FreeCString(ctx, st); }- }- JS_FreeValue(ctx, stack);- JS_FreeValue(ctx, e);-}--// QuickJS detects JS stack overflow by comparing the current C stack pointer-// against a top it records ONCE, at JS_NewRuntime. The runtime outlives the-// thread that made it: on Android an activity recreate keeps the process (and-// the booted engine) but hands every later JS call to a NEW glue thread, whose-// stack ASLR may map more than the 1MB budget below the recorded top — at which-// point every call, however flat, throws "Maximum call stack size exceeded"-// forever. Re-anchoring at each host→JS entry is the API's own answer to a-// runtime crossing threads, and costs one stack-pointer read.-void jsEntry(HostState& h) {- JS_UpdateStackTop(h.rt);-}--void evalJs(HostState& h, const std::string& src, const char* name) {- jsEntry(h);- JSValue r = JS_Eval(h.js, src.c_str(), src.size(), name, JS_EVAL_TYPE_GLOBAL);- if (JS_IsException(r)) logJsError(h.js, name);- JS_FreeValue(h.js, r);+void evalJs(HostState&, const std::string& src, const char* name) {+ esjs::Enter enter;+ esjs::run(src, name);}-void callJs(HostState& h, const char* fn, int argc, JSValue* argv) {- jsEntry(h);- JSValue global = JS_GetGlobalObject(h.js);- JSValue f = JS_GetPropertyStr(h.js, global, fn);- if (JS_IsFunction(h.js, f)) {- JSValue r = JS_Call(h.js, f, global, argc, argv);- if (JS_IsException(r)) logJsError(h.js, fn);- JS_FreeValue(h.js, r);- }- JS_FreeValue(h.js, f);- JS_FreeValue(h.js, global);+void callJs(HostState&, const char* fn, int argc, const esjs::Val* argv) {+ esjs::Enter enter;+ const esjs::Val global = esjs::global();+ const esjs::Val f = esjs::get(global, fn);+ if (esjs::isFunction(f)) esjs::call(f, global, argc, argv, fn);}void pumpJs(HostState& h) {- jsEntry(h);- pumpJobs(h);+ esjs::Enter enter;+ esjs::pumpMicrotasks();pumpTimers(h);- pumpJobs(h);+ esjs::pumpMicrotasks();+ esjs::pumpEngine();}-void bindGlobal(HostState& h, JSValue global, const char* name, JSCFunction* fn, int argc) {- JS_SetPropertyStr(h.js, global, name, JS_NewCFunction(h.js, fn, name, argc));+void bindGlobal(esjs::Val global, const char* name, esjs::NativeFn fn, int argc) {+ esjs::setFunction(global, name, fn, argc);}// =============================================================================@@ -384,33 +305,31 @@ void bindGlobal(HostState& h, JSValue global, const char* name, JSCFunction* fn,void initRuntime(HostState& h) {const double t0 = nowMs();- h.rt = JS_NewRuntime();- h.js = JS_NewContext(h.rt);- JSValue global = JS_GetGlobalObject(h.js);-- JS_SetPropertyStr(h.js, global, "W", JS_NewFloat64(h.js, h.w));- JS_SetPropertyStr(h.js, global, "H", JS_NewFloat64(h.js, h.h));- JS_SetPropertyStr(h.js, global, "S", JS_NewFloat64(h.js, h.w < h.h ? h.w : h.h));-- // The host environment the SDK expects but QuickJS (a language, not a runtime)- // does not provide: console, timers and a monotonic clock. Without them a- // rejected promise is silent and the asset cache's setTimeout throws.- JSValue console = JS_NewObject(h.js);- for (const char* name : {"log", "info", "debug", "trace"}) {- JS_SetPropertyStr(h.js, console, name, JS_NewCFunction(h.js, js_consoleLog, name, 1));- }- for (const char* name : {"warn", "error"}) {- JS_SetPropertyStr(h.js, console, name, JS_NewCFunction(h.js, js_consoleError, name, 1));- }- JS_SetPropertyStr(h.js, global, "console", console);-- bindGlobal(h, global, "setTimeout", js_setTimeout, 2);- bindGlobal(h, global, "setInterval", js_setInterval, 2);- bindGlobal(h, global, "clearTimeout", js_clearTimer, 1);- bindGlobal(h, global, "clearInterval", js_clearTimer, 1);- JSValue perf = JS_NewObject(h.js);- JS_SetPropertyStr(h.js, perf, "now", JS_NewCFunction(h.js, js_performanceNow, "now", 0));- JS_SetPropertyStr(h.js, global, "performance", perf);+ esjs::init(engineLog, nullptr);+ ESHOST_LOGI("JS engine: %s%s", esjs::engineName().c_str(), esjs::hasJit() ? " (JIT)" : " (interpreter)");+ bootNote("engine: %s", esjs::engineName().c_str());++ esjs::Enter enter;+ const esjs::Val global = esjs::global();+ esjs::set(global, "W", esjs::number(h.w));+ esjs::set(global, "H", esjs::number(h.h));+ esjs::set(global, "S", esjs::number(h.w < h.h ? h.w : h.h));++ // The host environment the SDK expects but an engine (a language, not a+ // runtime) does not provide: console, timers and a monotonic clock. Without+ // them a rejected promise is silent and the asset cache's setTimeout throws.+ const esjs::Val console = esjs::object();+ for (const char* name : {"log", "info", "debug", "trace"}) esjs::setFunction(console, name, js_consoleLog, 1);+ for (const char* name : {"warn", "error"}) esjs::setFunction(console, name, js_consoleError, 1);+ esjs::set(global, "console", console);++ bindGlobal(global, "setTimeout", js_setTimeout, 2);+ bindGlobal(global, "setInterval", js_setInterval, 2);+ bindGlobal(global, "clearTimeout", js_clearTimer, 1);+ bindGlobal(global, "clearInterval", js_clearTimer, 1);+ const esjs::Val perf = esjs::object();+ esjs::setFunction(perf, "now", js_performanceNow, 0);+ esjs::set(global, "performance", perf);// The es_* surface, one pillar at a time (see Bindings.hpp). The heap comes// first: it is what the generated entry points marshal buffers through.@@ -431,23 +350,20 @@ void initRuntime(HostState& h) {// The generated halves: per-component accessors, then the engine's binding// entry points — both from the same reflection the web's embind bindings come// from, so the SDK reaches the engine by the same names on either platform.- esn_register(h.js, global);- esn_register_functions(h.js, global);- JS_FreeValue(h.js, global);+ esn_register(global);+ esn_register_functions(global);// Layer 1: the real SDK bundle, embedded — installs `ESEngine`.const double tCtx = nowMs();- std::string bcPath = h.cacheDir.empty() ? std::string() : (h.cacheDir + "/esengine.native.bc");- JSValue br = evalCachedScript(h, kSdkBundleJS, kSdkBundleSize, "esengine.native.js",- bcPath, "esengine.native.qjsbc");- if (JS_IsException(br)) logJsError(h.js, "SDK bundle");- JS_FreeValue(h.js, br);+ const std::string cacheName = std::string("esengine.native.") + esjs::cacheTag();+ const std::string cachePath = h.cacheDir.empty() ? std::string() : (h.cacheDir + "/" + cacheName);+ evalCachedScript(h, kSdkBundleJS, kSdkBundleSize, "esengine.native.js", cachePath, cacheName);const double tBundle = nowMs();// Layer 2: the host bootstrap — the bridge over the es_* bindings, and the// default init/update that boots a packaged project.evalJs(h, kHostBootstrapJS, "bootstrap.js");- ESHOST_LOGI("boot ms — qjs ctx: %.0f | SDK bundle eval: %.0f", tCtx - t0, tBundle - tCtx);+ ESHOST_LOGI("boot ms — engine + bindings: %.0f | SDK bundle eval: %.0f", tCtx - t0, tBundle - tCtx);}bool runPackagedGame(HostState& h) {diff --git a/native/host/Runtime.hpp b/native/host/Runtime.hppindex d6ecb2edb..592f10956 100644--- a/native/host/Runtime.hpp+++ b/native/host/Runtime.hpp@@ -3,12 +3,13 @@/*** @file Runtime.hpp* @brief The host's INTERNAL surface: the state every part of it shares, and- * the QuickJS plumbing the binding TUs are written against.+ * the JS plumbing the binding TUs are written against.* @details Not part of the host's contract with a platform — that is Host.hpp.* This is what Host.cpp and the binding TUs share: one state struct, the- * JS runtime that owns the language-level environment QuickJS does not+ * JS runtime that owns the language-level environment an engine does not* ship (console, timers, a clock), and the value readers every binding- * needs. A binding TU includes this and nothing else of the host.+ * needs. A binding TU includes this and nothing else of the host; the+ * engine itself is behind js/esjs.hpp.** @author ESEngine Team* @date 2026@@ -21,9 +22,7 @@#include "Host.hpp"#include "media/native_audio.hpp"-extern "C" {-#include "quickjs.h"-}+#include "js/esjs.hpp"#include "esengine/core/EstellaContext.hpp"#include "esengine/ecs/Registry.hpp"@@ -37,13 +36,13 @@ extern "C" {namespace eshost {-/** A pending setTimeout / setInterval callback. QuickJS is only the language: the- * timers, like console, are the host's job. */+/** A pending setTimeout / setInterval callback. An engine is only the language:+ * the timers, like console, are the host's job. */struct Timer {int64_t id;double due; ///< nowMs() deadline.double interval; ///< Repeat period; 0 for a one-shot.- JSValue fn;+ esjs::Ref fn;};/**@@ -61,14 +60,12 @@ struct HostState {esengine::EstellaContext* ctx = nullptr;esengine::ecs::Registry* registry = nullptr;- // — Script: the QuickJS runtime the SDK and the game run in —- JSRuntime* rt = nullptr;- JSContext* js = nullptr;+ // — Script: the JS engine the SDK and the game run in (js/esjs.hpp) —std::vector<Timer> timers;int64_t nextTimerId = 1;- std::unordered_map<int, JSValue> fetchCallbacks; ///< in-flight es_fetch id -> JS callback+ std::unordered_map<int, esjs::Ref> fetchCallbacks; ///< in-flight es_fetch id -> JS callbackint nextFetchId = 1;- std::unordered_map<int, JSValue> wsCallbacks; ///< open es_wsOpen id -> JS event callback+ std::unordered_map<int, esjs::Ref> wsCallbacks; ///< open es_wsOpen id -> JS event callbackAudioEngine audio; ///< native sound (miniaudio); silent if no devicestd::string cacheDir; ///< reclaimable — SDK bytecode cache + hot-update content@@ -119,9 +116,9 @@ void hostLog(bool error, const char* fmt, ...);double nowMs();/**- * Bring up QuickJS with the environment the SDK expects but the language does not- * provide (console, timers, performance), install every es_* binding, then- * evaluate the SDK bundle and bootstrap.js. Leaves the packaged project's own+ * Bring up the JS engine with the environment the SDK expects but the language+ * does not provide (console, timers, performance), install every es_* binding,+ * then evaluate the SDK bundle and bootstrap.js. Leaves the packaged project's own* scripts and init() to {@link runPackagedGame}.*/void initRuntime(HostState& h);@@ -131,22 +128,16 @@ void initRuntime(HostState& h);bool runPackagedGame(HostState& h);/** Bind one global function. */-void bindGlobal(HostState& h, JSValue global, const char* name, JSCFunction* fn, int argc);+void bindGlobal(esjs::Val global, const char* name, esjs::NativeFn fn, int argc);-/** Report a pending JS exception through the platform log, with its stack. */-void logJsError(JSContext* ctx, const char* where);--/** Re-anchor QuickJS's stack-overflow check to the calling thread's stack.- * Must open every host→JS entry: the runtime outlives the thread that made it- * (Android activity recreate), and a stale anchor turns every call into a- * false "Maximum call stack size exceeded" — permanently. */-void jsEntry(HostState& h);--/** Evaluate a global script; exceptions are logged, not propagated. */+/** Evaluate a global script; exceptions are logged, not propagated. Opens its own+ * {@link esjs::Enter}. */void evalJs(HostState& h, const std::string& src, const char* name);-/** Call a global function by name; missing is a no-op, exceptions are logged. */-void callJs(HostState& h, const char* fn, int argc, JSValue* argv);+/** Call a global function by name; missing is a no-op, exceptions are logged.+ * Opens its own {@link esjs::Enter}, which the caller's argument values must+ * already be inside. */+void callJs(HostState& h, const char* fn, int argc, const esjs::Val* argv);/** One turn of the host's event loop: microtasks, then timers, then whatever* microtasks those timers queued. */@@ -161,7 +152,7 @@ void pumpJs(HostState& h);* ArrayBuffer (audio clip bytes, cache writes), a typed-array view (texture* pixels), or a plain JS number array.*/-void readByteSource(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out);+void readByteSource(esjs::Val v, std::vector<esengine::u8>& out);/** A packaged, project-relative file. Empty when missing or before boot. */std::vector<esengine::u8> readAsset(HostState& h, const char* path);diff --git a/native/host/bindings/AotBindings.cpp b/native/host/bindings/AotBindings.cppindex 3f69338ef..e646e6ed6 100644--- a/native/host/bindings/AotBindings.cpp+++ b/native/host/bindings/AotBindings.cpp@@ -5,7 +5,7 @@* @brief es_aot_* — the compiled systems a shipped desktop build loads.* @details The web road hands the module the engine's memory and lets JS pack* the rows. Here the engine IS the process: an address is a pointer- * nothing in QuickJS can hold, so the rows are packed on this side and+ * nothing in JS can hold, so the rows are packed on this side and* JS says only which system to run.** What this owns is the naming, in both directions. Where one component@@ -117,11 +117,11 @@ void* resourceAt(const char* name) {// — the calls —/** es_aot_install(path) -> system count, or -1 with the reason logged. */-JSValue installModule(JSContext* ctx, int argc, JSValueConst* argv,- std::optional<std::uint64_t> expectedContract = std::nullopt) {- if (argc < 1) return JS_NewInt32(ctx, -1);- const char* path = JS_ToCString(ctx, argv[0]);- if (path == nullptr) return JS_NewInt32(ctx, -1);+esjs::Val installModule(const esjs::Args& a,+ std::optional<std::uint64_t> expectedContract = std::nullopt) {+ if (a.size() < 1) return esjs::int32(-1);+ esjs::Utf8 pathUtf8(a[0]); const char* path = pathUtf8 ? pathUtf8.c_str() : nullptr;+ if (path == nullptr) return esjs::int32(-1);// A content-relative name, resolved the way every other packaged file is:// the OS loader searches its own path for a bare name and would find@@ -141,19 +141,18 @@ JSValue installModule(JSContext* ctx, int argc, JSValueConst* argv,s.candidates.clear();}if (!ok) ESHOST_LOGE("[aot] %s: %s", path, why.c_str());- JS_FreeCString(ctx, path);- return JS_NewInt32(ctx, ok ? static_cast<int>(s.dispatcher.count()) : -1);+ return esjs::int32(ok ? static_cast<int>(s.dispatcher.count()) : -1);}-JSValue js_install(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- return installModule(ctx, argc, argv);+esjs::Val js_install(const esjs::Args& a) {+ return installModule(a);}/** Validate the sidecar against the candidate before replacing the live module. */-JSValue js_installChecked(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2) return JS_ThrowTypeError(ctx, "es_aot_install_checked requires a module and contract");- const char* text = JS_ToCString(ctx, argv[1]);- if (!text) return JS_EXCEPTION;+esjs::Val js_installChecked(const esjs::Args& a) {+ if (a.size() < 2) return esjs::throwTypeError("es_aot_install_checked requires a module and contract");+ esjs::Utf8 textUtf8(a[1]); const char* text = textUtf8 ? textUtf8.c_str() : nullptr;+ if (!text) return esjs::undefined();std::uint64_t expected = 0;const std::size_t length = std::strlen(text);bool valid = length == 0;@@ -161,19 +160,17 @@ JSValue js_installChecked(JSContext* ctx, JSValueConst, int argc, JSValueConst*const auto parsed = std::from_chars(text, text + length, expected, 16);valid = parsed.ec == std::errc{} && parsed.ptr == text + length;}- JS_FreeCString(ctx, text);- if (!valid) return JS_ThrowTypeError(ctx, "module contract must be empty or 16 hex digits");- return installModule(ctx, argc, argv, expected);+ if (!valid) return esjs::throwTypeError("module contract must be empty or 16 hex digits");+ return installModule(a, expected);}/** es_aot_index(name) -> the index the scheduler keeps, or -1. */-JSValue js_index(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NewInt32(ctx, -1);- const char* name = JS_ToCString(ctx, argv[0]);- if (name == nullptr) return JS_NewInt32(ctx, -1);+esjs::Val js_index(const esjs::Args& a) {+ if (a.size() < 1) return esjs::int32(-1);+ esjs::Utf8 nameUtf8(a[0]); const char* name = nameUtf8 ? nameUtf8.c_str() : nullptr;+ if (name == nullptr) return esjs::int32(-1);const std::size_t at = state().dispatcher.indexOf(name);- JS_FreeCString(ctx, name);- return JS_NewInt32(ctx, at == aot::Dispatcher::npos ? -1 : static_cast<int>(at));+ return esjs::int32(at == aot::Dispatcher::npos ? -1 : static_cast<int>(at));}/**@@ -181,20 +178,20 @@ JSValue js_index(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {* where it cannot say. The SDK holds the sidecar written beside it and is the* only half that can compare the two.*/-JSValue js_contract(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_contract(const esjs::Args& a) {const std::uint64_t value = state().dispatcher.contract();- if (value == 0) return JS_NewString(ctx, "");+ if (value == 0) return esjs::string("");char hex[17];std::snprintf(hex, sizeof(hex), "%016llx", static_cast<unsigned long long>(value));- return JS_NewString(ctx, hex);+ return esjs::string(hex);}/** es_aot_bound(i) -> whether that system resolved; an unbound one interprets. */-JSValue js_bound(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_FALSE;+esjs::Val js_bound(const esjs::Args& a) {+ if (a.size() < 1) return esjs::boolean(false);std::uint32_t i = 0;- JS_ToUint32(ctx, &i, argv[0]);- return JS_NewBool(ctx, state().dispatcher.boundAt(i));+ i = esjs::toUint32(a[0]);+ return esjs::boolean(state().dispatcher.boundAt(i));}/**@@ -206,20 +203,20 @@ JSValue js_bound(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {* its layout epoch. A 0 row offset says the pool is gone, a 0 owner offset says* the column cannot be enumerated and its systems widen.*/-JSValue js_scriptRows(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 6) return JS_FALSE;- const char* name = JS_ToCString(ctx, argv[0]);- if (name == nullptr) return JS_FALSE;+esjs::Val js_scriptRows(const esjs::Args& a) {+ if (a.size() < 6) return esjs::boolean(false);+ esjs::Utf8 nameUtf8(a[0]); const char* name = nameUtf8 ? nameUtf8.c_str() : nullptr;+ if (name == nullptr) return esjs::boolean(false);std::uint32_t sparseOff = 0, sparseCount = 0, rowsOff = 0, stride = 0, mask = 0;std::uint32_t ownersOff = 0, ownerCount = 0;- JS_ToUint32(ctx, &sparseOff, argv[1]);- JS_ToUint32(ctx, &sparseCount, argv[2]);- JS_ToUint32(ctx, &rowsOff, argv[3]);- JS_ToUint32(ctx, &stride, argv[4]);- JS_ToUint32(ctx, &mask, argv[5]);- if (argc >= 8) {- JS_ToUint32(ctx, &ownersOff, argv[6]);- JS_ToUint32(ctx, &ownerCount, argv[7]);+ sparseOff = esjs::toUint32(a[1]);+ sparseCount = esjs::toUint32(a[2]);+ rowsOff = esjs::toUint32(a[3]);+ stride = esjs::toUint32(a[4]);+ mask = esjs::toUint32(a[5]);+ if (a.size() >= 8) {+ ownersOff = esjs::toUint32(a[6]);+ ownerCount = esjs::toUint32(a[7]);}// Range-checked through the heap rather than trusted: an offset is a number@@ -229,8 +226,7 @@ JSValue js_scriptRows(JSContext* ctx, JSValueConst, int argc, JSValueConst* argvvoid* owners = ownersOff == 0 ? nullptr: heapPtr(ownersOff, static_cast<std::size_t>(ownerCount) * sizeof(std::uint32_t));aot::RowSpan* slot = slotFor(name);- JS_FreeCString(ctx, name);- if (sparse == nullptr && sparseCount > 0) return JS_FALSE;+ if (sparse == nullptr && sparseCount > 0) return esjs::boolean(false);// An owner table that does not check out is DROPPED, not refused: narrowing// is an optimisation and must never be the thing that fails a frame.if (owners == nullptr) ownerCount = 0;@@ -240,21 +236,20 @@ JSValue js_scriptRows(JSContext* ctx, JSValueConst, int argc, JSValueConst* argvstatic_cast<unsigned char*>(rows), stride, mask,static_cast<const std::uint32_t*>(owners), ownerCount,};- return JS_TRUE;+ return esjs::boolean(true);}/** es_aot_resource(name, offset, bytes) -> where one call reads that resource. */-JSValue js_resource(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 3) return JS_FALSE;- const char* name = JS_ToCString(ctx, argv[0]);- if (name == nullptr) return JS_FALSE;+esjs::Val js_resource(const esjs::Args& a) {+ if (a.size() < 3) return esjs::boolean(false);+ esjs::Utf8 nameUtf8(a[0]); const char* name = nameUtf8 ? nameUtf8.c_str() : nullptr;+ if (name == nullptr) return esjs::boolean(false);std::uint32_t offset = 0, bytes = 0;- JS_ToUint32(ctx, &offset, argv[1]);- JS_ToUint32(ctx, &bytes, argv[2]);+ offset = esjs::toUint32(a[1]);+ bytes = esjs::toUint32(a[2]);void* at = heapPtr(offset, bytes);if (at != nullptr) state().resources[name] = at;- JS_FreeCString(ctx, name);- return JS_NewBool(ctx, at != nullptr);+ return esjs::boolean(at != nullptr);}/**@@ -270,18 +265,18 @@ JSValue js_resource(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv)* a despawn by the previous system moves them; the script epoch can only come* from the language that owns those pools. An absent argument reuses nothing.*/-JSValue js_run(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NewInt32(ctx, -1);+esjs::Val js_run(const esjs::Args& a) {+ if (a.size() < 1) return esjs::int32(-1);std::uint32_t i = 0;- JS_ToUint32(ctx, &i, argv[0]);+ i = esjs::toUint32(a[0]);AotState& s = state();// The dispatcher owns installed state. A failed replacement retains its// old systems; an independent flag would disable that preserved module.- if (i >= s.dispatcher.count()) return JS_NewInt32(ctx, -1);+ if (i >= s.dispatcher.count()) return esjs::int32(-1);aot::WorldStamp world;double scriptEpoch = 0.0;- if (argc >= 2 && JS_ToFloat64(ctx, &scriptEpoch, argv[1]) == 0 && host().registry != nullptr) {+ if (a.size() >= 2 && ((scriptEpoch = esjs::toNumber(a[1])), true) && host().registry != nullptr) {// Summed, not paired: both halves only ever count up, so no change in// one can be cancelled by a change in the other.world = aot::WorldStamp{host().registry->layoutEpoch() + scriptEpoch, true};@@ -293,29 +288,30 @@ JSValue js_run(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {}const auto cmds = s.dispatcher.run(i, s.candidates, resourceAt, world);// Asked AFTER the run, because that is where a late binding is settled.- if (!s.dispatcher.boundAt(i)) return JS_NewInt32(ctx, -1);+ if (!s.dispatcher.boundAt(i)) return esjs::int32(-1);// What this system covered and what it actually wrote, for the bench and the// gates that read them. A no-op unless a bench was asked for.benchNoteAotCandidates(s.dispatcher.candidatesWalked(i), s.dispatcher.rowsPacked(i));// After the call, never during it: a despawn invalidates the rows it read.- return JS_NewInt32(ctx, static_cast<int>(aot::applyCommands(*host().registry, cmds)));+ return esjs::int32(static_cast<int>(aot::applyCommands(*host().registry, cmds)));}/** es_aot_reset() — close the module and forget every name. */-JSValue js_reset(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_reset(const esjs::Args&) {AotState& s = state();s.dispatcher.reset();s.scriptByName.clear();s.scriptSpans.clear();s.resources.clear();- return JS_UNDEFINED;+ return esjs::undefined();}} // namespace-void registerAotBindings(HostState& h, JSValue global) {- const auto fn = [&](const char* name, JSCFunction* impl, int arity) {- JS_SetPropertyStr(h.js, global, name, JS_NewCFunction(h.js, impl, name, arity));+void registerAotBindings(HostState& h, esjs::Val global) {+ (void)h;+ const auto fn = [&](const char* name, esjs::NativeFn impl, int arity) {+ esjs::setFunction(global, name, impl, arity);};fn("es_aot_install", js_install, 1);fn("es_aot_install_checked", js_installChecked, 2);diff --git a/native/host/bindings/AssetBindings.cpp b/native/host/bindings/AssetBindings.cppindex 1a909d863..632ae153c 100644--- a/native/host/bindings/AssetBindings.cpp+++ b/native/host/bindings/AssetBindings.cpp@@ -32,40 +32,38 @@ namespace eshost {namespace {// es_readAsset(path) -> ArrayBuffer | null. Backs the bridge's readFile.-JSValue js_readAsset(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* path = JS_ToCString(ctx, argv[0]);- if (!path) return JS_NULL;+esjs::Val js_readAsset(const esjs::Args& a) {+ esjs::Utf8 pathUtf8(a[0]); const char* path = pathUtf8 ? pathUtf8.c_str() : nullptr;+ if (!path) return esjs::null();std::vector<u8> bytes = readAsset(host(), path);- JS_FreeCString(ctx, path);- if (bytes.empty()) return JS_NULL;- return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());+ if (bytes.empty()) return esjs::null();+ return esjs::arrayBufferCopy(bytes.data(), bytes.size());}// es_loadImagePixels(path | ArrayBuffer) -> { width, height, pixels: ArrayBuffer(RGBA) } | null.// Decodes a packaged image asset — or bytes the script fetched or read from the// cache, which is how a CDN image arrives — to top-first RGBA via stb_image.-JSValue js_loadImagePixels(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+esjs::Val js_loadImagePixels(const esjs::Args& a) {std::vector<u8> file;- size_t size = 0;- if (uint8_t* raw = JS_GetArrayBuffer(ctx, &size, argv[0])) {- file.assign(raw, raw + size);+ esjs::Bytes raw;+ if (esjs::bytesOf(a[0], &raw)) {+ file.assign(raw.data, raw.data + raw.size);} else {- JS_FreeValue(ctx, JS_GetException(ctx)); // not an ArrayBuffer: a path- const char* path = JS_ToCString(ctx, argv[0]);- if (!path) return JS_NULL;+ // not a byte buffer: a path+ esjs::Utf8 pathUtf8(a[0]); const char* path = pathUtf8 ? pathUtf8.c_str() : nullptr;+ if (!path) return esjs::null();file = readAsset(host(), path);- JS_FreeCString(ctx, path);}- if (file.empty()) return JS_NULL;+ if (file.empty()) return esjs::null();int w = 0, h = 0, ch = 0;stbi_uc* px = stbi_load_from_memory(file.data(), (int)file.size(), &w, &h, &ch, 4);- if (!px) { ESHOST_LOGE("stb_image decode failed"); return JS_NULL; }- JSValue buf = JS_NewArrayBufferCopy(ctx, px, (size_t)w * (size_t)h * 4);+ if (!px) { ESHOST_LOGE("stb_image decode failed"); return esjs::null(); }+ esjs::Val buf = esjs::arrayBufferCopy(px, (size_t)w * (size_t)h * 4);stbi_image_free(px);- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, w));- JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, h));- JS_SetPropertyStr(ctx, obj, "pixels", buf); // ArrayBuffer; the bootstrap wraps it Uint8Array+ esjs::Val obj = esjs::object();+ esjs::set(obj, "width", esjs::int32(w));+ esjs::set(obj, "height", esjs::int32(h));+ esjs::set(obj, "pixels", buf); // ArrayBuffer; the bootstrap wraps it Uint8Arrayreturn obj;}@@ -81,102 +79,83 @@ std::string pathIn(const std::string& dir, const char* key) {return dir + "/" + key;}-JSValue readFileAt(JSContext* ctx, const std::string& path) {- if (path.empty()) return JS_NULL;+esjs::Val readFileAt(const std::string& path) {+ if (path.empty()) return esjs::null();FILE* f = fopen(path.c_str(), "rb");- if (!f) return JS_NULL;+ if (!f) return esjs::null();fseek(f, 0, SEEK_END);const long size = ftell(f);fseek(f, 0, SEEK_SET);std::vector<u8> bytes(size > 0 ? (size_t)size : 0);if (!bytes.empty() && fread(bytes.data(), 1, bytes.size(), f) != bytes.size()) bytes.clear();fclose(f);- if (bytes.empty()) return JS_NULL;- return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());+ if (bytes.empty()) return esjs::null();+ return esjs::arrayBufferCopy(bytes.data(), bytes.size());}// A string source is written as UTF-8, so script-side JSON needs no TextEncoder.-JSValue writeFileAt(JSContext* ctx, const std::string& path, JSValueConst source) {- if (path.empty()) return JS_FALSE;+esjs::Val writeFileAt(const std::string& path, esjs::Val source) {+ if (path.empty()) return esjs::boolean(false);std::vector<u8> bytes;- if (JS_IsString(source)) {- size_t len = 0;- if (const char* text = JS_ToCStringLen(ctx, &len, source)) {- bytes.assign(text, text + len);- JS_FreeCString(ctx, text);- }+ if (esjs::isString(source)) {+ const esjs::Utf8 text(source);+ bytes.assign(text.c_str(), text.c_str() + text.size());} else {- readByteSource(ctx, source, bytes);+ readByteSource(source, bytes);}// Write a temp file and rename over the target: a crash or a kill mid-write// must not leave a truncated file where a save used to be. rename(2) within// one directory is atomic, so a reader sees the old file or the new one.const std::string tmp = path + ".tmp";FILE* f = fopen(tmp.c_str(), "wb");- if (!f) return JS_FALSE;+ if (!f) return esjs::boolean(false);const bool wrote = bytes.empty() || fwrite(bytes.data(), 1, bytes.size(), f) == bytes.size();const bool flushed = wrote && fflush(f) == 0;fclose(f);if (!flushed || rename(tmp.c_str(), path.c_str()) != 0) {remove(tmp.c_str());- return JS_FALSE;+ return esjs::boolean(false);}- return JS_TRUE;+ return esjs::boolean(true);}// es_readCacheFile(key) -> ArrayBuffer | null. Reclaimable half: hot-update content.-JSValue js_readCacheFile(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* key = JS_ToCString(ctx, argv[0]);+esjs::Val js_readCacheFile(const esjs::Args& a) {+ esjs::Utf8 keyUtf8(a[0]); const char* key = keyUtf8 ? keyUtf8.c_str() : nullptr;const std::string path = pathIn(host().cacheDir, key);- if (key) JS_FreeCString(ctx, key);- return readFileAt(ctx, path);+ return readFileAt(path);}// es_writeCacheFile(key, ArrayBuffer | TypedArray | string) -> bool.-JSValue js_writeCacheFile(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2) return JS_FALSE;- const char* key = JS_ToCString(ctx, argv[0]);+esjs::Val js_writeCacheFile(const esjs::Args& a) {+ if (a.size() < 2) return esjs::boolean(false);+ esjs::Utf8 keyUtf8(a[0]); const char* key = keyUtf8 ? keyUtf8.c_str() : nullptr;const std::string path = pathIn(host().cacheDir, key);- if (key) JS_FreeCString(ctx, key);- return writeFileAt(ctx, path, argv[1]);+ return writeFileAt(path, a[1]);}// es_readDataFile(key) -> ArrayBuffer | null. Durable half: what a player keeps.-JSValue js_readDataFile(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* key = JS_ToCString(ctx, argv[0]);+esjs::Val js_readDataFile(const esjs::Args& a) {+ esjs::Utf8 keyUtf8(a[0]); const char* key = keyUtf8 ? keyUtf8.c_str() : nullptr;const std::string path = pathIn(host().dataDir, key);- if (key) JS_FreeCString(ctx, key);- return readFileAt(ctx, path);+ return readFileAt(path);}// es_writeDataFile(key, ArrayBuffer | TypedArray | string) -> bool.-JSValue js_writeDataFile(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2) return JS_FALSE;- const char* key = JS_ToCString(ctx, argv[0]);+esjs::Val js_writeDataFile(const esjs::Args& a) {+ if (a.size() < 2) return esjs::boolean(false);+ esjs::Utf8 keyUtf8(a[0]); const char* key = keyUtf8 ? keyUtf8.c_str() : nullptr;const std::string path = pathIn(host().dataDir, key);- if (key) JS_FreeCString(ctx, key);- return writeFileAt(ctx, path, argv[1]);+ return writeFileAt(path, a[1]);}// es_utf8Decode(ArrayBuffer | TypedArray) -> string. Backs the TextDecoder the-// platform layer uses to read packaged JSON (manifests, scenes); QuickJS parses+// platform layer uses to read packaged JSON (manifests, scenes); the engine reads// UTF-8 natively, so this beats decoding byte-by-byte in script.-JSValue js_utf8Decode(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NewString(ctx, "");- size_t size = 0;- if (uint8_t* raw = JS_GetArrayBuffer(ctx, &size, argv[0])) {- return JS_NewStringLen(ctx, reinterpret_cast<const char*>(raw), size);- }- JS_FreeValue(ctx, JS_GetException(ctx)); // not an ArrayBuffer — try a view- size_t offset = 0, length = 0, bytesPerEl = 0;- JSValue ab = JS_GetTypedArrayBuffer(ctx, argv[0], &offset, &length, &bytesPerEl);- if (JS_IsException(ab)) { JS_FreeValue(ctx, JS_GetException(ctx)); return JS_NewString(ctx, ""); }- uint8_t* base = JS_GetArrayBuffer(ctx, &size, ab);- JSValue out = (base && offset + length <= size)- ? JS_NewStringLen(ctx, reinterpret_cast<const char*>(base + offset), length)- : JS_NewString(ctx, "");- JS_FreeValue(ctx, ab);- return out;+esjs::Val js_utf8Decode(const esjs::Args& a) {+ esjs::Bytes bytes;+ if (!esjs::bytesOf(a[0], &bytes)) return esjs::string("");+ return esjs::string(std::string_view(reinterpret_cast<const char*>(bytes.data), bytes.size));}} // namespace@@ -185,14 +164,14 @@ std::vector<u8> readAsset(HostState& h, const char* path) {return h.platform ? h.platform->readAsset(path) : std::vector<u8>{};}-void registerAssetBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_readAsset", js_readAsset, 1);- bindGlobal(h, global, "es_loadImagePixels", js_loadImagePixels, 1);- bindGlobal(h, global, "es_readCacheFile", js_readCacheFile, 1);- bindGlobal(h, global, "es_writeCacheFile", js_writeCacheFile, 2);- bindGlobal(h, global, "es_readDataFile", js_readDataFile, 1);- bindGlobal(h, global, "es_writeDataFile", js_writeDataFile, 2);- bindGlobal(h, global, "es_utf8Decode", js_utf8Decode, 1);+void registerAssetBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_readAsset", js_readAsset, 1);+ bindGlobal(global, "es_loadImagePixels", js_loadImagePixels, 1);+ bindGlobal(global, "es_readCacheFile", js_readCacheFile, 1);+ bindGlobal(global, "es_writeCacheFile", js_writeCacheFile, 2);+ bindGlobal(global, "es_readDataFile", js_readDataFile, 1);+ bindGlobal(global, "es_writeDataFile", js_writeDataFile, 2);+ bindGlobal(global, "es_utf8Decode", js_utf8Decode, 1);}} // namespace eshostdiff --git a/native/host/bindings/AudioBindings.cpp b/native/host/bindings/AudioBindings.cppindex a14925c5c..aa12d4e91 100644--- a/native/host/bindings/AudioBindings.cpp+++ b/native/host/bindings/AudioBindings.cpp@@ -30,112 +30,112 @@ namespace {// es_audioLoad(ArrayBuffer | TypedArray) -> { id, duration, bytes } | null. The// SDK hands the compressed clip bytes; the engine decodes + registers them.-JSValue js_audioLoad(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NULL;+esjs::Val js_audioLoad(const esjs::Args& a) {+ if (a.size() < 1) return esjs::null();std::vector<u8> bytes;- readByteSource(ctx, argv[0], bytes);- if (bytes.empty()) return JS_NULL;+ readByteSource(a[0], bytes);+ if (bytes.empty()) return esjs::null();auto r = host().audio.load(bytes.data(), bytes.size());- if (r.id < 0) return JS_NULL;- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.id));- JS_SetPropertyStr(ctx, o, "duration", JS_NewFloat64(ctx, r.duration));- JS_SetPropertyStr(ctx, o, "bytes", JS_NewInt64(ctx, r.bytes));+ if (r.id < 0) return esjs::null();+ esjs::Val o = esjs::object();+ esjs::set(o, "id", esjs::int32(r.id));+ esjs::set(o, "duration", esjs::number(r.duration));+ esjs::set(o, "bytes", esjs::int64(r.bytes));return o;}-JSValue js_audioUnload(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- int32_t id = 0; JS_ToInt32(ctx, &id, argv[0]);+esjs::Val js_audioUnload(const esjs::Args& a) {+ int32_t id = esjs::toInt32(a[0]);host().audio.unload(id);- return JS_UNDEFINED;+ return esjs::undefined();}// es_audioPlay(bufferId, volume, pan, loop, rate) -> voiceId (-1 if unknown).-JSValue js_audioPlay(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t buf = 0; JS_ToInt32(ctx, &buf, argv[0]);+esjs::Val js_audioPlay(const esjs::Args& a) {+ int32_t buf = esjs::toInt32(a[0]);double vol = 1, pan = 0, rate = 1;- if (argc > 1) JS_ToFloat64(ctx, &vol, argv[1]);- if (argc > 2) JS_ToFloat64(ctx, &pan, argv[2]);- const bool loop = argc > 3 && JS_ToBool(ctx, argv[3]);- if (argc > 4) JS_ToFloat64(ctx, &rate, argv[4]);- return JS_NewInt32(ctx, host().audio.play(buf, (f32)vol, (f32)pan, loop, (f32)rate));+ if (a.size() > 1) vol = esjs::toNumber(a[1]);+ if (a.size() > 2) pan = esjs::toNumber(a[2]);+ const bool loop = a.size() > 3 && esjs::toBool(a[3]);+ if (a.size() > 4) rate = esjs::toNumber(a[4]);+ return esjs::int32(host().audio.play(buf, (f32)vol, (f32)pan, loop, (f32)rate));}-// The voice-scoped commands all take the voice id as argv[0].-int32_t voiceArg(JSContext* ctx, JSValueConst* argv) {- int32_t v = 0; JS_ToInt32(ctx, &v, argv[0]); return v;+// The voice-scoped commands all take the voice id as a[0].+int32_t voiceArg(const esjs::Args& a) {+ int32_t v = esjs::toInt32(a[0]); return v;}-JSValue js_audioStop(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- host().audio.stop(voiceArg(ctx, argv)); return JS_UNDEFINED;+esjs::Val js_audioStop(const esjs::Args& a) {+ host().audio.stop(voiceArg(a)); return esjs::undefined();}-JSValue js_audioPause(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- host().audio.pause(voiceArg(ctx, argv)); return JS_UNDEFINED;+esjs::Val js_audioPause(const esjs::Args& a) {+ host().audio.pause(voiceArg(a)); return esjs::undefined();}-JSValue js_audioResume(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- host().audio.resume(voiceArg(ctx, argv)); return JS_UNDEFINED;+esjs::Val js_audioResume(const esjs::Args& a) {+ host().audio.resume(voiceArg(a)); return esjs::undefined();}-JSValue js_audioSetVolume(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double v = 1; JS_ToFloat64(ctx, &v, argv[1]);- host().audio.setVolume(voiceArg(ctx, argv), (f32)v); return JS_UNDEFINED;+esjs::Val js_audioSetVolume(const esjs::Args& a) {+ double v = esjs::toNumber(a[1]);+ host().audio.setVolume(voiceArg(a), (f32)v); return esjs::undefined();}-JSValue js_audioSetPan(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double p = 0; JS_ToFloat64(ctx, &p, argv[1]);- host().audio.setPan(voiceArg(ctx, argv), (f32)p); return JS_UNDEFINED;+esjs::Val js_audioSetPan(const esjs::Args& a) {+ double p = esjs::toNumber(a[1]);+ host().audio.setPan(voiceArg(a), (f32)p); return esjs::undefined();}-JSValue js_audioSetLoop(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- host().audio.setLoop(voiceArg(ctx, argv), JS_ToBool(ctx, argv[1]) != 0); return JS_UNDEFINED;+esjs::Val js_audioSetLoop(const esjs::Args& a) {+ host().audio.setLoop(voiceArg(a), esjs::toBool(a[1])); return esjs::undefined();}-JSValue js_audioSetRate(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- double r = 1; JS_ToFloat64(ctx, &r, argv[1]);- host().audio.setRate(voiceArg(ctx, argv), (f32)r); return JS_UNDEFINED;+esjs::Val js_audioSetRate(const esjs::Args& a) {+ double r = esjs::toNumber(a[1]);+ host().audio.setRate(voiceArg(a), (f32)r); return esjs::undefined();}// es_audioVoiceState(voiceId) -> { playing, currentTime } | null (null once ended).-JSValue js_audioVoiceState(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- auto st = host().audio.voiceState(voiceArg(ctx, argv));- if (!st.valid) return JS_NULL;- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "playing", JS_NewBool(ctx, st.playing));- JS_SetPropertyStr(ctx, o, "currentTime", JS_NewFloat64(ctx, st.currentTime));+esjs::Val js_audioVoiceState(const esjs::Args& a) {+ auto st = host().audio.voiceState(voiceArg(a));+ if (!st.valid) return esjs::null();+ esjs::Val o = esjs::object();+ esjs::set(o, "playing", esjs::boolean(st.playing));+ esjs::set(o, "currentTime", esjs::number(st.currentTime));return o;}-JSValue js_audioSuspendAll(JSContext* ctx, JSValueConst, int, JSValueConst*) {- host().audio.suspendAll(); return JS_UNDEFINED;+esjs::Val js_audioSuspendAll(const esjs::Args& a) {+ host().audio.suspendAll(); return esjs::undefined();}-JSValue js_audioResumeAll(JSContext* ctx, JSValueConst, int, JSValueConst*) {- host().audio.resumeAll(); return JS_UNDEFINED;+esjs::Val js_audioResumeAll(const esjs::Args& a) {+ host().audio.resumeAll(); return esjs::undefined();}} // namespace// es_audioSpectrum(bins) -> ArrayBuffer of `bins` magnitude bytes, or null when// nothing has played yet. The device's answer to a WebAudio AnalyserNode.-JSValue js_audioSpectrum(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1 || !hostAlive()) return JS_NULL;+esjs::Val js_audioSpectrum(const esjs::Args& a) {+ if (a.size() < 1 || !hostAlive()) return esjs::null();int32_t bins = 0;- JS_ToInt32(ctx, &bins, argv[0]);- if (bins <= 0 || bins > 4096) return JS_NULL;+ bins = esjs::toInt32(a[0]);+ if (bins <= 0 || bins > 4096) return esjs::null();std::vector<uint8_t> out((size_t)bins, 0);- if (!host().audio.spectrum(out.data(), out.size())) return JS_NULL;- return JS_NewArrayBufferCopy(ctx, out.data(), out.size());+ if (!host().audio.spectrum(out.data(), out.size())) return esjs::null();+ return esjs::arrayBufferCopy(out.data(), out.size());}-void registerAudioBindings(HostState& h, JSValue global) {+void registerAudioBindings(HostState& h, esjs::Val global) {if (!h.audio.ready()) return;- bindGlobal(h, global, "es_audioLoad", js_audioLoad, 1);- bindGlobal(h, global, "es_audioUnload", js_audioUnload, 1);- bindGlobal(h, global, "es_audioPlay", js_audioPlay, 5);- bindGlobal(h, global, "es_audioStop", js_audioStop, 1);- bindGlobal(h, global, "es_audioPause", js_audioPause, 1);- bindGlobal(h, global, "es_audioResume", js_audioResume, 1);- bindGlobal(h, global, "es_audioSetVolume", js_audioSetVolume, 2);- bindGlobal(h, global, "es_audioSetPan", js_audioSetPan, 2);- bindGlobal(h, global, "es_audioSetLoop", js_audioSetLoop, 2);- bindGlobal(h, global, "es_audioSpectrum", js_audioSpectrum, 1);- bindGlobal(h, global, "es_audioSetRate", js_audioSetRate, 2);- bindGlobal(h, global, "es_audioVoiceState", js_audioVoiceState, 1);- bindGlobal(h, global, "es_audioSuspendAll", js_audioSuspendAll, 0);- bindGlobal(h, global, "es_audioResumeAll", js_audioResumeAll, 0);+ bindGlobal(global, "es_audioLoad", js_audioLoad, 1);+ bindGlobal(global, "es_audioUnload", js_audioUnload, 1);+ bindGlobal(global, "es_audioPlay", js_audioPlay, 5);+ bindGlobal(global, "es_audioStop", js_audioStop, 1);+ bindGlobal(global, "es_audioPause", js_audioPause, 1);+ bindGlobal(global, "es_audioResume", js_audioResume, 1);+ bindGlobal(global, "es_audioSetVolume", js_audioSetVolume, 2);+ bindGlobal(global, "es_audioSetPan", js_audioSetPan, 2);+ bindGlobal(global, "es_audioSetLoop", js_audioSetLoop, 2);+ bindGlobal(global, "es_audioSpectrum", js_audioSpectrum, 1);+ bindGlobal(global, "es_audioSetRate", js_audioSetRate, 2);+ bindGlobal(global, "es_audioVoiceState", js_audioVoiceState, 1);+ bindGlobal(global, "es_audioSuspendAll", js_audioSuspendAll, 0);+ bindGlobal(global, "es_audioResumeAll", js_audioResumeAll, 0);}} // namespace eshostdiff --git a/native/host/bindings/DeviceBindings.cpp b/native/host/bindings/DeviceBindings.cppindex 4dea35342..c8bb4eb68 100644--- a/native/host/bindings/DeviceBindings.cpp+++ b/native/host/bindings/DeviceBindings.cpp@@ -53,69 +53,65 @@ std::string deviceName() {#endif}-JSValue js_deviceName(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewString(ctx, deviceName().c_str());+esjs::Val js_deviceName(const esjs::Args& a) {+ return esjs::string(deviceName().c_str());}-JSValue js_deviceCapabilities(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewInt32(ctx, hostAlive() && host().platform ? host().platform->deviceCapabilities() : 0);+esjs::Val js_deviceCapabilities(const esjs::Args& a) {+ return esjs::int32(hostAlive() && host().platform ? host().platform->deviceCapabilities() : 0);}-JSValue js_startMotion(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (!hostAlive() || !host().platform || argc < 3) return JS_FALSE;- int32_t interval = 16;- if (JS_ToInt32(ctx, &interval, argv[2]) < 0) return JS_EXCEPTION;- return JS_NewBool(ctx, host().platform->startMotion(JS_ToBool(ctx, argv[0]) > 0,- JS_ToBool(ctx, argv[1]) > 0, interval));+esjs::Val js_startMotion(const esjs::Args& a) {+ if (!hostAlive() || !host().platform || a.size() < 3) return esjs::boolean(false);+ const int32_t interval = esjs::toInt32(a[2]);+ return esjs::boolean(host().platform->startMotion(esjs::toBool(a[0]), esjs::toBool(a[1]), interval));}-JSValue js_stopMotion(JSContext*, JSValueConst, int, JSValueConst*) {+esjs::Val js_stopMotion(const esjs::Args&) {if (hostAlive() && host().platform) host().platform->stopMotion();- return JS_UNDEFINED;+ return esjs::undefined();}-JSValue motionVector(JSContext* ctx, const float* value) {- JSValue object = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, object, "x", JS_NewFloat64(ctx, value[0]));- JS_SetPropertyStr(ctx, object, "y", JS_NewFloat64(ctx, value[1]));- JS_SetPropertyStr(ctx, object, "z", JS_NewFloat64(ctx, value[2]));+esjs::Val motionVector(const float* value) {+ esjs::Val object = esjs::object();+ esjs::set(object, "x", esjs::number(value[0]));+ esjs::set(object, "y", esjs::number(value[1]));+ esjs::set(object, "z", esjs::number(value[2]));return object;}-JSValue js_pollMotion(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_pollMotion(const esjs::Args& a) {MotionState motion;- if (!hostAlive() || !host().platform || !host().platform->pollMotion(motion)) return JS_NULL;- JSValue result = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, result, "timestamp", JS_NewFloat64(ctx, motion.timestamp));- JS_SetPropertyStr(ctx, result, "accelerationIncludingGravity", motion.hasAcceleration- ? motionVector(ctx, motion.acceleration) : JS_NULL);- JS_SetPropertyStr(ctx, result, "gyroscope", motion.hasGyroscope ? motionVector(ctx, motion.gyroscope) : JS_NULL);+ if (!hostAlive() || !host().platform || !host().platform->pollMotion(motion)) return esjs::null();+ esjs::Val result = esjs::object();+ esjs::set(result, "timestamp", esjs::number(motion.timestamp));+ esjs::set(result, "accelerationIncludingGravity", motion.hasAcceleration+ ? motionVector(motion.acceleration) : esjs::null());+ esjs::set(result, "gyroscope", motion.hasGyroscope ? motionVector(motion.gyroscope) : esjs::null());return result;}-JSValue js_vibrate(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (!hostAlive() || !host().platform || argc < 2) return JS_FALSE;- int32_t duration = 15, intensity = 2;- if (JS_ToInt32(ctx, &duration, argv[0]) < 0 || JS_ToInt32(ctx, &intensity, argv[1]) < 0) return JS_EXCEPTION;- return JS_NewBool(ctx, host().platform->vibrate(duration, intensity));+esjs::Val js_vibrate(const esjs::Args& a) {+ if (!hostAlive() || !host().platform || a.size() < 2) return esjs::boolean(false);+ const int32_t duration = esjs::toInt32(a[0]), intensity = esjs::toInt32(a[1]);+ return esjs::boolean(host().platform->vibrate(duration, intensity));}-JSValue js_keepScreenOn(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- return JS_NewBool(ctx, hostAlive() && host().platform && argc > 0- && host().platform->keepScreenOn(JS_ToBool(ctx, argv[0]) > 0));+esjs::Val js_keepScreenOn(const esjs::Args& a) {+ return esjs::boolean(hostAlive() && host().platform && a.size() > 0+ && host().platform->keepScreenOn(esjs::toBool(a[0])));}-JSValue js_setTargetFrameRate(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- double fps = 0;- if (argc > 0 && JS_ToFloat64(ctx, &fps, argv[0]) < 0) return JS_EXCEPTION;+esjs::Val js_setTargetFrameRate(const esjs::Args& a) {+ const double fps = a.size() > 0 ? esjs::toNumber(a[0]) : 0;if (hostAlive() && host().platform) host().platform->setTargetFrameRate(fps > 0 ? (float)fps : 0.0f);- return JS_UNDEFINED;+ return esjs::undefined();}} // namespace-void registerDeviceBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_deviceName", js_deviceName, 0);- bindGlobal(h, global, "es_deviceCapabilities", js_deviceCapabilities, 0);- bindGlobal(h, global, "es_startMotion", js_startMotion, 3);- bindGlobal(h, global, "es_stopMotion", js_stopMotion, 0);- bindGlobal(h, global, "es_pollMotion", js_pollMotion, 0);- bindGlobal(h, global, "es_vibrate", js_vibrate, 2);- bindGlobal(h, global, "es_keepScreenOn", js_keepScreenOn, 1);- bindGlobal(h, global, "es_setTargetFrameRate", js_setTargetFrameRate, 1);+void registerDeviceBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_deviceName", js_deviceName, 0);+ bindGlobal(global, "es_deviceCapabilities", js_deviceCapabilities, 0);+ bindGlobal(global, "es_startMotion", js_startMotion, 3);+ bindGlobal(global, "es_stopMotion", js_stopMotion, 0);+ bindGlobal(global, "es_pollMotion", js_pollMotion, 0);+ bindGlobal(global, "es_vibrate", js_vibrate, 2);+ bindGlobal(global, "es_keepScreenOn", js_keepScreenOn, 1);+ bindGlobal(global, "es_setTargetFrameRate", js_setTargetFrameRate, 1);}} // namespace eshostdiff --git a/native/host/bindings/EcsBindings.cpp b/native/host/bindings/EcsBindings.cppindex 03009479e..53979a417 100644--- a/native/host/bindings/EcsBindings.cpp+++ b/native/host/bindings/EcsBindings.cpp@@ -31,8 +31,8 @@ using namespace esengine;namespace eshost {namespace {-JSValue js_createEntity(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewUint32(ctx, host().registry->create().id());+esjs::Val js_createEntity(const esjs::Args& a) {+ return esjs::uint32(host().registry->create().id());}/*** Every pool's version in one number — `Registry::layoutEpoch`, which the web@@ -40,62 +40,62 @@ JSValue js_createEntity(JSContext* ctx, JSValueConst, int, JSValueConst*) {* before trusting them for another frame, and a host that cannot answer makes* that holder re-resolve everything every frame.*/-JSValue js_layoutEpoch(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewFloat64(ctx, host().registry->layoutEpoch());+esjs::Val js_layoutEpoch(const esjs::Args& a) {+ return esjs::number(host().registry->layoutEpoch());}-JSValue js_destroyEntity(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- host().registry->destroy(esn_entity(ctx, argv[0]));- return JS_UNDEFINED;+esjs::Val js_destroyEntity(const esjs::Args& a) {+ host().registry->destroy(esn_entity(a[0]));+ return esjs::undefined();}-JSValue js_setParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), esn_entity(ctx, argv[1])));+esjs::Val js_setParent(const esjs::Args& a) {+ return esjs::boolean(ecs::setParent(*host().registry, esn_entity(a[0]), esn_entity(a[1])));}-JSValue js_reserveDestruction(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, host().registry->reserveDestruction(esn_entity(ctx, argv[0])));+esjs::Val js_reserveDestruction(const esjs::Args& a) {+ return esjs::boolean(host().registry->reserveDestruction(esn_entity(a[0])));}-JSValue js_releaseDestruction(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- host().registry->releaseDestruction(esn_entity(ctx, argv[0]));- return JS_UNDEFINED;+esjs::Val js_releaseDestruction(const esjs::Args& a) {+ host().registry->releaseDestruction(esn_entity(a[0]));+ return esjs::undefined();}-JSValue js_destructionPending(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, host().registry->destructionPending(esn_entity(ctx, argv[0])));+esjs::Val js_destructionPending(const esjs::Args& a) {+ return esjs::boolean(host().registry->destructionPending(esn_entity(a[0])));}-JSValue js_setEntityEnabled(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, host().registry->setEntityEnabled(esn_entity(ctx, argv[0]), JS_ToBool(ctx, argv[1]) != 0));+esjs::Val js_setEntityEnabled(const esjs::Args& a) {+ return esjs::boolean(host().registry->setEntityEnabled(esn_entity(a[0]), esjs::toBool(a[1])));}-JSValue js_isEntityActive(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, host().registry->isEntityActive(esn_entity(ctx, argv[0])));+esjs::Val js_isEntityActive(const esjs::Args& a) {+ return esjs::boolean(host().registry->isEntityActive(esn_entity(a[0])));}-JSValue js_isEntityEnabled(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, host().registry->isEntityEnabled(esn_entity(ctx, argv[0])));+esjs::Val js_isEntityEnabled(const esjs::Args& a) {+ return esjs::boolean(host().registry->isEntityEnabled(esn_entity(a[0])));}-JSValue js_hasInactiveEntities(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewBool(ctx, host().registry->hasInactiveEntities());+esjs::Val js_hasInactiveEntities(const esjs::Args& a) {+ return esjs::boolean(host().registry->hasInactiveEntities());}-JSValue js_activityEpoch(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewUint32(ctx, host().registry->activityEpoch());+esjs::Val js_activityEpoch(const esjs::Args& a) {+ return esjs::uint32(host().registry->activityEpoch());}-JSValue js_hasParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- return JS_NewBool(ctx, host().registry->has<ecs::Parent>(esn_entity(ctx, argv[0])));+esjs::Val js_hasParent(const esjs::Args& a) {+ return esjs::boolean(host().registry->has<ecs::Parent>(esn_entity(a[0])));}-JSValue js_getParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- auto* p = host().registry->tryGet<ecs::Parent>(esn_entity(ctx, argv[0]));- return JS_NewUint32(ctx, (p ? p->entity : INVALID_ENTITY).id());+esjs::Val js_getParent(const esjs::Args& a) {+ auto* p = host().registry->tryGet<ecs::Parent>(esn_entity(a[0]));+ return esjs::uint32((p ? p->entity : INVALID_ENTITY).id());}-JSValue js_removeParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), INVALID_ENTITY);- return JS_UNDEFINED;+esjs::Val js_removeParent(const esjs::Args& a) {+ ecs::setParent(*host().registry, esn_entity(a[0]), INVALID_ENTITY);+ return esjs::undefined();}-JSValue js_hasChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- auto* c = host().registry->tryGet<ecs::Children>(esn_entity(ctx, argv[0]));- return JS_NewBool(ctx, c && !c->entities.empty());+esjs::Val js_hasChildren(const esjs::Args& a) {+ auto* c = host().registry->tryGet<ecs::Children>(esn_entity(a[0]));+ return esjs::boolean(c && !c->entities.empty());}-JSValue js_getChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- JSValue arr = JS_NewArray(ctx);- if (auto* c = host().registry->tryGet<ecs::Children>(esn_entity(ctx, argv[0]))) {+esjs::Val js_getChildren(const esjs::Args& a) {+ esjs::Val arr = esjs::array();+ if (auto* c = host().registry->tryGet<ecs::Children>(esn_entity(a[0]))) {uint32_t i = 0;for (Entity child : c->entities) {- JS_SetPropertyUint32(ctx, arr, i++, JS_NewUint32(ctx, child.id()));+ esjs::setAt(arr, i++, esjs::uint32(child.id()));}}return arr;@@ -104,31 +104,29 @@ JSValue js_getChildren(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {// MeshSkin's joints are a variable-length entity list, so the component has no POD// layout and nothing generated can carry it — the same reason Children is here. A// glTF with a rig inserts one, and without these the insert fails on a device.-JSValue js_getMeshSkinJoints(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- JSValue arr = JS_NewArray(ctx);- if (auto* s = host().registry->tryGet<ecs::MeshSkin>(esn_entity(ctx, argv[0]))) {+esjs::Val js_getMeshSkinJoints(const esjs::Args& a) {+ esjs::Val arr = esjs::array();+ if (auto* s = host().registry->tryGet<ecs::MeshSkin>(esn_entity(a[0]))) {uint32_t i = 0;for (Entity joint : s->joints) {- JS_SetPropertyUint32(ctx, arr, i++, JS_NewUint32(ctx, joint.id()));+ esjs::setAt(arr, i++, esjs::uint32(joint.id()));}}return arr;}-JSValue js_setMeshSkinJoints(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2) return JS_UNDEFINED;- auto& skin = host().registry->getOrEmplace<ecs::MeshSkin>(esn_entity(ctx, argv[0]));+esjs::Val js_setMeshSkinJoints(const esjs::Args& a) {+ if (a.size() < 2) return esjs::undefined();+ auto& skin = host().registry->getOrEmplace<ecs::MeshSkin>(esn_entity(a[0]));skin.joints.clear();uint32_t len = 0;- JSValue lenv = JS_GetPropertyStr(ctx, argv[1], "length");- JS_ToUint32(ctx, &len, lenv);- JS_FreeValue(ctx, lenv);+ esjs::Val lenv = esjs::get(a[1], "length");+ len = esjs::toUint32(lenv);skin.joints.reserve(len);for (uint32_t i = 0; i < len; ++i) {- JSValue v = JS_GetPropertyUint32(ctx, argv[1], i);- skin.joints.push_back(esn_entity(ctx, v));- JS_FreeValue(ctx, v);+ esjs::Val v = esjs::getAt(a[1], i);+ skin.joints.push_back(esn_entity(v));}- return JS_UNDEFINED;+ return esjs::undefined();}/**@@ -136,83 +134,82 @@ JSValue js_setMeshSkinJoints(JSContext* ctx, JSValueConst, int argc, JSValueCons* Transform write announces through it, and an ABI call for one integer nearly* doubles the write it follows (bench/transform-invalidation).*/-JSValue js_transformEpochBuffer(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return esn_arraybuffer(ctx, &ecs::transformMutationEpoch(), sizeof(u32));+esjs::Val js_transformEpochBuffer(const esjs::Args& a) {+ return esn_arraybuffer(&ecs::transformMutationEpoch(), sizeof(u32));}/** Whether composition also records which entities' output moved. Off by default;* only a consumer maintaining an incremental structure pays for it. */-JSValue js_transformSetChangeTracking(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc >= 1 && host().ctx) {+esjs::Val js_transformSetChangeTracking(const esjs::Args& a) {+ if (a.size() >= 1 && host().ctx) {if (auto* ts = host().ctx->tryGet<ecs::TransformSystem>()) {- ts->setChangeTracking(JS_ToBool(ctx, argv[0]) != 0);+ ts->setChangeTracking(esjs::toBool(a[0]));}}- return JS_UNDEFINED;+ return esjs::undefined();}/*** What every composition since the last acknowledgement changed. The buffer views* the system's own vector and the next composition may move it, so a consumer* reads, applies, and acknowledges within one turn.*/-JSValue js_transformCompositionChanges(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_transformCompositionChanges(const esjs::Args& a) {static_assert(sizeof(Entity) == sizeof(u32), "the changed set is read as raw ids");auto* ts = host().ctx ? host().ctx->tryGet<ecs::TransformSystem>() : nullptr;- JSValue out = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, out, "serial", JS_NewUint32(ctx, ts ? ts->compositionSerial() : 0));- JS_SetPropertyStr(ctx, out, "tracking", JS_NewBool(ctx, ts && ts->changeTracking()));- JS_SetPropertyStr(ctx, out, "overflowed", JS_NewBool(ctx, ts && ts->changesOverflowed()));+ esjs::Val out = esjs::object();+ esjs::set(out, "serial", esjs::uint32(ts ? ts->compositionSerial() : 0));+ esjs::set(out, "tracking", esjs::boolean(ts && ts->changeTracking()));+ esjs::set(out, "overflowed", esjs::boolean(ts && ts->changesOverflowed()));const size_t count = ts ? ts->pendingChanges().size() : 0;- JS_SetPropertyStr(ctx, out, "count", JS_NewUint32(ctx, static_cast<uint32_t>(count)));- JS_SetPropertyStr(ctx, out, "visited", JS_NewUint32(ctx, ts ? ts->visited() : 0));- JS_SetPropertyStr(ctx, out, "changed", count == 0 ? JS_NULL- : esn_arraybuffer(ctx, const_cast<Entity*>(ts->pendingChanges().data()), count * sizeof(Entity)));+ esjs::set(out, "count", esjs::uint32(static_cast<uint32_t>(count)));+ esjs::set(out, "visited", esjs::uint32(ts ? ts->visited() : 0));+ esjs::set(out, "changed", count == 0 ? esjs::null()+ : esn_arraybuffer(const_cast<Entity*>(ts->pendingChanges().data()), count * sizeof(Entity)));return out;}/** Applied: the set starts again. Separate from the read, so a consumer that* throws half way through has not acknowledged and gets it again. */-JSValue js_transformTakeChanges(JSContext* ctx, JSValueConst, int, JSValueConst*) {- (void)ctx;+esjs::Val js_transformTakeChanges(const esjs::Args& a) {if (host().ctx) {if (auto* ts = host().ctx->tryGet<ecs::TransformSystem>()) ts->takeChanges();}- return JS_UNDEFINED;+ return esjs::undefined();}/** The consumer half: compose if a producer said the inputs moved. A headless* host installs no renderer, and nothing else would ever schedule it. */-JSValue js_transformEnsureComposed(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_transformEnsureComposed(const esjs::Args& a) {if (host().ctx && host().registry) {if (auto* ts = host().ctx->tryGet<ecs::TransformSystem>()) ts->ensureComposed(*host().registry);}- return JS_UNDEFINED;+ return esjs::undefined();}} // namespace-void registerEcsBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_createEntity", js_createEntity, 0);- bindGlobal(h, global, "es_destroyEntity", js_destroyEntity, 1);- bindGlobal(h, global, "es_setParent", js_setParent, 2);- bindGlobal(h, global, "es_reserveDestruction", js_reserveDestruction, 1);- bindGlobal(h, global, "es_releaseDestruction", js_releaseDestruction, 1);- bindGlobal(h, global, "es_destructionPending", js_destructionPending, 1);- bindGlobal(h, global, "es_setEntityEnabled", js_setEntityEnabled, 2);- bindGlobal(h, global, "es_isEntityActive", js_isEntityActive, 1);- bindGlobal(h, global, "es_isEntityEnabled", js_isEntityEnabled, 1);- bindGlobal(h, global, "es_hasInactiveEntities", js_hasInactiveEntities, 0);- bindGlobal(h, global, "es_activityEpoch", js_activityEpoch, 0);- bindGlobal(h, global, "es_hasParent", js_hasParent, 1);- bindGlobal(h, global, "es_getParent", js_getParent, 1);- bindGlobal(h, global, "es_removeParent", js_removeParent, 1);- bindGlobal(h, global, "es_hasChildren", js_hasChildren, 1);- bindGlobal(h, global, "es_getChildren", js_getChildren, 1);- bindGlobal(h, global, "es_getMeshSkinJoints", js_getMeshSkinJoints, 1);- bindGlobal(h, global, "es_setMeshSkinJoints", js_setMeshSkinJoints, 2);- bindGlobal(h, global, "es_registryLayoutEpoch", js_layoutEpoch, 0);- bindGlobal(h, global, "es_transformEpochBuffer", js_transformEpochBuffer, 0);- bindGlobal(h, global, "es_transformEnsureComposed", js_transformEnsureComposed, 0);- bindGlobal(h, global, "es_transformSetChangeTracking", js_transformSetChangeTracking, 1);- bindGlobal(h, global, "es_transformCompositionChanges", js_transformCompositionChanges, 0);- bindGlobal(h, global, "es_transformTakeChanges", js_transformTakeChanges, 0);+void registerEcsBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_createEntity", js_createEntity, 0);+ bindGlobal(global, "es_destroyEntity", js_destroyEntity, 1);+ bindGlobal(global, "es_setParent", js_setParent, 2);+ bindGlobal(global, "es_reserveDestruction", js_reserveDestruction, 1);+ bindGlobal(global, "es_releaseDestruction", js_releaseDestruction, 1);+ bindGlobal(global, "es_destructionPending", js_destructionPending, 1);+ bindGlobal(global, "es_setEntityEnabled", js_setEntityEnabled, 2);+ bindGlobal(global, "es_isEntityActive", js_isEntityActive, 1);+ bindGlobal(global, "es_isEntityEnabled", js_isEntityEnabled, 1);+ bindGlobal(global, "es_hasInactiveEntities", js_hasInactiveEntities, 0);+ bindGlobal(global, "es_activityEpoch", js_activityEpoch, 0);+ bindGlobal(global, "es_hasParent", js_hasParent, 1);+ bindGlobal(global, "es_getParent", js_getParent, 1);+ bindGlobal(global, "es_removeParent", js_removeParent, 1);+ bindGlobal(global, "es_hasChildren", js_hasChildren, 1);+ bindGlobal(global, "es_getChildren", js_getChildren, 1);+ bindGlobal(global, "es_getMeshSkinJoints", js_getMeshSkinJoints, 1);+ bindGlobal(global, "es_setMeshSkinJoints", js_setMeshSkinJoints, 2);+ bindGlobal(global, "es_registryLayoutEpoch", js_layoutEpoch, 0);+ bindGlobal(global, "es_transformEpochBuffer", js_transformEpochBuffer, 0);+ bindGlobal(global, "es_transformEnsureComposed", js_transformEnsureComposed, 0);+ bindGlobal(global, "es_transformSetChangeTracking", js_transformSetChangeTracking, 1);+ bindGlobal(global, "es_transformCompositionChanges", js_transformCompositionChanges, 0);+ bindGlobal(global, "es_transformTakeChanges", js_transformTakeChanges, 0);}} // namespace eshostdiff --git a/native/host/bindings/HeapBindings.cpp b/native/host/bindings/HeapBindings.cppindex d568ed023..ed92689e7 100644--- a/native/host/bindings/HeapBindings.cpp+++ b/native/host/bindings/HeapBindings.cpp@@ -157,36 +157,37 @@ namespace {// es_heap() -> ArrayBuffer over the whole arena. The SDK builds its typed-array// views on this once (`createNativeHeap`); the arena never moves, so unlike a// growable wasm heap the views stay valid for the process lifetime.-JSValue js_heap(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_heap(const esjs::Args& a) {uint8_t* base = heapBase();- if (!base) return JS_NULL;- return esn_arraybuffer(ctx, base, heapSize());+ if (!base) return esjs::null();+ return esn_arraybuffer(base, heapSize());}// es_malloc(bytes) -> offset (0 when full, which reads as null like _malloc).-JSValue js_malloc(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NewUint32(ctx, 0);+esjs::Val js_malloc(const esjs::Args& a) {+ if (a.size() < 1) return esjs::uint32(0);int64_t bytes = 0;- JS_ToInt64(ctx, &bytes, argv[0]);- if (bytes <= 0) return JS_NewUint32(ctx, 0);- return JS_NewUint32(ctx, heapAlloc(static_cast<size_t>(bytes)));+ bytes = esjs::toInt64(a[0]);+ if (bytes <= 0) return esjs::uint32(0);+ return esjs::uint32(heapAlloc(static_cast<size_t>(bytes)));}// es_free(offset).-JSValue js_free(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_UNDEFINED;+esjs::Val js_free(const esjs::Args& a) {+ if (a.size() < 1) return esjs::undefined();uint32_t offset = 0;- JS_ToUint32(ctx, &offset, argv[0]);+ offset = esjs::toUint32(a[0]);heapFree(offset);- return JS_UNDEFINED;+ return esjs::undefined();}} // namespace-void registerHeapBindings(HostState& h, JSValue global) {- JS_SetPropertyStr(h.js, global, "es_heap", JS_NewCFunction(h.js, js_heap, "es_heap", 0));- JS_SetPropertyStr(h.js, global, "es_malloc", JS_NewCFunction(h.js, js_malloc, "es_malloc", 1));- JS_SetPropertyStr(h.js, global, "es_free", JS_NewCFunction(h.js, js_free, "es_free", 1));+void registerHeapBindings(HostState& h, esjs::Val global) {+ (void)h;+ bindGlobal(global, "es_heap", js_heap, 0);+ bindGlobal(global, "es_malloc", js_malloc, 1);+ bindGlobal(global, "es_free", js_free, 1);}} // namespace eshostdiff --git a/native/host/bindings/InputBindings.cpp b/native/host/bindings/InputBindings.cppindex 418671d09..68459703a 100644--- a/native/host/bindings/InputBindings.cpp+++ b/native/host/bindings/InputBindings.cpp@@ -22,10 +22,10 @@namespace eshost {namespace {-JSValue floatArray(JSContext* ctx, const float* values, int count) {- JSValue arr = JS_NewArray(ctx);+esjs::Val floatArray(const float* values, int count) {+ esjs::Val arr = esjs::array();for (int i = 0; i < count; ++i) {- JS_SetPropertyUint32(ctx, arr, (uint32_t)i, JS_NewFloat64(ctx, values[i]));+ esjs::setAt(arr, (uint32_t)i, esjs::number(values[i]));}return arr;}@@ -33,28 +33,28 @@ JSValue floatArray(JSContext* ctx, const float* values, int count) {// es_pollGamepads() -> [{ index, connected, buttons[], axes[] }]. `mapping` is// added by the adapter, which is where the claim that this IS the standard// layout belongs.-JSValue js_pollGamepads(JSContext* ctx, JSValueConst, int, JSValueConst*) {- JSValue arr = JS_NewArray(ctx);+esjs::Val js_pollGamepads(const esjs::Args& a) {+ esjs::Val arr = esjs::array();if (!hostAlive() || !host().platform) return arr;std::vector<GamepadState> pads;host().platform->pollGamepads(pads);uint32_t n = 0;for (const GamepadState& pad : pads) {- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "index", JS_NewInt32(ctx, pad.index));- JS_SetPropertyStr(ctx, o, "connected", JS_NewBool(ctx, pad.connected));- JS_SetPropertyStr(ctx, o, "buttons", floatArray(ctx, pad.buttons, 17));- JS_SetPropertyStr(ctx, o, "axes", floatArray(ctx, pad.axes, 4));- JS_SetPropertyUint32(ctx, arr, n++, o);+ esjs::Val o = esjs::object();+ esjs::set(o, "index", esjs::int32(pad.index));+ esjs::set(o, "connected", esjs::boolean(pad.connected));+ esjs::set(o, "buttons", floatArray(pad.buttons, 17));+ esjs::set(o, "axes", floatArray(pad.axes, 4));+ esjs::setAt(arr, n++, o);}return arr;}} // namespace-void registerInputBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_pollGamepads", js_pollGamepads, 0);+void registerInputBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_pollGamepads", js_pollGamepads, 0);}} // namespace eshostdiff --git a/native/host/bindings/NetBindings.cpp b/native/host/bindings/NetBindings.cppindex 38f6fa09a..3b5b5cc8c 100644--- a/native/host/bindings/NetBindings.cpp+++ b/native/host/bindings/NetBindings.cpp@@ -41,35 +41,17 @@ std::queue<FetchResult> g_fetchQueue;std::mutex g_wsMutex;std::queue<WsEvent> g_wsQueue;-std::string fetchStrProp(JSContext* ctx, JSValueConst obj, const char* key, const char* dflt) {- JSValue v = JS_GetPropertyStr(ctx, obj, key);- std::string out = dflt ? dflt : "";- if (JS_IsString(v)) {- if (const char* s = JS_ToCString(ctx, v)) { out = s; JS_FreeCString(ctx, s); }- }- JS_FreeValue(ctx, v);- return out;+std::string fetchStrProp(esjs::Val obj, const char* key, const char* dflt) {+ const esjs::Val v = esjs::get(obj, key);+ return esjs::isString(v) ? esjs::toString(v) : std::string(dflt ? dflt : "");}-void readFetchHeaders(JSContext* ctx, JSValueConst obj, FetchRequest& req) {- JSValue h = JS_GetPropertyStr(ctx, obj, "headers");- if (JS_IsObject(h)) {- JSPropertyEnum* tab = nullptr;- uint32_t len = 0;- if (JS_GetOwnPropertyNames(ctx, &tab, &len, h, JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {- for (uint32_t i = 0; i < len; ++i) {- const char* key = JS_AtomToCString(ctx, tab[i].atom);- JSValue val = JS_GetProperty(ctx, h, tab[i].atom);- const char* vs = JS_ToCString(ctx, val);- if (key && vs) req.headers.emplace_back(key, vs);- if (vs) JS_FreeCString(ctx, vs);- if (key) JS_FreeCString(ctx, key);- JS_FreeValue(ctx, val);- }- JS_FreePropertyEnum(ctx, tab, len);- }+void readFetchHeaders(esjs::Val obj, FetchRequest& req) {+ const esjs::Val h = esjs::get(obj, "headers");+ if (!esjs::isObject(h)) return;+ for (const std::string& key : esjs::ownKeys(h)) {+ req.headers.emplace_back(key, esjs::toString(esjs::get(h, key.c_str())));}- JS_FreeValue(ctx, h);}// es_fetch(request, callback): request = { url, method?, headers?, body?,@@ -77,28 +59,24 @@ void readFetchHeaders(JSContext* ctx, JSValueConst obj, FetchRequest& req) {// { ok, status, statusText, headers, arrayBuffer | text, error? }. The bridge// wraps this in a Promise. responseType 'text' returns a string; everything else// returns an ArrayBuffer (the bridge decodes text/json from it on demand).-JSValue js_fetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2 || !JS_IsObject(argv[0]) || !JS_IsFunction(ctx, argv[1])) return JS_UNDEFINED;+esjs::Val js_fetch(const esjs::Args& a) {+ if (a.size() < 2 || !esjs::isObject(a[0]) || !esjs::isFunction(a[1])) return esjs::undefined();HostState& h = host();FetchRequest req;req.id = h.nextFetchId++;- req.url = fetchStrProp(ctx, argv[0], "url", "");- req.method = fetchStrProp(ctx, argv[0], "method", "GET");- req.wantText = fetchStrProp(ctx, argv[0], "responseType", "arraybuffer") == "text";- readFetchHeaders(ctx, argv[0], req);- JSValue body = JS_GetPropertyStr(ctx, argv[0], "body");- if (JS_IsString(body)) {- size_t len = 0;- if (const char* s = JS_ToCStringLen(ctx, &len, body)) {- req.body.assign(s, s + len);- JS_FreeCString(ctx, s);- }- } else if (!JS_IsUndefined(body) && !JS_IsNull(body)) {- readByteSource(ctx, body, req.body);+ req.url = fetchStrProp(a[0], "url", "");+ req.method = fetchStrProp(a[0], "method", "GET");+ req.wantText = fetchStrProp(a[0], "responseType", "arraybuffer") == "text";+ readFetchHeaders(a[0], req);+ const esjs::Val body = esjs::get(a[0], "body");+ if (esjs::isString(body)) {+ const esjs::Utf8 text(body);+ req.body.assign(text.c_str(), text.c_str() + text.size());+ } else if (!esjs::isNullish(body)) {+ readByteSource(body, req.body);}- JS_FreeValue(ctx, body);- h.fetchCallbacks[req.id] = JS_DupValue(ctx, argv[1]);+ h.fetchCallbacks[req.id] = esjs::Ref(a[1]);if (req.url.empty()) {FetchResult err;err.id = req.id;@@ -107,72 +85,58 @@ JSValue js_fetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {} else {h.platform->startFetch(req);}- return JS_UNDEFINED;+ return esjs::undefined();}-JSValue makeFetchResult(HostState& h, const FetchResult& r) {- JSValue o = JS_NewObject(h.js);- JS_SetPropertyStr(h.js, o, "ok", JS_NewBool(h.js, r.ok));- JS_SetPropertyStr(h.js, o, "status", JS_NewInt32(h.js, r.status));- JS_SetPropertyStr(h.js, o, "statusText", JS_NewString(h.js, r.statusText.c_str()));- if (!r.error.empty()) JS_SetPropertyStr(h.js, o, "error", JS_NewString(h.js, r.error.c_str()));- JSValue headers = JS_NewObject(h.js);- for (const auto& kv : r.headers) {- JS_SetPropertyStr(h.js, headers, kv.first.c_str(), JS_NewString(h.js, kv.second.c_str()));- }- JS_SetPropertyStr(h.js, o, "headers", headers);+esjs::Val makeFetchResult(const FetchResult& r) {+ const esjs::Val o = esjs::object();+ esjs::set(o, "ok", esjs::boolean(r.ok));+ esjs::set(o, "status", esjs::int32(r.status));+ esjs::set(o, "statusText", esjs::string(r.statusText));+ if (!r.error.empty()) esjs::set(o, "error", esjs::string(r.error));+ const esjs::Val headers = esjs::object();+ for (const auto& kv : r.headers) esjs::set(headers, kv.first.c_str(), esjs::string(kv.second));+ esjs::set(o, "headers", headers);if (r.isText) {- JS_SetPropertyStr(h.js, o, "text",- JS_NewStringLen(h.js, reinterpret_cast<const char*>(r.body.data()), r.body.size()));+ esjs::set(o, "text", esjs::string(std::string_view(reinterpret_cast<const char*>(r.body.data()), r.body.size())));} else {- JS_SetPropertyStr(h.js, o, "arrayBuffer",- JS_NewArrayBufferCopy(h.js, r.body.data(), r.body.size()));+ esjs::set(o, "arrayBuffer", esjs::arrayBufferCopy(r.body.data(), r.body.size()));}return o;}// es_wsOpen(url, onEvent) -> id: onEvent({ type: 'open' | 'message' | 'error' | 'close',// data?: string | ArrayBuffer, code?, reason? }). 'close' is always the last event.-JSValue js_wsOpen(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2 || !JS_IsFunction(ctx, argv[1])) return JS_ThrowTypeError(ctx, "es_wsOpen(url, onEvent)");- const char* url = JS_ToCString(ctx, argv[0]);- if (!url) return JS_EXCEPTION;- const std::string u = url;- JS_FreeCString(ctx, url);+esjs::Val js_wsOpen(const esjs::Args& a) {+ if (a.size() < 2 || !esjs::isFunction(a[1])) return esjs::throwTypeError("es_wsOpen(url, onEvent)");+ const std::string u = esjs::toString(a[0]);const int id = wsOpen(u, [](WsEvent e) {std::lock_guard<std::mutex> lk(g_wsMutex);g_wsQueue.push(std::move(e));});- host().wsCallbacks[id] = JS_DupValue(ctx, argv[1]);- return JS_NewInt32(ctx, id);+ host().wsCallbacks[id] = esjs::Ref(a[1]);+ return esjs::int32(id);}-JSValue js_wsSend(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t id = 0;- if (argc < 2 || JS_ToInt32(ctx, &id, argv[0])) return JS_FALSE;- if (JS_IsString(argv[1])) {- size_t len = 0;- const char* s = JS_ToCStringLen(ctx, &len, argv[1]);- if (!s) return JS_EXCEPTION;- const bool ok = wsSend(id, reinterpret_cast<const uint8_t*>(s), len, true);- JS_FreeCString(ctx, s);- return JS_NewBool(ctx, ok);+esjs::Val js_wsSend(const esjs::Args& a) {+ if (a.size() < 2) return esjs::boolean(false);+ const int32_t id = esjs::toInt32(a[0]);+ if (esjs::isString(a[1])) {+ const esjs::Utf8 text(a[1]);+ return esjs::boolean(wsSend(id, reinterpret_cast<const uint8_t*>(text.c_str()), text.size(), true));}std::vector<uint8_t> bytes;- readByteSource(ctx, argv[1], bytes);- return JS_NewBool(ctx, wsSend(id, bytes.data(), bytes.size(), false));+ readByteSource(a[1], bytes);+ return esjs::boolean(wsSend(id, bytes.data(), bytes.size(), false));}-JSValue js_wsClose(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t id = 0, code = 1000;- if (argc < 1 || JS_ToInt32(ctx, &id, argv[0])) return JS_UNDEFINED;- if (argc > 1 && !JS_IsUndefined(argv[1])) JS_ToInt32(ctx, &code, argv[1]);- std::string reason;- if (argc > 2 && JS_IsString(argv[2])) {- if (const char* r = JS_ToCString(ctx, argv[2])) { reason = r; JS_FreeCString(ctx, r); }- }+esjs::Val js_wsClose(const esjs::Args& a) {+ if (a.size() < 1) return esjs::undefined();+ const int32_t id = esjs::toInt32(a[0]);+ const int32_t code = a.size() > 1 && !esjs::isUndefined(a[1]) ? esjs::toInt32(a[1]) : 1000;+ const std::string reason = a.size() > 2 && esjs::isString(a[2]) ? esjs::toString(a[2]) : std::string();wsClose(id, code, reason);- return JS_UNDEFINED;+ return esjs::undefined();}} // namespace@@ -181,60 +145,55 @@ void drainSockets(HostState& h) {std::queue<WsEvent> events;{ std::lock_guard<std::mutex> lk(g_wsMutex); events.swap(g_wsQueue); }if (events.empty()) return;- jsEntry(h);+ esjs::Enter enter;while (!events.empty()) {WsEvent e = std::move(events.front());events.pop();auto it = h.wsCallbacks.find(e.id);if (it == h.wsCallbacks.end()) continue;- JSValue o = JS_NewObject(h.js);+ esjs::Scope scope;+ const esjs::Val o = esjs::object();const char* type = e.kind == WsEvent::Kind::Open ? "open": e.kind == WsEvent::Kind::Error ? "error": e.kind == WsEvent::Kind::Close ? "close" : "message";- JS_SetPropertyStr(h.js, o, "type", JS_NewString(h.js, type));+ esjs::set(o, "type", esjs::string(type));if (e.kind == WsEvent::Kind::Text) {- JS_SetPropertyStr(h.js, o, "data",- JS_NewStringLen(h.js, reinterpret_cast<const char*>(e.data.data()), e.data.size()));+ esjs::set(o, "data", esjs::string(std::string_view(reinterpret_cast<const char*>(e.data.data()), e.data.size())));} else if (e.kind == WsEvent::Kind::Binary) {- JS_SetPropertyStr(h.js, o, "data", JS_NewArrayBufferCopy(h.js, e.data.data(), e.data.size()));+ esjs::set(o, "data", esjs::arrayBufferCopy(e.data.data(), e.data.size()));}- if (e.kind == WsEvent::Kind::Close) JS_SetPropertyStr(h.js, o, "code", JS_NewInt32(h.js, e.code));- if (!e.reason.empty()) JS_SetPropertyStr(h.js, o, "reason", JS_NewString(h.js, e.reason.c_str()));- JSValue cb = it->second;+ if (e.kind == WsEvent::Kind::Close) esjs::set(o, "code", esjs::int32(e.code));+ if (!e.reason.empty()) esjs::set(o, "reason", esjs::string(e.reason));+ // A close is the last event: the callback is released once it has run.+ esjs::Ref cb = e.kind == WsEvent::Kind::Close ? std::move(it->second) : esjs::Ref(it->second.get());if (e.kind == WsEvent::Kind::Close) h.wsCallbacks.erase(it);- JSValue ret = JS_Call(h.js, cb, JS_UNDEFINED, 1, &o);- if (JS_IsException(ret)) logJsError(h.js, "es_wsOpen event");- JS_FreeValue(h.js, ret);- JS_FreeValue(h.js, o);- if (e.kind == WsEvent::Kind::Close) JS_FreeValue(h.js, cb);+ esjs::call(cb.get(), esjs::undefined(), 1, &o, "es_wsOpen event");}}void drainFetches(HostState& h) {- jsEntry(h);std::queue<FetchResult> done;{ std::lock_guard<std::mutex> lk(g_fetchMutex); done.swap(g_fetchQueue); }+ if (done.empty()) return;+ esjs::Enter enter;while (!done.empty()) {const FetchResult r = std::move(done.front());done.pop();auto it = h.fetchCallbacks.find(r.id);if (it == h.fetchCallbacks.end()) continue; // never happens, but stay safe- JSValue cb = it->second;+ esjs::Ref cb = std::move(it->second);h.fetchCallbacks.erase(it);- JSValue arg = makeFetchResult(h, r);- JSValue ret = JS_Call(h.js, cb, JS_UNDEFINED, 1, &arg);- if (JS_IsException(ret)) logJsError(h.js, "es_fetch callback");- JS_FreeValue(h.js, ret);- JS_FreeValue(h.js, arg);- JS_FreeValue(h.js, cb);+ esjs::Scope scope;+ const esjs::Val arg = makeFetchResult(r);+ esjs::call(cb.get(), esjs::undefined(), 1, &arg, "es_fetch callback");}}-void registerNetBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_fetch", js_fetch, 2);- bindGlobal(h, global, "es_wsOpen", js_wsOpen, 2);- bindGlobal(h, global, "es_wsSend", js_wsSend, 2);- bindGlobal(h, global, "es_wsClose", js_wsClose, 3);+void registerNetBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_fetch", js_fetch, 2);+ bindGlobal(global, "es_wsOpen", js_wsOpen, 2);+ bindGlobal(global, "es_wsSend", js_wsSend, 2);+ bindGlobal(global, "es_wsClose", js_wsClose, 3);}// Thread-safe: the platform's HTTP completion (any thread) queues its reply here;diff --git a/native/host/bindings/RenderBindings.cpp b/native/host/bindings/RenderBindings.cppindex e0f692dfb..faaecd371 100644--- a/native/host/bindings/RenderBindings.cpp+++ b/native/host/bindings/RenderBindings.cpp@@ -46,67 +46,60 @@ namespace {// uploads through WebGL2, so there is no engine entry point shared with it.// `format`/`blockRefused` carry the CHOICE out: an RGBA upload is otherwise a// correct picture at four times the memory, with nothing saying it happened.-JSValue js_createTextureKTX2(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1) return JS_NULL;+esjs::Val js_createTextureKTX2(const esjs::Args& a) {+ if (a.size() < 1) return esjs::null();std::vector<u8> bytes;- readByteSource(ctx, argv[0], bytes);- if (bytes.empty()) return JS_NULL;- const bool srgb = argc > 1 && JS_ToBool(ctx, argv[1]) != 0;+ readByteSource(a[0], bytes);+ if (bytes.empty()) return esjs::null();+ const bool srgb = a.size() > 1 && esjs::toBool(a[1]);auto r = transcodeKTX2(bytes.data(), bytes.size(), srgb,host().ctx->require<resource::ResourceManager>(), *host().gfx);- if (r.handle < 0) return JS_NULL;- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "id", JS_NewInt32(ctx, r.handle));- JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, r.width));- JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, r.height));- JS_SetPropertyStr(ctx, o, "format", JS_NewInt32(ctx, r.format));- JS_SetPropertyStr(ctx, o, "blockRefused", JS_NewBool(ctx, r.blockRefused));+ if (r.handle < 0) return esjs::null();+ esjs::Val o = esjs::object();+ esjs::set(o, "id", esjs::int32(r.handle));+ esjs::set(o, "width", esjs::int32(r.width));+ esjs::set(o, "height", esjs::int32(r.height));+ esjs::set(o, "format", esjs::int32(r.format));+ esjs::set(o, "blockRefused", esjs::boolean(r.blockRefused));return o;}// es_getTextureDimensions(handle) -> { width, height } | null. The engine's// rm_getTextureDimensions returns an emscripten::val, so this one query stays// hand-written; it reads the same ResourceManager that entry point would.-JSValue js_getTextureDimensions(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+esjs::Val js_getTextureDimensions(const esjs::Args& a) {int64_t id = 0;- JS_ToInt64(ctx, &id, argv[0]);+ id = esjs::toInt64(a[0]);auto* tex = host().ctx->require<resource::ResourceManager>().getTexture(resource::TextureHandle((u32)id));- if (!tex) return JS_NULL;- JSValue obj = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, obj, "width", JS_NewInt32(ctx, (int32_t)tex->getWidth()));- JS_SetPropertyStr(ctx, obj, "height", JS_NewInt32(ctx, (int32_t)tex->getHeight()));+ if (!tex) return esjs::null();+ esjs::Val obj = esjs::object();+ esjs::set(obj, "width", esjs::int32((int32_t)tex->getWidth()));+ esjs::set(obj, "height", esjs::int32((int32_t)tex->getHeight()));return obj;}// es_rasterizeGlyph({ codepoint, fontFamily, style, pixelSize, sdf, padding })// -> { pixels: ArrayBuffer, width, height, advance, bearingX, bearingY } | null.// The device's answer to the browser's 2D canvas; see media/glyph_raster.hpp.-JSValue js_rasterizeGlyph(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 1 || !hostAlive() || !host().platform) return JS_NULL;- JSValue req = argv[0];+esjs::Val js_rasterizeGlyph(const esjs::Args& a) {+ if (a.size() < 1 || !hostAlive() || !host().platform) return esjs::null();+ esjs::Val req = a[0];const auto numberField = [&](const char* name, double fallback) {- JSValue v = JS_GetPropertyStr(ctx, req, name);+ esjs::Val v = esjs::get(req, name);double out = fallback;- if (!JS_IsUndefined(v)) JS_ToFloat64(ctx, &out, v);- JS_FreeValue(ctx, v);+ if (!esjs::isUndefined(v)) out = esjs::toNumber(v);return out;};const auto boolField = [&](const char* name) {- JSValue v = JS_GetPropertyStr(ctx, req, name);- const bool out = JS_ToBool(ctx, v) != 0;- JS_FreeValue(ctx, v);+ esjs::Val v = esjs::get(req, name);+ const bool out = esjs::toBool(v);return out;};- std::string family;- JSValue familyVal = JS_GetPropertyStr(ctx, req, "fontFamily");- if (const char* s = JS_ToCString(ctx, familyVal)) {- family = s;- JS_FreeCString(ctx, s);- }- JS_FreeValue(ctx, familyVal);+ const esjs::Val familyVal = esjs::get(req, "fontFamily");+ const std::string family = esjs::isNullish(familyVal) ? std::string() : esjs::toString(familyVal);const auto glyph = rasterizeGlyph(*host().platform,@@ -116,63 +109,60 @@ JSValue js_rasterizeGlyph(JSContext* ctx, JSValueConst, int argc, JSValueConst*(float)numberField("pixelSize", 48),boolField("sdf"),(float)numberField("padding", 6));- if (!glyph.ok) return JS_NULL;-- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "pixels",- glyph.rgba.empty() ? JS_NewArrayBufferCopy(ctx, nullptr, 0)- : JS_NewArrayBufferCopy(ctx, glyph.rgba.data(), glyph.rgba.size()));- JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, glyph.width));- JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, glyph.height));- JS_SetPropertyStr(ctx, o, "advance", JS_NewFloat64(ctx, glyph.advance));- JS_SetPropertyStr(ctx, o, "bearingX", JS_NewFloat64(ctx, glyph.bearingX));- JS_SetPropertyStr(ctx, o, "bearingY", JS_NewFloat64(ctx, glyph.bearingY));+ if (!glyph.ok) return esjs::null();++ esjs::Val o = esjs::object();+ esjs::set(o, "pixels", glyph.rgba.empty() ? esjs::arrayBufferCopy(nullptr, 0)+ : esjs::arrayBufferCopy(glyph.rgba.data(), glyph.rgba.size()));+ esjs::set(o, "width", esjs::int32(glyph.width));+ esjs::set(o, "height", esjs::int32(glyph.height));+ esjs::set(o, "advance", esjs::number(glyph.advance));+ esjs::set(o, "bearingX", esjs::number(glyph.bearingX));+ esjs::set(o, "bearingY", esjs::number(glyph.bearingY));return o;}// es_renderer_surfaceSize() -> { width, height }: the camera plugin reads it per// frame, so a rotation reaches the projection without an event.-JSValue js_renderer_surfaceSize(JSContext* ctx, JSValueConst, int, JSValueConst*) {- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "width", JS_NewInt32(ctx, hostAlive() ? (int32_t)host().w : 0));- JS_SetPropertyStr(ctx, o, "height", JS_NewInt32(ctx, hostAlive() ? (int32_t)host().h : 0));+esjs::Val js_renderer_surfaceSize(const esjs::Args& a) {+ esjs::Val o = esjs::object();+ esjs::set(o, "width", esjs::int32(hostAlive() ? (int32_t)host().w : 0));+ esjs::set(o, "height", esjs::int32(hostAlive() ? (int32_t)host().h : 0));return o;}// OS content insets in the same pixel domain as the rendered surface.-JSValue js_safeAreaInsets(JSContext* ctx, JSValueConst, int, JSValueConst*) {+esjs::Val js_safeAreaInsets(const esjs::Args& a) {const auto insets = hostAlive() && host().platform? host().platform->safeAreaInsets() : Platform::SafeInsets{};- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "top", JS_NewFloat64(ctx, insets.top));- JS_SetPropertyStr(ctx, o, "bottom", JS_NewFloat64(ctx, insets.bottom));- JS_SetPropertyStr(ctx, o, "left", JS_NewFloat64(ctx, insets.left));- JS_SetPropertyStr(ctx, o, "right", JS_NewFloat64(ctx, insets.right));+ esjs::Val o = esjs::object();+ esjs::set(o, "top", esjs::number(insets.top));+ esjs::set(o, "bottom", esjs::number(insets.bottom));+ esjs::set(o, "left", esjs::number(insets.left));+ esjs::set(o, "right", esjs::number(insets.right));return o;}// es_setWindowSize(w, h): the project's design resolution, which only the SDK can// read (the window exists before any JS, and the host parses no JSON). A platform// that is GIVEN its screen ignores it.-JSValue js_setWindowSize(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t w = 0, h = 0;- if (argc < 2 || JS_ToInt32(ctx, &w, argv[0]) < 0 || JS_ToInt32(ctx, &h, argv[1]) < 0) {- return JS_UNDEFINED;- }+esjs::Val js_setWindowSize(const esjs::Args& a) {+ if (a.size() < 2) return esjs::undefined();+ const int32_t w = esjs::toInt32(a[0]), h = esjs::toInt32(a[1]);if (host().platform) host().platform->setWindowSize(w, h);- return JS_UNDEFINED;+ return esjs::undefined();}// es_registry_getCameraEntities() -> [entity]. Active cameras with a Transform,// as the web binding reports them (its sibling returns an emscripten::val array).-JSValue js_registry_getCameraEntities(JSContext* ctx, JSValueConst, int, JSValueConst*) {- JSValue arr = JS_NewArray(ctx);+esjs::Val js_registry_getCameraEntities(const esjs::Args& a) {+ esjs::Val arr = esjs::array();if (!hostAlive() || !host().registry) return arr;auto& registry = *host().registry;uint32_t n = 0;for (auto entity : registry.activeView<ecs::Camera, ecs::Transform>()) {if (registry.get<ecs::Camera>(entity).isActive) {- JS_SetPropertyUint32(ctx, arr, n++, JS_NewInt32(ctx, (int32_t)entity.id()));+ esjs::setAt(arr, n++, esjs::int32((int32_t)entity.id()));}}return arr;@@ -180,14 +170,14 @@ JSValue js_registry_getCameraEntities(JSContext* ctx, JSValueConst, int, JSValue} // namespace-void registerRenderBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_createTextureKTX2", js_createTextureKTX2, 2);- bindGlobal(h, global, "es_getTextureDimensions", js_getTextureDimensions, 1);- bindGlobal(h, global, "es_rasterizeGlyph", js_rasterizeGlyph, 1);- bindGlobal(h, global, "es_renderer_surfaceSize", js_renderer_surfaceSize, 0);- bindGlobal(h, global, "es_safeAreaInsets", js_safeAreaInsets, 0);- bindGlobal(h, global, "es_setWindowSize", js_setWindowSize, 2);- bindGlobal(h, global, "es_registry_getCameraEntities", js_registry_getCameraEntities, 0);+void registerRenderBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_createTextureKTX2", js_createTextureKTX2, 2);+ bindGlobal(global, "es_getTextureDimensions", js_getTextureDimensions, 1);+ bindGlobal(global, "es_rasterizeGlyph", js_rasterizeGlyph, 1);+ bindGlobal(global, "es_renderer_surfaceSize", js_renderer_surfaceSize, 0);+ bindGlobal(global, "es_safeAreaInsets", js_safeAreaInsets, 0);+ bindGlobal(global, "es_setWindowSize", js_setWindowSize, 2);+ bindGlobal(global, "es_registry_getCameraEntities", js_registry_getCameraEntities, 0);}} // namespace eshostdiff --git a/native/host/bindings/SteamBindings.cpp b/native/host/bindings/SteamBindings.cppindex 3718e6b43..49c28d210 100644--- a/native/host/bindings/SteamBindings.cpp+++ b/native/host/bindings/SteamBindings.cpp@@ -23,18 +23,17 @@ namespace {/** Push the overlay's state into JS, where the services layer pauses the game. */void deliverSteamOverlay(bool covered) {- HostState& h = host();- if (!h.js) return;- JSValue arg = JS_NewBool(h.js, covered);- callJs(h, "es_onSteamOverlay", 1, &arg);- JS_FreeValue(h.js, arg);+ if (!hostAlive() || !esjs::alive()) return;+ esjs::Enter enter;+ const esjs::Val arg = esjs::boolean(covered);+ callJs(host(), "es_onSteamOverlay", 1, &arg);}// es_steam_init(appId) -> bool. Called by the SDK, which is where game.config.json// is read — the host has no JSON parser and no reason to grow one.-JSValue js_steam_init(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- int32_t appId = 0;- if (argc < 1 || JS_ToInt32(ctx, &appId, argv[0]) < 0 || appId <= 0) return JS_NewBool(ctx, false);+esjs::Val js_steam_init(const esjs::Args& a) {+ const int32_t appId = a.size() < 1 ? 0 : esjs::toInt32(a[0]);+ if (appId <= 0) return esjs::boolean(false);// The platform says where the redistributable was shipped. A leaf name would// do on Windows and silently never resolve on macOS (see SteamApi::init).const std::string dir = host().platform ? host().platform->executableDir() : std::string();@@ -54,74 +53,72 @@ JSValue js_steam_init(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv// answer that is not a guess.ESHOST_LOGI("steam: unavailable — %s", steam().lastError().c_str());}- return JS_NewBool(ctx, ok);+ return esjs::boolean(ok);}-JSValue js_steam_available(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewBool(ctx, steam().available());+esjs::Val js_steam_available(const esjs::Args& a) {+ return esjs::boolean(steam().available());}// es_steam_identity() -> { id, name }: the signed-in account. The id is a STRING// because a 64-bit account id does not survive a double.-JSValue js_steam_identity(JSContext* ctx, JSValueConst, int, JSValueConst*) {- JSValue o = JS_NewObject(ctx);- JS_SetPropertyStr(ctx, o, "id", JS_NewString(ctx, steam().steamId().c_str()));- JS_SetPropertyStr(ctx, o, "name", JS_NewString(ctx, steam().personaName().c_str()));+esjs::Val js_steam_identity(const esjs::Args& a) {+ esjs::Val o = esjs::object();+ esjs::set(o, "id", esjs::string(steam().steamId().c_str()));+ esjs::set(o, "name", esjs::string(steam().personaName().c_str()));return o;}-const char* argString(JSContext* ctx, JSValueConst v, std::string& keep) {- const char* s = JS_ToCString(ctx, v);- keep = s ? s : "";- if (s) JS_FreeCString(ctx, s);+const char* argString(esjs::Val v, std::string& keep) {+ keep = esjs::toString(v);return keep.c_str();}-JSValue js_steam_unlock(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+esjs::Val js_steam_unlock(const esjs::Args& a) {std::string id;- if (argc < 1) return JS_NewBool(ctx, false);- return JS_NewBool(ctx, steam().unlock(argString(ctx, argv[0], id)));+ if (a.size() < 1) return esjs::boolean(false);+ return esjs::boolean(steam().unlock(argString(a[0], id)));}-JSValue js_steam_unlocked(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+esjs::Val js_steam_unlocked(const esjs::Args& a) {std::string id;- if (argc < 1) return JS_NewBool(ctx, false);- return JS_NewBool(ctx, steam().unlocked(argString(ctx, argv[0], id)));+ if (a.size() < 1) return esjs::boolean(false);+ return esjs::boolean(steam().unlocked(argString(a[0], id)));}-JSValue js_steam_setStat(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+esjs::Val js_steam_setStat(const esjs::Args& a) {std::string name;- int32_t value = 0;- if (argc < 2 || JS_ToInt32(ctx, &value, argv[1]) < 0) return JS_NewBool(ctx, false);- return JS_NewBool(ctx, steam().setStat(argString(ctx, argv[0], name), value));+ if (a.size() < 2) return esjs::boolean(false);+ const int32_t value = esjs::toInt32(a[1]);+ return esjs::boolean(steam().setStat(argString(a[0], name), value));}-JSValue js_steam_getStat(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+esjs::Val js_steam_getStat(const esjs::Args& a) {std::string name;- if (argc < 1) return JS_NewInt32(ctx, 0);- return JS_NewInt32(ctx, steam().stat(argString(ctx, argv[0], name)));+ if (a.size() < 1) return esjs::int32(0);+ return esjs::int32(steam().stat(argString(a[0], name)));}-JSValue js_steam_store(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewBool(ctx, steam().store());+esjs::Val js_steam_store(const esjs::Args& a) {+ return esjs::boolean(steam().store());}-JSValue js_steam_reset(JSContext* ctx, JSValueConst, int, JSValueConst*) {- return JS_NewBool(ctx, steam().reset());+esjs::Val js_steam_reset(const esjs::Args& a) {+ return esjs::boolean(steam().reset());}} // namespace-void registerSteamBindings(HostState& h, JSValue global) {- bindGlobal(h, global, "es_steam_init", js_steam_init, 1);- bindGlobal(h, global, "es_steam_available", js_steam_available, 0);- bindGlobal(h, global, "es_steam_identity", js_steam_identity, 0);- bindGlobal(h, global, "es_steam_unlock", js_steam_unlock, 1);- bindGlobal(h, global, "es_steam_unlocked", js_steam_unlocked, 1);- bindGlobal(h, global, "es_steam_setStat", js_steam_setStat, 2);- bindGlobal(h, global, "es_steam_getStat", js_steam_getStat, 1);- bindGlobal(h, global, "es_steam_store", js_steam_store, 0);- bindGlobal(h, global, "es_steam_reset", js_steam_reset, 0);+void registerSteamBindings(HostState& h, esjs::Val global) {+ bindGlobal(global, "es_steam_init", js_steam_init, 1);+ bindGlobal(global, "es_steam_available", js_steam_available, 0);+ bindGlobal(global, "es_steam_identity", js_steam_identity, 0);+ bindGlobal(global, "es_steam_unlock", js_steam_unlock, 1);+ bindGlobal(global, "es_steam_unlocked", js_steam_unlocked, 1);+ bindGlobal(global, "es_steam_setStat", js_steam_setStat, 2);+ bindGlobal(global, "es_steam_getStat", js_steam_getStat, 1);+ bindGlobal(global, "es_steam_store", js_steam_store, 0);+ bindGlobal(global, "es_steam_reset", js_steam_reset, 0);}} // namespace eshostdiff --git a/native/host/bindings/TextEditorBindings.cpp b/native/host/bindings/TextEditorBindings.cppindex ebbb9b5f1..aa2580eb1 100644--- a/native/host/bindings/TextEditorBindings.cpp+++ b/native/host/bindings/TextEditorBindings.cpp@@ -52,59 +52,48 @@ void push(EditorPush item) {g_queue.push(std::move(item));}-std::string argString(JSContext* ctx, JSValueConst v) {- std::string out;- if (const char* s = JS_ToCString(ctx, v)) {- out = s;- JS_FreeCString(ctx, s);- }- return out;-}+std::string argString(esjs::Val v) { return esjs::toString(v); }-int argInt(JSContext* ctx, JSValueConst v) {- int32_t out = 0;- JS_ToInt32(ctx, &out, v);- return out;-}+int argInt(esjs::Val v) { return esjs::toInt32(v); }// es_textEditor_focus(value, selectionStart, selectionEnd, multiline, maxLength, password)-JSValue js_textEditor_focus(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 6 || !hostAlive() || !host().platform) return JS_UNDEFINED;- host().platform->textEditorFocus(argString(ctx, argv[0]), argInt(ctx, argv[1]),- argInt(ctx, argv[2]), JS_ToBool(ctx, argv[3]) != 0,- argInt(ctx, argv[4]), JS_ToBool(ctx, argv[5]) != 0);- return JS_UNDEFINED;+esjs::Val js_textEditor_focus(const esjs::Args& a) {+ if (a.size() < 6 || !hostAlive() || !host().platform) return esjs::undefined();+ host().platform->textEditorFocus(argString(a[0]), argInt(a[1]),+ argInt(a[2]), esjs::toBool(a[3]),+ argInt(a[4]), esjs::toBool(a[5]));+ return esjs::undefined();}-JSValue js_textEditor_blur(JSContext*, JSValueConst, int, JSValueConst*) {+esjs::Val js_textEditor_blur(const esjs::Args&) {if (hostAlive() && host().platform) host().platform->textEditorBlur();- return JS_UNDEFINED;+ return esjs::undefined();}// es_textEditor_write(value, selectionStart, selectionEnd)-JSValue js_textEditor_write(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 3 || !hostAlive() || !host().platform) return JS_UNDEFINED;- host().platform->textEditorWrite(argString(ctx, argv[0]), argInt(ctx, argv[1]),- argInt(ctx, argv[2]));- return JS_UNDEFINED;+esjs::Val js_textEditor_write(const esjs::Args& a) {+ if (a.size() < 3 || !hostAlive() || !host().platform) return esjs::undefined();+ host().platform->textEditorWrite(argString(a[0]), argInt(a[1]),+ argInt(a[2]));+ return esjs::undefined();}/** The push as the SDK's `es_onNativeTextEditor` reads it. */-JSValue makePush(HostState& h, const EditorPush& item) {- JSValue obj = JS_NewObject(h.js);+esjs::Val makePush(const EditorPush& item) {+ esjs::Val obj = esjs::object();switch (item.kind) {case EditorPush::Kind::State:- JS_SetPropertyStr(h.js, obj, "kind", JS_NewString(h.js, "state"));- JS_SetPropertyStr(h.js, obj, "value", JS_NewString(h.js, item.value.c_str()));- JS_SetPropertyStr(h.js, obj, "selectionStart", JS_NewInt32(h.js, item.selectionStart));- JS_SetPropertyStr(h.js, obj, "selectionEnd", JS_NewInt32(h.js, item.selectionEnd));- JS_SetPropertyStr(h.js, obj, "composing", JS_NewBool(h.js, item.composing));+ esjs::set(obj, "kind", esjs::string("state"));+ esjs::set(obj, "value", esjs::string(item.value.c_str()));+ esjs::set(obj, "selectionStart", esjs::int32(item.selectionStart));+ esjs::set(obj, "selectionEnd", esjs::int32(item.selectionEnd));+ esjs::set(obj, "composing", esjs::boolean(item.composing));break;case EditorPush::Kind::Submit:- JS_SetPropertyStr(h.js, obj, "kind", JS_NewString(h.js, "submit"));+ esjs::set(obj, "kind", esjs::string("submit"));break;case EditorPush::Kind::Cancel:- JS_SetPropertyStr(h.js, obj, "kind", JS_NewString(h.js, "cancel"));+ esjs::set(obj, "kind", esjs::string("cancel"));break;}return obj;@@ -116,32 +105,27 @@ void drainTextEditor(HostState& h) {std::queue<EditorPush> pending;{ std::lock_guard<std::mutex> lk(g_mutex); pending.swap(g_queue); }if (pending.empty()) return;- jsEntry(h);-- JSValue global = JS_GetGlobalObject(h.js);- JSValue fn = JS_GetPropertyStr(h.js, global, "es_onNativeTextEditor");+ (void)h;+ esjs::Enter enter;+ const esjs::Val fn = esjs::get(esjs::global(), "es_onNativeTextEditor");while (!pending.empty()) {const EditorPush item = std::move(pending.front());pending.pop();- if (!JS_IsFunction(h.js, fn)) continue; // the SDK has not installed it (yet)- JSValue arg = makePush(h, item);- JSValue ret = JS_Call(h.js, fn, JS_UNDEFINED, 1, &arg);- if (JS_IsException(ret)) logJsError(h.js, "es_onNativeTextEditor");- JS_FreeValue(h.js, ret);- JS_FreeValue(h.js, arg);+ if (!esjs::isFunction(fn)) continue; // the SDK has not installed it (yet)+ esjs::Scope scope;+ const esjs::Val arg = makePush(item);+ esjs::call(fn, esjs::undefined(), 1, &arg, "es_onNativeTextEditor");}- JS_FreeValue(h.js, fn);- JS_FreeValue(h.js, global);}-void registerTextEditorBindings(HostState& h, JSValue global) {+void registerTextEditorBindings(HostState& h, esjs::Val global) {// Only when the platform has a keyboard: the SDK treats the entry points as// an all-or-nothing group, so a half-bound host has no surface at all rather// than one that opens a keyboard nobody reads.if (!h.platform || !h.platform->hasTextEditor()) return;- bindGlobal(h, global, "es_textEditor_focus", js_textEditor_focus, 6);- bindGlobal(h, global, "es_textEditor_blur", js_textEditor_blur, 0);- bindGlobal(h, global, "es_textEditor_write", js_textEditor_write, 3);+ bindGlobal(global, "es_textEditor_focus", js_textEditor_focus, 6);+ bindGlobal(global, "es_textEditor_blur", js_textEditor_blur, 0);+ bindGlobal(global, "es_textEditor_write", js_textEditor_write, 3);}// Thread-safe: the platform reports from its UI thread, the frame loop delivers.diff --git a/native/host/esn_shim.hpp b/native/host/esn_shim.hppindex 6a6e15dab..990264fbd 100644--- a/native/host/esn_shim.hpp+++ b/native/host/esn_shim.hpp@@ -6,9 +6,7 @@// each bound component's header — so the shim itself needs no component headers.#pragma once-extern "C" {-#include "quickjs.h"-}+#include "js/esjs.hpp" // the engine surface every binding is written against#include "esengine/ecs/Registry.hpp" // esengine::ecs::Registry + esengine::Entity#include "esengine/resource/ResourceManager.hpp" // esengine::resource::ResourceManager@@ -23,18 +21,18 @@ extern "C" {// a JS argument.esengine::ecs::Registry& esn_reg();esengine::resource::ResourceManager& esn_rm();-esengine::Entity esn_entity(JSContext* ctx, JSValueConst v);+esengine::Entity esn_entity(esjs::Val v);// Read obj[key] as a number into *out; returns true if present & numeric.-bool esn_getnum(JSContext* ctx, JSValueConst obj, const char* key, double* out);+bool esn_getnum(esjs::Val obj, const char* key, double* out);// Read obj[key] as a truthy int into *out; returns true if present.-bool esn_getbool(JSContext* ctx, JSValueConst obj, const char* key, int* out);+bool esn_getbool(esjs::Val obj, const char* key, int* out);// Read obj[key] as an array of n numbers into dst[0..n-1] (no-op if absent).-void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, int n);+void esn_getvec(esjs::Val obj, const char* key, float* dst, int n);// Wrap [ptr, ptr+size) as a zero-copy JS ArrayBuffer (native owns the memory).-JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size);+esjs::Val esn_arraybuffer(void* ptr, size_t size);// Read a JS byte source (ArrayBuffer, typed-array view, or plain number array)// into `out`.-void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out);+void esn_bytes(esjs::Val v, std::vector<esengine::u8>& out);// --- the heap a `uintptr_t` argument addresses (see host/heap.hpp) ------------// A generated wrapper reads such an argument through this pair, so the entry@@ -48,9 +46,9 @@ void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out);// that hand bytes straight across (the renderer's native backend).//// Returns 0 when there is nothing to pass, which every binding treats as null.-uint32_t esn_argOffset(JSContext* ctx, JSValueConst v);+uint32_t esn_argOffset(esjs::Val v);// Release what esn_argOffset copied in. A no-op when the argument was an offset.-void esn_argRelease(JSContext* ctx, JSValueConst v, uint32_t offset);+void esn_argRelease(esjs::Val v, uint32_t offset);// Resolve a heap offset to the real address a binding takes, or 0 if out of range.uintptr_t esn_heapAddr(uint32_t offset);@@ -69,5 +67,5 @@ uint32_t esn_publish(EsnSlot& slot, const void* src, size_t bytes);// Components (NativeBindings.generated.cpp) and the engine's binding entry// points (NativeFunctionBindings.generated.cpp), from the same declarations the// web build registers with embind.-void esn_register(JSContext* ctx, JSValue global);-void esn_register_functions(JSContext* ctx, JSValue global);+void esn_register(esjs::Val global);+void esn_register_functions(esjs::Val global);diff --git a/native/host/js/esjs.hpp b/native/host/js/esjs.hppnew file mode 100644index 000000000..0d0cbb00c--- /dev/null+++ b/native/host/js/esjs.hpp@@ -0,0 +1,261 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file esjs.hpp+ * @brief The JS engine the native host runs, behind one small surface.+ * @details Every binding the host has, hand-written or generated, is written+ * against this file and nothing else of the engine. One build carries one+ * engine, chosen when the host is built:+ *+ * * V8, where a JIT is allowed (desktop, Android): the SDK and the game+ * run compiled, as they do in a browser.+ * * QuickJS-ng, where it is not (iOS): an interpreter, small and fast to+ * start.+ *+ * The surface is what the bindings actually use — values, objects, arrays,+ * byte buffers, functions, calls — and the lifetime rule is V8's, because+ * it is the one that cannot be emulated the other way round:+ *+ * * A {@link Val} lives as long as the {@link Scope} it was made in. A+ * native function runs inside one, and so does every host entry+ * ({@link Enter}); nothing is freed by hand.+ * * A value kept past that — a timer's callback, a pending fetch's — is+ * held by a {@link Ref}.+ *+ * Every call here must happen inside an {@link Enter}.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include <cstddef>+#include <cstdint>+#include <string>+#include <string_view>+#include <vector>++namespace esjs {++// =============================================================================+// Values+// =============================================================================++/** A JS value, valid until the {@link Scope} that made it closes. The bits are the+ * engine's own handle; only the backend reads them. A default-constructed Val is+ * not a value: ask for {@link undefined} when you mean undefined. */+struct Val {+ alignas(8) unsigned char bits[16] = {};+};++/** A native function's arguments. Reading past the end gives undefined, as a JS+ * function reading a missing parameter does. */+class Args {+public:+ int size() const { return argc_; }+ Val operator[](int i) const;++ // Backend-internal: what the engine handed the trampoline.+ const void* impl_ = nullptr;+ int argc_ = 0;+};++/** A function JS can call. Return {@link undefined} for no value, or what a+ * `throw*` call returned to raise an exception. */+using NativeFn = Val (*)(const Args&);++Val undefined();+Val null();+Val boolean(bool v);+Val number(double v);+Val int32(int32_t v);+Val uint32(uint32_t v);+/** As a JS number: exact up to 2^53, which every id that crosses is. */+Val int64(int64_t v);+Val string(std::string_view utf8);+Val object();+Val array();+/** An ArrayBuffer holding a copy of the bytes. */+Val arrayBufferCopy(const void* data, size_t size);+/** An ArrayBuffer over memory the host owns and keeps alive for as long as JS can+ * reach it — the heap arena, a component's storage. Zero-copy; writes from JS+ * land in that memory. */+Val arrayBufferWrap(void* data, size_t size);++/** Raise a TypeError / Error in the calling JS. Return what these return. */+Val throwTypeError(const char* message);+Val throwError(const char* message);++bool isUndefined(Val v);+bool isNull(Val v);+inline bool isNullish(Val v) { return isUndefined(v) || isNull(v); }+bool isBool(Val v);+bool isNumber(Val v);+bool isString(Val v);+bool isFunction(Val v);+bool isObject(Val v);+bool isArray(Val v);++/** JS's own conversions (ToNumber, ToInt32, ToUint32, ToBoolean, ToString). A+ * conversion that throws (a Symbol, a throwing valueOf) answers 0 / false / "". */+double toNumber(Val v);+int32_t toInt32(Val v);+uint32_t toUint32(Val v);+int64_t toInt64(Val v);+bool toBool(Val v);+std::string toString(Val v);++/** A value's UTF-8, for the length of a statement: no copy on an engine whose+ * strings are already UTF-8. */+class Utf8 {+public:+ explicit Utf8(Val v);+ ~Utf8();+ Utf8(const Utf8&) = delete;+ Utf8& operator=(const Utf8&) = delete;+ const char* c_str() const { return data_ ? data_ : ""; }+ size_t size() const { return size_; }+ std::string_view view() const { return {c_str(), size_}; }+ explicit operator bool() const { return data_ != nullptr; }++private:+ const char* data_ = nullptr;+ size_t size_ = 0;+ std::string own_; ///< where an engine that must convert puts the bytes+};++/** The bytes behind an ArrayBuffer or any view of one (a typed array, a DataView):+ * the engine's own memory, writable, valid while the value is. False for anything+ * else. */+struct Bytes {+ uint8_t* data = nullptr;+ size_t size = 0;+};+bool bytesOf(Val v, Bytes* out);++// =============================================================================+// Objects+// =============================================================================++Val global();+/** `obj[key]`; undefined when absent, or when @p obj is not an object. */+Val get(Val obj, const char* key);+void set(Val obj, const char* key, Val value);+Val getAt(Val obj, uint32_t index);+void setAt(Val obj, uint32_t index, Val value);+/** `obj.length`, as a uint32 (0 when absent). */+uint32_t lengthOf(Val obj);+/** The object's own enumerable string keys, in JS order. */+std::vector<std::string> ownKeys(Val obj);+/** `obj[name] = <native function>`. */+void setFunction(Val obj, const char* name, NativeFn fn, int argc);++/**+ * `fn.call(self, ...argv)`. An exception is logged under @p where and answered+ * with false — every host entry treats a throwing callback the same way, so it is+ * done here once. @p result, when given, receives the return value.+ */+bool call(Val fn, Val self, int argc, const Val* argv, const char* where, Val* result = nullptr);++// =============================================================================+// Lifetimes+// =============================================================================++/** A region whose values are released when it closes. Native functions run in one+ * already; open one in a loop that makes many values per iteration. */+class Scope {+public:+ Scope();+ ~Scope();+ Scope(const Scope&) = delete;+ Scope& operator=(const Scope&) = delete;++private:+ alignas(16) unsigned char storage_[64];+};++/** A value kept past its scope. Move-only; releasing an empty Ref is a no-op, and+ * so is releasing one after the engine is gone (process exit). */+class Ref {+public:+ Ref() = default;+ explicit Ref(Val v);+ ~Ref();+ Ref(Ref&& o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; }+ Ref& operator=(Ref&& o) noexcept;+ Ref(const Ref&) = delete;+ Ref& operator=(const Ref&) = delete;++ Val get() const;+ void reset();+ explicit operator bool() const { return handle_ != nullptr; }++private:+ void* handle_ = nullptr;+};++// =============================================================================+// The engine+// =============================================================================++/** Where the engine's own messages go: an uncaught exception, a rejected cache. */+using Logger = void (*)(bool error, const char* message);++/** Bring the engine up: one runtime, one context, for the process. @p exePath is+ * where an engine that ships data files beside the binary looks for them. */+void init(Logger log, const char* exePath);+bool alive();++/** "V8 10.0.139.9", "QuickJS-ng 0.10.1" — for the boot record. */+std::string engineName();+/** Whether this engine compiles JS to machine code. */+bool hasJit();++/**+ * The host stepping into JS: from a frame, an input event, a drained callback.+ * Binds the engine to the calling thread (a platform may hand the next frame to a+ * different one — Android recreates its glue thread) and opens a {@link Scope}.+ * Nests freely.+ */+class Enter {+public:+ Enter();+ ~Enter();+ Enter(const Enter&) = delete;+ Enter& operator=(const Enter&) = delete;++private:+ alignas(16) unsigned char storage_[160];+};++/** Run what promises queued. app.tick() is async: its systems run here. */+void pumpMicrotasks();+/** Run the engine's own deferred work (a JIT's background compile results, idle+ * GC). A no-op for an engine that has none. */+void pumpEngine();++/** Evaluate a global script; an exception is logged under @p name. */+bool run(std::string_view source, const char* name);++/** How {@link runCached} treated the cache it was handed. */+enum class CacheUse { None, Used, Rejected };++/**+ * Evaluate a global script through a compile cache. @p cache (may be empty) is a+ * blob an earlier {@link runCached} produced for the SAME source on the SAME+ * engine build; one the engine declines is reported, with @p why, and the script+ * is compiled instead. @p fresh, when given and the cache was not used, receives a+ * new blob to store for next time.+ */+bool runCached(std::string_view source, const char* name,+ const uint8_t* cache, size_t cacheSize,+ CacheUse* use, std::string* why, std::vector<uint8_t>* fresh);++/** What a cache blob is called on disk, so caches from different engines (or+ * engine builds) never meet: "qjsbc", "v8cache". */+const char* cacheTag();++} // namespace esjsdiff --git a/native/host/js/esjs_quickjs.cpp b/native/host/js/esjs_quickjs.cppnew file mode 100644index 000000000..b530d2495--- /dev/null+++ b/native/host/js/esjs_quickjs.cpp@@ -0,0 +1,449 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file esjs_quickjs.cpp+ * @brief esjs over QuickJS-ng — the engine where no JIT is allowed (iOS).+ * @details QuickJS counts references and the surface counts scopes, so this file+ * is the bridge between the two: every value it hands out that holds a+ * reference is recorded on one stack of locals, and a closing scope (a+ * native function returning, an {@link Enter} ending) releases what was+ * recorded since it opened. A value written into an object or returned+ * to JS is duplicated first, so the scope's release never takes a+ * reference something else still holds.+ *+ * The JS thread is one thread at a time (Android may change WHICH one),+ * so the stack is a plain global.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "esjs.hpp"++extern "C" {+#include "quickjs.h"+}++#include <cstdlib>+#include <cstring>+#include <new>++namespace esjs {+namespace {++static_assert(sizeof(JSValue) <= sizeof(Val::bits), "a JSValue must fit a Val");++JSRuntime* g_rt = nullptr;+JSContext* g_ctx = nullptr;+Logger g_log = nullptr;+bool g_alive = false;+std::vector<JSValue> g_locals;++inline JSValue raw(Val v) {+ JSValue j;+ std::memcpy(&j, v.bits, sizeof(JSValue));+ return j;+}++inline Val borrowed(JSValue j) {+ Val v;+ std::memcpy(v.bits, &j, sizeof(JSValue));+ return v;+}++/** A value this file made (or was handed with a reference): released by the+ * enclosing scope. */+inline Val local(JSValue j) {+ if (JS_VALUE_HAS_REF_COUNT(j)) g_locals.push_back(j);+ return borrowed(j);+}++void releaseTo(size_t mark) {+ while (g_locals.size() > mark) {+ JSValue j = g_locals.back();+ g_locals.pop_back();+ JS_FreeValue(g_ctx, j);+ }+}++void say(bool error, const std::string& s) {+ if (g_log) g_log(error, s.c_str());+}++std::string describe(JSValueConst e) {+ std::string out;+ if (const char* s = JS_ToCString(g_ctx, e)) {+ out = s;+ JS_FreeCString(g_ctx, s);+ } else {+ JS_FreeValue(g_ctx, JS_GetException(g_ctx));+ out = "?";+ }+ return out;+}++/** Report the pending exception, with its stack: a bare message ("Maximum call+ * stack size exceeded") says nothing about which SDK path produced it. */+void reportException(const char* where) {+ JSValue e = JS_GetException(g_ctx);+ say(true, std::string("JS error in ") + where + ": " + describe(e));+ if (JS_IsObject(e)) {+ JSValue stack = JS_GetPropertyStr(g_ctx, e, "stack");+ if (JS_IsString(stack)) say(true, " stack: " + describe(stack));+ else if (JS_IsException(stack)) JS_FreeValue(g_ctx, JS_GetException(g_ctx));+ JS_FreeValue(g_ctx, stack);+ }+ JS_FreeValue(g_ctx, e);+}++/** Drop a pending exception a lenient read does not report. */+void clearException() {+ JS_FreeValue(g_ctx, JS_GetException(g_ctx));+}++/** A read that may throw (a getter): its exception becomes undefined. */+Val readOrUndefined(JSValue j) {+ if (JS_IsException(j)) {+ clearException();+ return borrowed(JS_UNDEFINED);+ }+ return local(j);+}++struct Frame {+ JSValueConst* argv;+};++JSValue trampoline(JSContext*, JSValueConst, int argc, JSValueConst* argv, int, void* opaque) {+ Frame frame{argv};+ Args args;+ args.impl_ = &frame;+ args.argc_ = argc;+ const size_t mark = g_locals.size();+ const Val r = reinterpret_cast<NativeFn>(opaque)(args);+ JSValue out = raw(r);+ if (!JS_IsException(out)) out = JS_DupValue(g_ctx, out); // survives the release below+ releaseTo(mark);+ return out;+}++struct ScopeState {+ size_t mark;+};+static_assert(sizeof(ScopeState) <= 64, "Scope storage");++} // namespace++// =============================================================================+// Values+// =============================================================================++Val Args::operator[](int i) const {+ if (i < 0 || i >= argc_) return borrowed(JS_UNDEFINED);+ return borrowed(static_cast<const Frame*>(impl_)->argv[i]);+}++Val undefined() { return borrowed(JS_UNDEFINED); }+Val null() { return borrowed(JS_NULL); }+Val boolean(bool v) { return borrowed(JS_NewBool(g_ctx, v)); }+Val number(double v) { return local(JS_NewFloat64(g_ctx, v)); }+Val int32(int32_t v) { return borrowed(JS_NewInt32(g_ctx, v)); }+Val uint32(uint32_t v) { return local(JS_NewUint32(g_ctx, v)); }+Val int64(int64_t v) { return local(JS_NewInt64(g_ctx, v)); }+Val string(std::string_view s) { return readOrUndefined(JS_NewStringLen(g_ctx, s.data(), s.size())); }+Val object() { return local(JS_NewObject(g_ctx)); }+Val array() { return local(JS_NewArray(g_ctx)); }++Val arrayBufferCopy(const void* data, size_t size) {+ return local(JS_NewArrayBufferCopy(g_ctx, static_cast<const uint8_t*>(data), size));+}++Val arrayBufferWrap(void* data, size_t size) {+ return local(JS_NewArrayBuffer(g_ctx, static_cast<uint8_t*>(data), size, nullptr, nullptr, false));+}++Val throwTypeError(const char* message) { return borrowed(JS_ThrowTypeError(g_ctx, "%s", message)); }+Val throwError(const char* message) { return borrowed(JS_ThrowInternalError(g_ctx, "%s", message)); }++bool isUndefined(Val v) { return JS_IsUndefined(raw(v)); }+bool isNull(Val v) { return JS_IsNull(raw(v)); }+bool isBool(Val v) { return JS_IsBool(raw(v)); }+bool isNumber(Val v) { return JS_IsNumber(raw(v)); }+bool isString(Val v) { return JS_IsString(raw(v)); }+bool isFunction(Val v) { return JS_IsFunction(g_ctx, raw(v)); }+bool isObject(Val v) { return JS_IsObject(raw(v)); }+bool isArray(Val v) { return JS_IsArray(raw(v)); }++double toNumber(Val v) {+ double d = 0;+ if (JS_ToFloat64(g_ctx, &d, raw(v)) < 0) { clearException(); return 0; }+ return d;+}+int32_t toInt32(Val v) {+ int32_t i = 0;+ if (JS_ToInt32(g_ctx, &i, raw(v)) < 0) { clearException(); return 0; }+ return i;+}+uint32_t toUint32(Val v) {+ uint32_t u = 0;+ if (JS_ToUint32(g_ctx, &u, raw(v)) < 0) { clearException(); return 0; }+ return u;+}+int64_t toInt64(Val v) {+ int64_t i = 0;+ if (JS_ToInt64(g_ctx, &i, raw(v)) < 0) { clearException(); return 0; }+ return i;+}+bool toBool(Val v) {+ const int b = JS_ToBool(g_ctx, raw(v));+ if (b < 0) { clearException(); return false; }+ return b != 0;+}+std::string toString(Val v) {+ Utf8 s(v);+ return std::string(s.view());+}++Utf8::Utf8(Val v) {+ size_t len = 0;+ data_ = JS_ToCStringLen(g_ctx, &len, raw(v));+ if (!data_) { clearException(); return; }+ size_ = len;+}++Utf8::~Utf8() {+ if (data_ && g_alive) JS_FreeCString(g_ctx, data_);+}++bool bytesOf(Val v, Bytes* out) {+ const JSValue j = raw(v);+ if (!JS_IsObject(j)) return false;+ if (JS_IsArrayBuffer(j)) {+ size_t size = 0;+ uint8_t* data = JS_GetArrayBuffer(g_ctx, &size, j);+ if (!data && size != 0) { clearException(); return false; }+ out->data = data;+ out->size = size;+ return true;+ }+ size_t offset = 0, length = 0, perElement = 0;+ JSValue buffer = JS_GetTypedArrayBuffer(g_ctx, j, &offset, &length, &perElement);+ if (JS_IsException(buffer)) { clearException(); return false; }+ size_t size = 0;+ uint8_t* base = JS_GetArrayBuffer(g_ctx, &size, buffer);+ JS_FreeValue(g_ctx, buffer); // the view keeps the buffer alive+ if (!base || offset + length > size) { if (!base) clearException(); return false; }+ out->data = base + offset;+ out->size = length;+ return true;+}++// =============================================================================+// Objects+// =============================================================================++Val global() { return local(JS_GetGlobalObject(g_ctx)); }++Val get(Val obj, const char* key) {+ if (!JS_IsObject(raw(obj))) return undefined();+ return readOrUndefined(JS_GetPropertyStr(g_ctx, raw(obj), key));+}++void set(Val obj, const char* key, Val value) {+ if (JS_SetPropertyStr(g_ctx, raw(obj), key, JS_DupValue(g_ctx, raw(value))) < 0) clearException();+}++Val getAt(Val obj, uint32_t index) {+ if (!JS_IsObject(raw(obj))) return undefined();+ return readOrUndefined(JS_GetPropertyUint32(g_ctx, raw(obj), index));+}++void setAt(Val obj, uint32_t index, Val value) {+ if (JS_SetPropertyUint32(g_ctx, raw(obj), index, JS_DupValue(g_ctx, raw(value))) < 0) clearException();+}++uint32_t lengthOf(Val obj) {+ const Val len = get(obj, "length");+ return isUndefined(len) ? 0 : toUint32(len);+}++std::vector<std::string> ownKeys(Val obj) {+ std::vector<std::string> keys;+ if (!JS_IsObject(raw(obj))) return keys;+ JSPropertyEnum* tab = nullptr;+ uint32_t len = 0;+ if (JS_GetOwnPropertyNames(g_ctx, &tab, &len, raw(obj), JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) != 0) {+ clearException();+ return keys;+ }+ keys.reserve(len);+ for (uint32_t i = 0; i < len; ++i) {+ if (const char* k = JS_AtomToCString(g_ctx, tab[i].atom)) {+ keys.emplace_back(k);+ JS_FreeCString(g_ctx, k);+ }+ }+ JS_FreePropertyEnum(g_ctx, tab, len);+ return keys;+}++void setFunction(Val obj, const char* name, NativeFn fn, int argc) {+ JSValue f = JS_NewCClosure(g_ctx, trampoline, name, nullptr, argc, 0, reinterpret_cast<void*>(fn));+ JS_SetPropertyStr(g_ctx, raw(obj), name, f);+}++bool call(Val fn, Val self, int argc, const Val* argv, const char* where, Val* result) {+ std::vector<JSValue> args(static_cast<size_t>(argc > 0 ? argc : 0));+ for (int i = 0; i < argc; ++i) args[static_cast<size_t>(i)] = raw(argv[i]);+ JSValue r = JS_Call(g_ctx, raw(fn), raw(self), argc, args.data());+ if (JS_IsException(r)) {+ reportException(where);+ if (result) *result = undefined();+ return false;+ }+ const Val out = local(r);+ if (result) *result = out;+ return true;+}++// =============================================================================+// Lifetimes+// =============================================================================++Scope::Scope() { new (storage_) ScopeState{g_locals.size()}; }+Scope::~Scope() { if (g_alive) releaseTo(reinterpret_cast<ScopeState*>(storage_)->mark); }++Ref::Ref(Val v) : handle_(new JSValue(JS_DupValue(g_ctx, raw(v)))) {}++Ref::~Ref() { reset(); }++Ref& Ref::operator=(Ref&& o) noexcept {+ if (this != &o) {+ reset();+ handle_ = o.handle_;+ o.handle_ = nullptr;+ }+ return *this;+}++Val Ref::get() const { return handle_ ? borrowed(*static_cast<JSValue*>(handle_)) : undefined(); }++void Ref::reset() {+ if (!handle_) return;+ auto* j = static_cast<JSValue*>(handle_);+ if (g_alive) JS_FreeValue(g_ctx, *j);+ delete j;+ handle_ = nullptr;+}++// =============================================================================+// The engine+// =============================================================================++void init(Logger log, const char*) {+ g_log = log;+ g_rt = JS_NewRuntime();+ g_ctx = JS_NewContext(g_rt);+ g_alive = true;+ // Process exit destroys the host's statics after this runs, and their Refs+ // must not reach a runtime the C library is tearing down.+ std::atexit([] { g_alive = false; });+}++bool alive() { return g_alive; }++std::string engineName() { return std::string("QuickJS-ng ") + JS_GetVersion(); }++bool hasJit() { return false; }++namespace {+struct EnterState {+ size_t mark;+};+static_assert(sizeof(EnterState) <= 160, "Enter storage");+} // namespace++// QuickJS detects JS stack overflow by comparing the C stack pointer against a top+// it records once, at JS_NewRuntime. The runtime outlives the thread that made it:+// on Android an activity recreate keeps the process but hands every later JS call+// to a NEW glue thread, whose stack ASLR may map below the recorded top — at which+// point every call, however flat, throws "Maximum call stack size exceeded"+// forever. Re-anchoring at each host entry is the API's own answer, and costs one+// stack-pointer read.+Enter::Enter() {+ JS_UpdateStackTop(g_rt);+ new (storage_) EnterState{g_locals.size()};+}++Enter::~Enter() {+ if (g_alive) releaseTo(reinterpret_cast<EnterState*>(storage_)->mark);+}++void pumpMicrotasks() {+ JSContext* c = nullptr;+ for (;;) {+ const int r = JS_ExecutePendingJob(g_rt, &c);+ if (r == 0) break;+ if (r < 0) reportException("promise job"); // the queue continues past it+ }+}++void pumpEngine() {}++bool run(std::string_view source, const char* name) {+ // JS_Eval reads a NUL-terminated buffer.+ const std::string src(source);+ JSValue r = JS_Eval(g_ctx, src.c_str(), src.size(), name, JS_EVAL_TYPE_GLOBAL);+ if (JS_IsException(r)) {+ reportException(name);+ return false;+ }+ JS_FreeValue(g_ctx, r);+ return true;+}++bool runCached(std::string_view source, const char* name, const uint8_t* cache, size_t cacheSize,+ CacheUse* use, std::string* why, std::vector<uint8_t>* fresh) {+ if (use) *use = CacheUse::None;+ JSValue fn = JS_UNDEFINED;+ if (cache && cacheSize) {+ fn = JS_ReadObject(g_ctx, cache, cacheSize, JS_READ_OBJ_BYTECODE);+ if (JS_IsException(fn)) {+ JSValue e = JS_GetException(g_ctx);+ if (why) *why = describe(e);+ JS_FreeValue(g_ctx, e);+ if (use) *use = CacheUse::Rejected;+ fn = JS_UNDEFINED;+ } else if (use) {+ *use = CacheUse::Used;+ }+ }+ if (JS_IsUndefined(fn)) {+ const std::string src(source);+ fn = JS_Eval(g_ctx, src.c_str(), src.size(), name, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);+ if (JS_IsException(fn)) {+ reportException(name);+ return false;+ }+ if (fresh) {+ size_t len = 0;+ if (uint8_t* bc = JS_WriteObject(g_ctx, &len, fn, JS_WRITE_OBJ_BYTECODE)) {+ fresh->assign(bc, bc + len);+ js_free(g_ctx, bc);+ }+ }+ }+ JSValue r = JS_EvalFunction(g_ctx, fn); // consumes fn+ if (JS_IsException(r)) {+ reportException(name);+ return false;+ }+ JS_FreeValue(g_ctx, r);+ return true;+}++const char* cacheTag() { return "qjsbc"; }++} // namespace esjsdiff --git a/native/host/js/esjs_v8.cpp b/native/host/js/esjs_v8.cppnew file mode 100644index 000000000..b56f334e6--- /dev/null+++ b/native/host/js/esjs_v8.cpp@@ -0,0 +1,537 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file esjs_v8.cpp+ * @brief esjs over V8 — the engine where a JIT is allowed (desktop, Android).+ * @details One isolate and one context for the process. What this file adds to+ * the plain embedding is what the host's contract asks for and V8 does+ * not assume:+ *+ * * Microtasks run when the host pumps them, not whenever a call+ * returns — app.tick() is async, and the frame loop decides when its+ * systems run (QuickJS's job queue has the same shape).+ * * The isolate is entered per host entry, under a Locker, because a+ * platform may hand the next frame to a different thread (Android+ * recreates its glue thread), and the stack limit follows the thread.+ * * A read that throws (a getter, a valueOf) answers a default, as the+ * QuickJS backend does: bindings read loosely-shaped SDK objects and+ * must not leave an exception pending behind a normal return.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "esjs.hpp"++#include <libplatform/libplatform.h>+#include <v8.h>++#include <cstdlib>+#include <cstring>+#include <memory>+#include <new>+#include <thread>++#if defined(ESJS_V8_ICU) && defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>+#endif++namespace esjs {+namespace {++static_assert(sizeof(v8::Local<v8::Value>) == sizeof(void*), "a Local is one pointer");++std::unique_ptr<v8::Platform> g_platform;+v8::ArrayBuffer::Allocator* g_allocator = nullptr;+v8::Isolate* g_iso = nullptr;+v8::Global<v8::Context> g_context;+Logger g_log = nullptr;+bool g_alive = false;+std::thread::id g_thread;++// A Val's bits: the Local's pointer, and a flag for "an exception is pending".+constexpr size_t kThrewByte = 8;++inline v8::Local<v8::Value> raw(Val v) {+ v8::Local<v8::Value> l;+ std::memcpy(static_cast<void*>(&l), v.bits, sizeof(l));+ return l;+}++inline Val wrap(v8::Local<v8::Value> l) {+ Val v;+ std::memcpy(v.bits, static_cast<const void*>(&l), sizeof(l));+ return v;+}++inline Val threw() {+ Val v;+ v.bits[kThrewByte] = 1;+ return v;+}++inline bool isThrew(Val v) { return v.bits[kThrewByte] != 0; }++inline v8::Local<v8::Context> ctx() { return g_context.Get(g_iso); }++void say(bool error, const std::string& s) {+ if (g_log) g_log(error, s.c_str());+}++std::string utf8Of(v8::Local<v8::Value> v) {+ if (v.IsEmpty()) return {};+ v8::String::Utf8Value s(g_iso, v);+ return *s ? std::string(*s, static_cast<size_t>(s.length())) : std::string("?");+}++/** Report what a TryCatch caught, with its stack: a bare message ("Maximum call+ * stack size exceeded") says nothing about which SDK path produced it. */+void report(v8::TryCatch& tc, const char* where) {+ if (!tc.HasCaught()) return;+ say(true, std::string("JS error in ") + where + ": " + utf8Of(tc.Exception()));+ v8::Local<v8::Value> stack;+ if (tc.StackTrace(ctx()).ToLocal(&stack) && stack->IsString()) {+ say(true, " stack: " + utf8Of(stack));+ }+}++/** An exception nothing caught — a microtask's, a promise job's. */+void onMessage(v8::Local<v8::Message> message, v8::Local<v8::Value> error) {+ std::string where = utf8Of(message->GetScriptResourceName());+ const int line = message->GetLineNumber(ctx()).FromMaybe(0);+ say(true, "JS error in " + (where.empty() ? std::string("promise job") : where) + ":"+ + std::to_string(line) + ": " + utf8Of(error));+ v8::Local<v8::Value> stack;+ if (error->IsObject() &&+ error.As<v8::Object>()->Get(ctx(), v8::String::NewFromUtf8Literal(g_iso, "stack")).ToLocal(&stack) &&+ stack->IsString()) {+ say(true, " stack: " + utf8Of(stack));+ }+}++v8::Local<v8::String> key(const char* k) {+ return v8::String::NewFromUtf8(g_iso, k, v8::NewStringType::kInternalized).ToLocalChecked();+}++void trampoline(const v8::FunctionCallbackInfo<v8::Value>& info) {+ const auto fn = reinterpret_cast<NativeFn>(info.Data().As<v8::External>()->Value());+ Args args;+ args.impl_ = &info;+ args.argc_ = info.Length();+ const Val r = fn(args);+ if (isThrew(r)) return; // the exception is already scheduled+ const v8::Local<v8::Value> out = raw(r);+ if (!out.IsEmpty()) info.GetReturnValue().Set(out);+}++/** Bind the isolate's stack limit to the calling thread when it changes: V8 takes+ * it from the thread that made the isolate, and a later thread's stack lies+ * somewhere else entirely. The budget is what a platform thread reliably has+ * below a host entry. */+void followThread() {+ const auto self = std::this_thread::get_id();+ if (self == g_thread) return;+ g_thread = self;+ constexpr uintptr_t kBudget = 768 * 1024;+ const uintptr_t here = reinterpret_cast<uintptr_t>(&self);+ if (here > kBudget) g_iso->SetStackLimit(here - kBudget);+}++struct EnterState {+ v8::Locker locker;+ v8::Isolate::Scope isolateScope;+ v8::HandleScope handles;+ v8::Context::Scope contextScope;+ explicit EnterState(v8::Isolate* iso)+ : locker(iso), isolateScope(iso), handles(iso), contextScope(g_context.Get(iso)) {}+};+static_assert(sizeof(EnterState) <= 160, "Enter storage");+static_assert(sizeof(v8::HandleScope) <= 64, "Scope storage");++} // namespace++// =============================================================================+// Values+// =============================================================================++Val Args::operator[](int i) const {+ const auto& info = *static_cast<const v8::FunctionCallbackInfo<v8::Value>*>(impl_);+ return wrap(info[i]); // undefined past Length()+}++Val undefined() { return wrap(v8::Undefined(g_iso)); }+Val null() { return wrap(v8::Null(g_iso)); }+Val boolean(bool v) { return wrap(v8::Boolean::New(g_iso, v)); }+Val number(double v) { return wrap(v8::Number::New(g_iso, v)); }+Val int32(int32_t v) { return wrap(v8::Integer::New(g_iso, v)); }+Val uint32(uint32_t v) { return wrap(v8::Integer::NewFromUnsigned(g_iso, v)); }+Val int64(int64_t v) { return wrap(v8::Number::New(g_iso, static_cast<double>(v))); }++Val string(std::string_view s) {+ v8::Local<v8::String> out;+ if (!v8::String::NewFromUtf8(g_iso, s.data(), v8::NewStringType::kNormal, static_cast<int>(s.size()))+ .ToLocal(&out)) {+ return undefined(); // longer than V8's string limit+ }+ return wrap(out);+}++Val object() { return wrap(v8::Object::New(g_iso)); }+Val array() { return wrap(v8::Array::New(g_iso)); }++Val arrayBufferCopy(const void* data, size_t size) {+ v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(g_iso, size);+ if (size) std::memcpy(ab->GetBackingStore()->Data(), data, size);+ return wrap(ab);+}++Val arrayBufferWrap(void* data, size_t size) {+ auto store = v8::ArrayBuffer::NewBackingStore(data, size, v8::BackingStore::EmptyDeleter, nullptr);+ return wrap(v8::ArrayBuffer::New(g_iso, std::move(store)));+}++Val throwTypeError(const char* message) {+ g_iso->ThrowException(v8::Exception::TypeError(key(message)));+ return threw();+}++Val throwError(const char* message) {+ g_iso->ThrowException(v8::Exception::Error(key(message)));+ return threw();+}++bool isUndefined(Val v) { return raw(v)->IsUndefined(); }+bool isNull(Val v) { return raw(v)->IsNull(); }+bool isBool(Val v) { return raw(v)->IsBoolean(); }+bool isNumber(Val v) { return raw(v)->IsNumber(); }+bool isString(Val v) { return raw(v)->IsString(); }+bool isFunction(Val v) { return raw(v)->IsFunction(); }+bool isObject(Val v) { return raw(v)->IsObject(); }+bool isArray(Val v) { return raw(v)->IsArray(); }++double toNumber(Val v) {+ const v8::Local<v8::Value> l = raw(v);+ if (l->IsNumber()) return l.As<v8::Number>()->Value();+ v8::TryCatch tc(g_iso);+ return l->NumberValue(ctx()).FromMaybe(0);+}++int32_t toInt32(Val v) {+ const v8::Local<v8::Value> l = raw(v);+ if (l->IsInt32()) return l.As<v8::Int32>()->Value();+ v8::TryCatch tc(g_iso);+ return l->Int32Value(ctx()).FromMaybe(0);+}++uint32_t toUint32(Val v) {+ const v8::Local<v8::Value> l = raw(v);+ if (l->IsUint32()) return l.As<v8::Uint32>()->Value();+ v8::TryCatch tc(g_iso);+ return l->Uint32Value(ctx()).FromMaybe(0);+}++int64_t toInt64(Val v) {+ const v8::Local<v8::Value> l = raw(v);+ if (l->IsInt32()) return l.As<v8::Int32>()->Value();+ v8::TryCatch tc(g_iso);+ return l->IntegerValue(ctx()).FromMaybe(0);+}++bool toBool(Val v) { return raw(v)->BooleanValue(g_iso); }++std::string toString(Val v) {+ Utf8 s(v);+ return std::string(s.view());+}++Utf8::Utf8(Val v) {+ v8::Local<v8::Value> l = raw(v);+ v8::Local<v8::String> s;+ if (l->IsString()) {+ s = l.As<v8::String>();+ } else {+ v8::TryCatch tc(g_iso);+ if (!l->ToString(ctx()).ToLocal(&s)) return;+ }+ own_.resize(static_cast<size_t>(s->Utf8Length(g_iso)));+ if (!own_.empty()) {+ s->WriteUtf8(g_iso, own_.data(), static_cast<int>(own_.size()), nullptr,+ v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8);+ }+ data_ = own_.c_str();+ size_ = own_.size();+}++Utf8::~Utf8() = default;++bool bytesOf(Val v, Bytes* out) {+ const v8::Local<v8::Value> l = raw(v);+ if (l->IsArrayBuffer()) {+ auto store = l.As<v8::ArrayBuffer>()->GetBackingStore();+ out->data = static_cast<uint8_t*>(store->Data());+ out->size = store->ByteLength();+ return true;+ }+ if (l->IsArrayBufferView()) {+ const auto view = l.As<v8::ArrayBufferView>();+ auto store = view->Buffer()->GetBackingStore();+ const size_t offset = view->ByteOffset(), length = view->ByteLength();+ if (offset + length > store->ByteLength()) return false;+ out->data = static_cast<uint8_t*>(store->Data()) + offset;+ out->size = length;+ return true;+ }+ return false;+}++// =============================================================================+// Objects+// =============================================================================++Val global() { return wrap(ctx()->Global()); }++Val get(Val obj, const char* k) {+ const v8::Local<v8::Value> o = raw(obj);+ if (!o->IsObject()) return undefined();+ v8::TryCatch tc(g_iso);+ v8::Local<v8::Value> out;+ if (!o.As<v8::Object>()->Get(ctx(), key(k)).ToLocal(&out)) return undefined();+ return wrap(out);+}++void set(Val obj, const char* k, Val value) {+ const v8::Local<v8::Value> o = raw(obj);+ if (!o->IsObject()) return;+ v8::TryCatch tc(g_iso);+ (void)o.As<v8::Object>()->Set(ctx(), key(k), raw(value));+}++Val getAt(Val obj, uint32_t index) {+ const v8::Local<v8::Value> o = raw(obj);+ if (!o->IsObject()) return undefined();+ v8::TryCatch tc(g_iso);+ v8::Local<v8::Value> out;+ if (!o.As<v8::Object>()->Get(ctx(), index).ToLocal(&out)) return undefined();+ return wrap(out);+}++void setAt(Val obj, uint32_t index, Val value) {+ const v8::Local<v8::Value> o = raw(obj);+ if (!o->IsObject()) return;+ v8::TryCatch tc(g_iso);+ (void)o.As<v8::Object>()->Set(ctx(), index, raw(value));+}++uint32_t lengthOf(Val obj) {+ const v8::Local<v8::Value> o = raw(obj);+ if (o->IsArray()) return o.As<v8::Array>()->Length();+ const Val len = get(obj, "length");+ return isUndefined(len) ? 0 : toUint32(len);+}++std::vector<std::string> ownKeys(Val obj) {+ std::vector<std::string> keys;+ const v8::Local<v8::Value> o = raw(obj);+ if (!o->IsObject()) return keys;+ v8::TryCatch tc(g_iso);+ v8::Local<v8::Array> names;+ if (!o.As<v8::Object>()+ ->GetOwnPropertyNames(ctx(), static_cast<v8::PropertyFilter>(+ v8::ONLY_ENUMERABLE | v8::SKIP_SYMBOLS))+ .ToLocal(&names)) {+ return keys;+ }+ const uint32_t n = names->Length();+ keys.reserve(n);+ for (uint32_t i = 0; i < n; ++i) {+ v8::Local<v8::Value> name;+ if (names->Get(ctx(), i).ToLocal(&name)) keys.push_back(utf8Of(name));+ }+ return keys;+}++void setFunction(Val obj, const char* name, NativeFn fn, int argc) {+ const v8::Local<v8::Value> o = raw(obj);+ if (!o->IsObject()) return;+ auto tmpl = v8::FunctionTemplate::New(g_iso, trampoline,+ v8::External::New(g_iso, reinterpret_cast<void*>(fn)),+ v8::Local<v8::Signature>(), argc,+ v8::ConstructorBehavior::kThrow);+ v8::Local<v8::Function> f;+ if (!tmpl->GetFunction(ctx()).ToLocal(&f)) return;+ f->SetName(key(name));+ (void)o.As<v8::Object>()->Set(ctx(), key(name), f);+}++bool call(Val fn, Val self, int argc, const Val* argv, const char* where, Val* result) {+ if (result) *result = undefined();+ const v8::Local<v8::Value> f = raw(fn);+ if (!f->IsFunction()) return false;+ std::vector<v8::Local<v8::Value>> args(static_cast<size_t>(argc > 0 ? argc : 0));+ for (int i = 0; i < argc; ++i) args[static_cast<size_t>(i)] = raw(argv[i]);+ v8::TryCatch tc(g_iso);+ v8::Local<v8::Value> out;+ if (!f.As<v8::Function>()->Call(ctx(), raw(self), argc, args.data()).ToLocal(&out)) {+ report(tc, where);+ return false;+ }+ if (result) *result = wrap(out);+ return true;+}++// =============================================================================+// Lifetimes+// =============================================================================++Scope::Scope() { ::new (storage_) v8::HandleScope(g_iso); } // :: — HandleScope hides operator new+Scope::~Scope() { reinterpret_cast<v8::HandleScope*>(storage_)->~HandleScope(); }++Ref::Ref(Val v) : handle_(new v8::Global<v8::Value>(g_iso, raw(v))) {}++Ref::~Ref() { reset(); }++Ref& Ref::operator=(Ref&& o) noexcept {+ if (this != &o) {+ reset();+ handle_ = o.handle_;+ o.handle_ = nullptr;+ }+ return *this;+}++Val Ref::get() const {+ if (!handle_) return undefined();+ return wrap(static_cast<v8::Global<v8::Value>*>(handle_)->Get(g_iso));+}++void Ref::reset() {+ if (!handle_) return;+ auto* g = static_cast<v8::Global<v8::Value>*>(handle_);+ if (g_alive) delete g; // after exit the isolate is not ours to touch; the OS reclaims it+ handle_ = nullptr;+}++// =============================================================================+// The engine+// =============================================================================++void init(Logger log, const char* exePath) {+ g_log = log;+#if defined(ESJS_V8_ICU)+ // A build with Intl reads its locale data from icudtl.dat beside the binary.+#if defined(_WIN32)+ char self[MAX_PATH] = {};+ if (!exePath && GetModuleFileNameA(nullptr, self, MAX_PATH)) exePath = self;+#endif+ if (!v8::V8::InitializeICUDefaultLocation(exePath ? exePath : "")) {+ say(true, "V8: icudtl.dat not found beside the executable — Intl will not work");+ }+#else+ (void)exePath;+#endif+ g_platform = v8::platform::NewDefaultPlatform();+ v8::V8::InitializePlatform(g_platform.get());+ v8::V8::Initialize();++ g_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();+ v8::Isolate::CreateParams params;+ params.array_buffer_allocator = g_allocator;+ g_iso = v8::Isolate::New(params);+ g_thread = std::this_thread::get_id();+ {+ v8::Locker locker(g_iso);+ v8::Isolate::Scope isolateScope(g_iso);+ v8::HandleScope handles(g_iso);+ g_iso->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);+ g_iso->AddMessageListener(onMessage);+ g_context.Reset(g_iso, v8::Context::New(g_iso));+ }+ g_alive = true;+ // Process exit destroys the host's statics after this runs, and their Refs+ // must not reach an isolate whose platform the C library is tearing down.+ std::atexit([] { g_alive = false; });+}++bool alive() { return g_alive; }++std::string engineName() { return std::string("V8 ") + v8::V8::GetVersion(); }++bool hasJit() { return true; }++Enter::Enter() {+ ::new (storage_) EnterState(g_iso);+ followThread();+}++Enter::~Enter() { reinterpret_cast<EnterState*>(storage_)->~EnterState(); }++void pumpMicrotasks() { g_iso->PerformMicrotaskCheckpoint(); }++void pumpEngine() {+ while (v8::platform::PumpMessageLoop(g_platform.get(), g_iso)) {+ }+}++namespace {++bool compileAndRun(std::string_view source, const char* name, v8::ScriptCompiler::CachedData* cache,+ CacheUse* use, std::vector<uint8_t>* fresh) {+ v8::TryCatch tc(g_iso);+ v8::Local<v8::String> code;+ if (!v8::String::NewFromUtf8(g_iso, source.data(), v8::NewStringType::kNormal,+ static_cast<int>(source.size()))+ .ToLocal(&code)) {+ say(true, std::string("JS error in ") + name + ": source too large");+ return false;+ }+ v8::ScriptOrigin origin(g_iso, key(name));+ v8::ScriptCompiler::Source src(code, origin, cache); // takes the cache+ const auto options = cache ? v8::ScriptCompiler::kConsumeCodeCache : v8::ScriptCompiler::kNoCompileOptions;+ v8::Local<v8::Script> script;+ if (!v8::ScriptCompiler::Compile(ctx(), &src, options).ToLocal(&script)) {+ report(tc, name);+ return false;+ }+ if (cache && use) *use = src.GetCachedData()->rejected ? CacheUse::Rejected : CacheUse::Used;+ v8::Local<v8::Value> result;+ if (!script->Run(ctx()).ToLocal(&result)) {+ report(tc, name);+ return false;+ }+ // After the run, so the functions the top level compiled are in the blob too.+ if (fresh && (!use || *use != CacheUse::Used)) {+ std::unique_ptr<v8::ScriptCompiler::CachedData> out(+ v8::ScriptCompiler::CreateCodeCache(script->GetUnboundScript()));+ if (out) fresh->assign(out->data, out->data + out->length);+ }+ return true;+}++} // namespace++bool run(std::string_view source, const char* name) {+ return compileAndRun(source, name, nullptr, nullptr, nullptr);+}++bool runCached(std::string_view source, const char* name, const uint8_t* cache, size_t cacheSize,+ CacheUse* use, std::string* why, std::vector<uint8_t>* fresh) {+ if (use) *use = CacheUse::None;+ v8::ScriptCompiler::CachedData* data = nullptr;+ if (cache && cacheSize) {+ data = new v8::ScriptCompiler::CachedData(cache, static_cast<int>(cacheSize),+ v8::ScriptCompiler::CachedData::BufferNotOwned);+ }+ const bool ok = compileAndRun(source, name, data, use, fresh);+ if (use && *use == CacheUse::Rejected && why) {+ *why = "built by a different V8 build, flag set or source";+ }+ return ok;+}++const char* cacheTag() { return "v8cache"; }++} // namespace esjsdiff --git a/native/host/media/native_audio.hpp b/native/host/media/native_audio.hppindex 4952f1d0a..06f6b5441 100644--- a/native/host/media/native_audio.hpp+++ b/native/host/media/native_audio.hpp@@ -74,7 +74,7 @@ public:/** Report every non-looping voice that ended on its own since the last call,* then free it. Runs on the game thread each frame — miniaudio's public API* is game-thread safe, so the notification reaches JS with no cross-thread- * hop into QuickJS. */+ * hop into the JS engine. */void pumpEnded(const std::function<void(int)>& onEnded);private:diff --git a/native/host/platform/desktop.cpp b/native/host/platform/desktop.cppindex b8066e191..54c80fff7 100644--- a/native/host/platform/desktop.cpp+++ b/native/host/platform/desktop.cpp@@ -562,6 +562,12 @@ int main(int argc, char** argv) {bool running = true;bool shown = false;+ // ESTELLA_HIDDEN_WINDOW=1: never show the window. The surface is bound and+ // every frame is drawn and presented exactly as in a visible run — the window+ // just never reaches the screen — so a bench, a shot or a conformance trace can+ // run on a desktop without putting an app in front of whoever is using it.+ const char* hiddenEnv = SDL_getenv("ESTELLA_HIDDEN_WINDOW");+ const bool keepHidden = hiddenEnv && hiddenEnv[0] == '1';// SDL reports mouse positions in window coordinates; the host contract is// surface pixels, as it is for touch.auto pixelScale = [&] { return SDL_GetWindowPixelDensity(window); };@@ -657,7 +663,7 @@ int main(int argc, char** argv) {// Shown once something has been drawn on it: sizing happens during// boot, and a window shown before that is a default-sized empty// rectangle that then jumps.- if (!shown) {+ if (!shown && !keepHidden) {shown = true;SDL_ShowWindow(window);// And in front: a game that opens behind the window it wasdiff --git a/pipeline/tests/native-template.test.ts b/pipeline/tests/native-template.test.tsindex 20f703875..465a22f28 100644--- a/pipeline/tests/native-template.test.ts+++ b/pipeline/tests/native-template.test.ts@@ -10,7 +10,7 @@// 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, readFileSync, existsSync } from 'node:fs';+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';@@ -357,6 +357,32 @@ describe('what a PUBLISHED template must carry', () => {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.diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 83423dffc..89e0e2b83 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -341,7 +341,7 @@ export interface NativeEngineApi {ui_isScreenDomain?(registry: unknown, entity: number): boolean;}-/** Build the API over a host scope (the QuickJS global object; a plain object+/** Build the API over a host scope (the native host global object; a plain object* in tests). A name the host did not bind simply stays absent. */export function createNativeEngineApi(scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,diff --git a/toolchain.manifest.json b/toolchain.manifest.jsonindex 55bf77d3f..7d6065959 100644--- a/toolchain.manifest.json+++ b/toolchain.manifest.json@@ -30,7 +30,7 @@},"native": {"$comment": [- "The two projects the native host links that are too large to vendor. PINNED, not",+ "The projects the native host links that are too large to vendor. PINNED, not","tracked: `--depth 1` of a moving branch makes a runtime template unreproducible, and","webgpu.h is a moving target. Not submodules either — Dawn fetches its own dependencies","with a script rather than submodules, so tracking it that way saves nobody the fetch",@@ -55,6 +55,33 @@],"repo": "https://github.com/libsdl-org/SDL","commit": "147a8ee32dbf9ac02f3794964490687b6bbda1bc"+ },+ "v8": {+ "$comment": [+ "The JIT the desktop and Android hosts run the SDK and the game on (iOS allows no",+ "JIT and keeps QuickJS). Prebuilt, because V8 builds only with Chromium's own",+ "toolchain and Android's only on Linux. ONE V8 version on both, so the embedding",+ "code (native/host/js/esjs_v8.cpp) is written once. Neither build enables V8's",+ "sandbox, which is what lets the host hand JS zero-copy views of engine memory.",+ "Archives are pinned by sha256: a template other people install has to rebuild",+ "from the same bytes."+ ],+ "version": "10.0.139.9",+ "windows": [+ {+ "url": "https://api.nuget.org/v3-flatcontainer/v8-v143-x64/10.0.139.9/v8-v143-x64.10.0.139.9.nupkg",+ "sha256": "4f72f76f6ab235d865732dab48e7b1c7b1640783a2ff9cfbcb1781435fd52e49"+ },+ {+ "url": "https://api.nuget.org/v3-flatcontainer/v8.redist-v143-x64/10.0.139.9/v8.redist-v143-x64.10.0.139.9.nupkg",+ "sha256": "342ea8d47039e56fbad2a52b4425f5e39f37fdb9ba1fe4e7251b899d8479507a"+ }+ ],+ "android": {+ "$comment": "v8-android-jit-nointl 11.1000.4 is V8 10.0.139.9 built for the NDK's libc++ (react-native's prebuilt).",+ "url": "https://registry.npmjs.org/v8-android-jit-nointl/-/v8-android-jit-nointl-11.1000.4.tgz",+ "sha256": "46870658adfe0f6eaa4819226af37a25663bd54599304dd7d7c91ed1089dae9e"+ }}},"cmake": {diff --git a/tools/eht/generators/native_bindings.py b/tools/eht/generators/native_bindings.pyindex 707d603b0..422bc2220 100644--- a/tools/eht/generators/native_bindings.py+++ b/tools/eht/generators/native_bindings.py@@ -1,10 +1,12 @@-"""Native (QuickJS) binding generator — the native sibling of the embind generator.+"""Native binding generator — the native sibling of the embind generator.-Emits, per ES_COMPONENT, QuickJS-callable member getters/setters for reflected+Emits, per ES_COMPONENT, script-callable member getters/setters for reflectedstrings, scalars, vectors and enums, plus compiler-validated zero-copy buffers and an``esn_register()`` that installs them as script globals. It consumes the SAMEparsed reflection (data.Component) as EmbindGenerator, so the web (embind) and-native (QuickJS) binding surfaces are generated from one source and cannot drift.+native binding surfaces are generated from one source and cannot drift. The+emitted code is written against the host's engine surface (esjs.hpp), so it is+the same whichever JS engine the host embeds.Opt-in: only emitted when ``python -m eht --native-output PATH`` is given, so thedefault EHT run (and the committed *.generated.* files it produces) is unchanged.@@ -50,52 +52,51 @@ class NativeBindingsGenerator:n = prop.namemembers = self._members(ct)if members:- lines = [' { JSValue v = JS_NewObject(ctx);']- lines += [f' JS_SetPropertyStr(ctx, v, "{m}", JS_NewFloat64(ctx, c->{n}.{m}));'+ lines = [' { const esjs::Val v = esjs::object();']+ lines += [f' esjs::set(v, "{m}", esjs::number(c->{n}.{m}));'for m in members]- return lines + [f' JS_SetPropertyStr(ctx, o, "{n}", v); }}']+ return lines + [f' esjs::set(o, "{n}", v); }}']if ct == 'std::string':- value = f'JS_NewStringLen(ctx, c->{n}.data(), c->{n}.size())'+ value = f'esjs::string(std::string_view(c->{n}.data(), c->{n}.size()))'elif ct == 'bool':- value = f'JS_NewBool(ctx, c->{n})'+ value = f'esjs::boolean(c->{n})'elif self.types.is_handle(ct):- value = f'JS_NewFloat64(ctx, c->{n}.id())'+ value = f'esjs::number(c->{n}.id())'elif ct == 'Entity':- value = f'JS_NewFloat64(ctx, static_cast<esengine::u32>(c->{n}))'+ value = f'esjs::number(static_cast<esengine::u32>(c->{n}))'elif ct in _FLOAT | _INT or self.types.is_enum(ct):- value = f'JS_NewFloat64(ctx, static_cast<double>(c->{n}))'+ value = f'esjs::number(static_cast<double>(c->{n}))'else:return []- return [f' JS_SetPropertyStr(ctx, o, "{n}", {value});']+ return [f' esjs::set(o, "{n}", {value});']def _field(self, prop) -> str:t = prop.cpp_typen = prop.namect = self.types.clean_type(t)if ct == 'std::string':- return (f' {{ JSValue v = JS_GetPropertyStr(ctx, o, "{n}"); '- 'if (!JS_IsUndefined(v)) { size_t len; const char* s = JS_ToCStringLen(ctx, &len, v); '- f'if (s) {{ c.{n}.assign(s, len); JS_FreeCString(ctx, s); }} }} '- 'JS_FreeValue(ctx, v); }')+ return (f' {{ const esjs::Val v = esjs::get(o, "{n}"); '+ 'if (!esjs::isUndefined(v)) { const esjs::Utf8 s(v); '+ f'if (s) c.{n}.assign(s.c_str(), s.size()); }} }}')if self._members(ct):- lines = [f' {{ JSValue v = JS_GetPropertyStr(ctx, o, "{n}");']- lines.append(' if (JS_IsObject(v)) {')+ lines = [f' {{ const esjs::Val v = esjs::get(o, "{n}");']+ lines.append(' if (esjs::isObject(v)) {')for i, m in enumerate(self._members(ct)):- lines.append(f' {{ double x; if (esn_getnum(ctx, v, JS_IsArray(v) ? "{i}" : "{m}", &x)) '+ lines.append(f' {{ double x; if (esn_getnum(v, esjs::isArray(v) ? "{i}" : "{m}", &x)) 'f'c.{n}.{m} = static_cast<decltype(c.{n}.{m})>(x); }}')- return '\n'.join(lines + [' } JS_FreeValue(ctx, v); }'])+ return '\n'.join(lines + [' } }'])if ct == 'bool':- return f' {{ int _b; if (esn_getbool(ctx, o, "{n}", &_b)) c.{n} = _b != 0; }}'+ return f' {{ int _b; if (esn_getbool(o, "{n}", &_b)) c.{n} = _b != 0; }}'if self.types.is_enum(t) or ct in _INT or ct == 'Entity':- return (f' {{ double _v; if (esn_getnum(ctx, o, "{n}", &_v)) '+ return (f' {{ double _v; if (esn_getnum(o, "{n}", &_v)) 'f'c.{n} = static_cast<decltype(c.{n})>(static_cast<long long>(_v)); }}')if ct in _FLOAT:- return (f' {{ double _v; if (esn_getnum(ctx, o, "{n}", &_v)) '+ return (f' {{ double _v; if (esn_getnum(o, "{n}", &_v)) 'f'c.{n} = static_cast<decltype(c.{n})>(_v); }}')if self.types.is_handle(t):# A resource handle (e.g. TextureHandle): the script passes the packed# id returned by a resource binding (es_createTexture); reconstruct it.- return (f' {{ double _v; if (esn_getnum(ctx, o, "{n}", &_v)) '+ return (f' {{ double _v; if (esn_getnum(o, "{n}", &_v)) 'f'c.{n} = decltype(c.{n})(static_cast<esengine::u32>(static_cast<long long>(_v))); }}')if self.types.is_struct_vector(ct):return f' // {n}: a list, carried by its own _set/_get pair'@@ -130,70 +131,64 @@ class NativeBindingsGenerator:def _list_binding(self, comp, full, prop, members) -> List[str]:get_name = f'es_{comp.name}_{prop.name}_get'set_name = f'es_{comp.name}_{prop.name}_set'- out = [f'static JSValue {get_name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',- ' JSValue arr = JS_NewArray(ctx);',- ' if (argc < 1) return arr;',- f' const auto* c = esn_reg().tryGet<{full}>(esn_entity(ctx, argv[0]));',+ out = [f'static esjs::Val {get_name}(const esjs::Args& a) {{',+ ' const esjs::Val arr = esjs::array();',+ ' if (a.size() < 1) return arr;',+ f' const auto* c = esn_reg().tryGet<{full}>(esn_entity(a[0]));',' if (!c) return arr;',' uint32_t i = 0;',f' for (const auto& v : c->{prop.name}) {{']if members:- out.append(' JSValue o = JS_NewObject(ctx);')+ out.append(' const esjs::Val o = esjs::object();')for m in members:- out.append(f' JS_SetPropertyStr(ctx, o, "{m}", JS_NewFloat64(ctx, v.{m}));')- out.append(' JS_SetPropertyUint32(ctx, arr, i++, o);')+ out.append(f' esjs::set(o, "{m}", esjs::number(v.{m}));')+ out.append(' esjs::setAt(arr, i++, o);')else:- out.append(' JS_SetPropertyUint32(ctx, arr, i++, JS_NewFloat64(ctx, v));')+ out.append(' esjs::setAt(arr, i++, esjs::number(v));')out += [' }',' return arr;','}',- f'static JSValue {set_name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',- ' if (argc < 2) return JS_UNDEFINED;',- f' auto& c = esn_reg().getOrEmplace<{full}>(esn_entity(ctx, argv[0]));',+ f'static esjs::Val {set_name}(const esjs::Args& a) {{',+ ' if (a.size() < 2) return esjs::undefined();',+ f' auto& c = esn_reg().getOrEmplace<{full}>(esn_entity(a[0]));',f' c.{prop.name}.clear();',- ' uint32_t len = 0;',- ' JSValue lenv = JS_GetPropertyStr(ctx, argv[1], "length");',- ' JS_ToUint32(ctx, &len, lenv);',- ' JS_FreeValue(ctx, lenv);',+ ' const uint32_t len = esjs::lengthOf(a[1]);',f' c.{prop.name}.reserve(len);',' for (uint32_t i = 0; i < len; ++i) {',- ' JSValue e = JS_GetPropertyUint32(ctx, argv[1], i);',- f' decltype(c.{prop.name})::value_type v{{}};',- ' double n = 0;']+ ' esjs::Scope scope;',+ ' const esjs::Val e = esjs::getAt(a[1], i);',+ f' decltype(c.{prop.name})::value_type v{{}};']if members:for m in members:- out += [f' {{ JSValue f = JS_GetPropertyStr(ctx, e, "{m}");',- f' if (JS_ToFloat64(ctx, &n, f) == 0) v.{m} = static_cast<decltype(v.{m})>(n);',- ' JS_FreeValue(ctx, f); }']+ out.append(f' v.{m} = static_cast<decltype(v.{m})>(esjs::toNumber(esjs::get(e, "{m}")));')else:- out += [' if (JS_ToFloat64(ctx, &n, e) == 0) v = static_cast<decltype(v)>(n);']+ out.append(' v = static_cast<decltype(v)>(esjs::toNumber(e));')out += [f' c.{prop.name}.push_back(v);',- ' JS_FreeValue(ctx, e);',' }',- ' return JS_UNDEFINED;',+ ' return esjs::undefined();','}']return outdef _component(self, comp: Component) -> List[str]:full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name# Per-field setter: es_set_<Component>(entityId, obj).- out = [f'static JSValue es_set_{comp.name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',- ' if (argc < 2) return JS_UNDEFINED;',- ' esengine::Entity e = esn_entity(ctx, argv[0]);',+ out = [f'static esjs::Val es_set_{comp.name}(const esjs::Args& a) {{',+ ' if (a.size() < 2) return esjs::undefined();',+ ' esengine::Entity e = esn_entity(a[0]);',f' auto& c = esn_reg().getOrEmplace<{full}>(e);',- ' JSValueConst o = argv[1];',+ ' const esjs::Val o = a[1];',' (void)c; (void)o;']for prop in comp.properties:if 'readonly' not in prop.annotations:out.append(self._field(prop))if comp.name in WRITE_HOOKS:out.append(f' {WRITE_HOOKS[comp.name]}')- out.append(' return JS_UNDEFINED;')+ out.append(' return esjs::undefined();')out.append('}')- out += [f'static JSValue es_get_{comp.name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',- ' JSValue o = JS_NewObject(ctx);',- ' if (argc < 1) return o;',- f' auto* c = esn_reg().tryGet<{full}>(esn_entity(ctx, argv[0]));',+ out += [f'static esjs::Val es_get_{comp.name}(const esjs::Args& a) {{',+ ' const esjs::Val o = esjs::object();',+ ' if (a.size() < 1) return o;',+ f' auto* c = esn_reg().tryGet<{full}>(esn_entity(a[0]));',' if (!c) return o;']read_hook = READ_HOOKS.get(comp.name)if read_hook:@@ -204,28 +199,28 @@ class NativeBindingsGenerator:# The buffer implementation is registered below only if the native# compiler proves trivial ownership and the actual wasm accessor offsets.# getOrEmplace so a first write (component add) also creates the component.- out.append(f'static JSValue es_{comp.name}_buffer(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')- out.append(' if (argc < 1) return JS_UNDEFINED;')- out.append(' esengine::Entity e = esn_entity(ctx, argv[0]);')+ out.append(f'static esjs::Val es_{comp.name}_buffer(const esjs::Args& a) {{')+ out.append(' if (a.size() < 1) return esjs::undefined();')+ out.append(' esengine::Entity e = esn_entity(a[0]);')out.append(f' auto& c = esn_reg().getOrEmplace<{full}>(e);')read_hook = READ_HOOKS.get(comp.name)if read_hook:out.append(f' c.{read_hook}(); // lazily derived fields, see READ_HOOKS')- out.append(f' return esn_arraybuffer(ctx, &c, sizeof({full}));')+ out.append(f' return esn_arraybuffer(&c, sizeof({full}));')out.append('}')# Lifecycle: the native siblings of the embind Registry's has/remove. With# the buffer (getOrEmplace = add) + ptrAccessors (fields), these complete the# component API the SDK's BuiltinBridge drives (getBuiltinMethods).- out.append(f'static JSValue es_{comp.name}_has(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')- out.append(' if (argc < 1) return JS_UNDEFINED;')- out.append(' esengine::Entity e = esn_entity(ctx, argv[0]);')- out.append(f' return JS_NewBool(ctx, esn_reg().has<{full}>(e));')+ out.append(f'static esjs::Val es_{comp.name}_has(const esjs::Args& a) {{')+ out.append(' if (a.size() < 1) return esjs::undefined();')+ out.append(' esengine::Entity e = esn_entity(a[0]);')+ out.append(f' return esjs::boolean(esn_reg().has<{full}>(e));')out.append('}')- out.append(f'static JSValue es_{comp.name}_remove(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')- out.append(' if (argc < 1) return JS_UNDEFINED;')- out.append(' esengine::Entity e = esn_entity(ctx, argv[0]);')+ out.append(f'static esjs::Val es_{comp.name}_remove(const esjs::Args& a) {{')+ out.append(' if (a.size() < 1) return esjs::undefined();')+ out.append(' esengine::Entity e = esn_entity(a[0]);')out.append(f' if (esn_reg().has<{full}>(e)) esn_reg().remove<{full}>(e);')- out.append(' return JS_UNDEFINED;')+ out.append(' return esjs::undefined();')out.append('}')for prop, members in self._list_fields(comp):out.extend(self._list_binding(comp, full, prop, members))@@ -235,7 +230,7 @@ class NativeBindingsGenerator:def generate(self) -> str:lines = ['// Auto-generated by EHT (native_bindings) — DO NOT EDIT.',- '// Native QuickJS sibling of WebBindings.generated.cpp — one reflection source.',+ '// Native sibling of WebBindings.generated.cpp — one reflection source.',f'#include "{self.shim_header}"','#include <type_traits>','#include <cstddef>',@@ -261,45 +256,38 @@ class NativeBindingsGenerator:for comp in components:lines.extend(self._component(comp))lines.extend([- 'static JSValue es_getBuiltinComponentNames(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {',- ' if (argc < 1) return JS_UNDEFINED;',- ' const auto e = esn_entity(ctx, argv[0]);',+ 'static esjs::Val es_getBuiltinComponentNames(const esjs::Args& a) {',+ ' if (a.size() < 1) return esjs::undefined();',+ ' const auto e = esn_entity(a[0]);',' std::string names;',])for comp in components:full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.namelines.append(f' if (esn_reg().has<{full}>(e)) {{ if (!names.empty()) names += "|"; names += "{comp.name}"; }}')lines.extend([- ' return JS_NewStringLen(ctx, names.data(), names.size());',+ ' return esjs::string(names);','}', '',])lines.extend([- 'static JSValue es_componentTypeId(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {',- ' if (argc < 1) return JS_NewInt32(ctx, -1);',- ' const char* raw = JS_ToCString(ctx, argv[0]);',- ' if (!raw) return JS_EXCEPTION;',- ' const std::string name(raw);',- ' JS_FreeCString(ctx, raw);',+ 'static esjs::Val es_componentTypeId(const esjs::Args& a) {',+ ' if (a.size() < 1) return esjs::int32(-1);',+ ' const std::string name = esjs::toString(a[0]);',])for comp in components:full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name- lines.append(f' if (name == "{comp.name}") return JS_NewInt64(ctx, esengine::componentTypeId<{full}>());')- lines.extend([' return JS_NewInt32(ctx, -1);', '}', ''])- lines.append('void esn_register(JSContext* ctx, JSValue global) {')- lines.append(' JS_SetPropertyStr(ctx, global, "es_componentTypeId", '- 'JS_NewCFunction(ctx, es_componentTypeId, "es_componentTypeId", 1));')- lines.append(' JS_SetPropertyStr(ctx, global, "es_getBuiltinComponentNames", '- 'JS_NewCFunction(ctx, es_getBuiltinComponentNames, "es_getBuiltinComponentNames", 1));')+ lines.append(f' if (name == "{comp.name}") return esjs::int64(esengine::componentTypeId<{full}>());')+ lines.extend([' return esjs::int32(-1);', '}', ''])+ lines.append('void esn_register(esjs::Val global) {')+ lines.append(' esjs::setFunction(global, "es_componentTypeId", es_componentTypeId, 1);')+ lines.append(' esjs::setFunction(global, "es_getBuiltinComponentNames", es_getBuiltinComponentNames, 1);')for comp in components:setter = f'es_set_{comp.name}'buffer = f'es_{comp.name}_buffer'has = f'es_{comp.name}_has'remove = f'es_{comp.name}_remove'- lines.append(f' JS_SetPropertyStr(ctx, global, "{setter}", '- f'JS_NewCFunction(ctx, {setter}, "{setter}", 2));')+ lines.append(f' esjs::setFunction(global, "{setter}", {setter}, 2);')getter = f'es_get_{comp.name}'- lines.append(f' JS_SetPropertyStr(ctx, global, "{getter}", '- f'JS_NewCFunction(ctx, {getter}, "{getter}", 1));')+ lines.append(f' esjs::setFunction(global, "{getter}", {getter}, 1);')# Expose the raw buffer ONLY when this compiler proves every accessed# offset matches wasm32 and no owned string/vector can be overwritten.full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name@@ -313,18 +301,14 @@ class NativeBindingsGenerator:checks += [f'offsetof(decltype({full}::{f["name"]}), {m["name"]}) == {m["offset"]}'for m in f.get('members', [])]lines.append(f' if constexpr ({" && ".join(checks)}) {{')- lines.append(f' JS_SetPropertyStr(ctx, global, "{buffer}", '- f'JS_NewCFunction(ctx, {buffer}, "{buffer}", 1));')+ lines.append(f' esjs::setFunction(global, "{buffer}", {buffer}, 1);')lines.append(' }')- lines.append(f' JS_SetPropertyStr(ctx, global, "{has}", '- f'JS_NewCFunction(ctx, {has}, "{has}", 1));')- lines.append(f' JS_SetPropertyStr(ctx, global, "{remove}", '- f'JS_NewCFunction(ctx, {remove}, "{remove}", 1));')+ lines.append(f' esjs::setFunction(global, "{has}", {has}, 1);')+ lines.append(f' esjs::setFunction(global, "{remove}", {remove}, 1);')for prop, _members in self._list_fields(comp):for fn, arity in ((f'es_{comp.name}_{prop.name}_get', 1),(f'es_{comp.name}_{prop.name}_set', 2)):- lines.append(f' JS_SetPropertyStr(ctx, global, "{fn}", '- f'JS_NewCFunction(ctx, {fn}, "{fn}", {arity}));')+ lines.append(f' esjs::setFunction(global, "{fn}", {fn}, {arity});')lines.append('}')lines.append('')return '\n'.join(lines)diff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.pyindex eb300101b..8dc0259d6 100644--- a/tools/eht/generators/native_functions.py+++ b/tools/eht/generators/native_functions.py@@ -1,4 +1,4 @@-"""Native (QuickJS) wrappers for the engine's binding ENTRY POINTS.+"""Native wrappers for the engine's binding ENTRY POINTS.The component half of the boundary has been generated from one reflection sourcefor a while (``native_bindings.py`` + ``embind.py``). The function half was not:@@ -9,8 +9,9 @@ drives (the frame, the UI layout, tilemaps, particles) worked on the web and hadto be rewritten in C++ to work on a device.This generator removes the second hand-written copy. It reads the declarations in-``bindings/*.hpp`` — the same ones embind registers — and emits a QuickJS wrapper-per function that marshals the arguments and calls it. The BODY is shared: the+``bindings/*.hpp`` — the same ones embind registers — and emits a wrapper per+function that marshals the arguments and calls it, written against the host's+engine surface (esjs.hpp) so it is the same whichever JS engine the host embeds. The BODY is shared: thebinding TU itself compiles natively (see cmake/ESEngineSources.cmake), so bothplatforms run the same implementation; only the registration differs.@@ -38,7 +39,7 @@ is what tells you which entry points still need a hand-written binding.import refrom typing import List, NamedTuple, Optional, Tuple-# What the wrapper can marshal, and how each maps to a QuickJS read.+# What the wrapper can marshal, and how each maps to a JS read._INT_TYPES = {'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64','int', 'int32_t', 'uint32_t', 'size_t', 'long'}_FLOAT_TYPES = {'f32', 'f64', 'float', 'double'}@@ -268,7 +269,7 @@ def _qualify(cpp_type: str) -> str:class NativeFunctionsGenerator:- """Emit ``es_<name>`` QuickJS wrappers for parsed binding declarations."""+ """Emit ``es_<name>`` native wrappers for parsed binding declarations."""def __init__(self, headers: List[Tuple[str, str]], shim_header: str = 'esn_shim.hpp'):# headers: (include path as the generated TU should spell it, source text)@@ -290,18 +291,15 @@ class NativeFunctionsGenerator:def _wrapper(self, fn: Function) -> List[str]:js_params = [p for p in fn.params if p.cpp_type not in _IMPLICIT_REFS]out = [f'#ifdef {g}' for g in fn.guards]- out.append(f'static JSValue {self._js_name(fn.name)}'- f'(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')+ out.append(f'static esjs::Val {self._js_name(fn.name)}(const esjs::Args& a) {{')if js_params:- out.append(f' if (argc < {len(js_params)}) return JS_UNDEFINED;')- out.append(' (void)argc; (void)argv;')+ out.append(f' if (a.size() < {len(js_params)}) return esjs::undefined();')+ out.append(' (void)a;')call_args: List[str] = []# (local, js argument index) per buffer argument, so a copied-in buffer is# released after the call — see esn_argRelease.ptr_releases: List[Tuple[str, int]] = []- # C-string arguments, freed after the call for the same reason.- cstr_frees: List[str] = []js_index = 0for param in fn.params:if param.cpp_type in _IMPLICIT_REFS:@@ -314,66 +312,60 @@ class NativeFunctionsGenerator:# buffer handed straight across is copied in and released after the# call. The binding's own BoundarySpan check runs either way, and# now against a real region.- out.append(f' const uint32_t {local}_off = esn_argOffset(ctx, argv[{js_index}]);')+ out.append(f' const uint32_t {local}_off = esn_argOffset(a[{js_index}]);')out.append(f' const uintptr_t {local} = esn_heapAddr({local}_off);')ptr_releases.append((local, js_index))elif param.cpp_type == _CSTR:# Owned by the wrapper for the duration of the call. A missing or# non-string argument reads as empty, matching how cwrap coerces one.- out.append(f' const char* {local}_c = JS_ToCString(ctx, argv[{js_index}]);')- out.append(f' const char* {local} = {local}_c ? {local}_c : "";')- cstr_frees.append(local)+ out.append(f' const esjs::Utf8 {local}_c(a[{js_index}]);')+ out.append(f' const char* {local} = {local}_c.c_str();')elif param.cpp_type == _STRING:# A JS string, owned by the wrapper for the call. An absent or# non-string argument reads as empty rather than aborting the call,# matching how embind coerces one.- out.append(f' const char* {local}_c = JS_ToCString(ctx, argv[{js_index}]);')- out.append(f' const std::string {local} = {local}_c ? {local}_c : "";')- out.append(f' if ({local}_c) JS_FreeCString(ctx, {local}_c);')+ out.append(f' const std::string {local} = esjs::toString(a[{js_index}]);')elif param.cpp_type in _BOOL_TYPES:- out.append(f' const bool {local} = JS_ToBool(ctx, argv[{js_index}]) != 0;')+ out.append(f' const bool {local} = esjs::toBool(a[{js_index}]);')elif param.cpp_type in _FLOAT_TYPES:cpp = _qualify(param.cpp_type)- out.append(f' double {local}_d = 0; JS_ToFloat64(ctx, &{local}_d, argv[{js_index}]);')- out.append(f' const {cpp} {local} = static_cast<{cpp}>({local}_d);')+ out.append(f' const {cpp} {local} = static_cast<{cpp}>(esjs::toNumber(a[{js_index}]));')else:cpp = _qualify(param.cpp_type)- out.append(f' int64_t {local}_i = 0; JS_ToInt64(ctx, &{local}_i, argv[{js_index}]);')- out.append(f' const {cpp} {local} = static_cast<{cpp}>({local}_i);')+ out.append(f' const {cpp} {local} = static_cast<{cpp}>(esjs::toInt64(a[{js_index}]));')call_args.append(local)js_index += 1scope = '' if fn.extern_c else 'esengine::'call = f'{scope}{fn.name}({", ".join(call_args)})'- releases = [f' esn_argRelease(ctx, argv[{index}], {local}_off);'+ releases = [f' esn_argRelease(a[{index}], {local}_off);'for local, index in ptr_releases]- releases += [f' if ({local}_c) JS_FreeCString(ctx, {local}_c);' for local in cstr_frees]if fn.ret == _VOID:out.append(f' {call};')out.extend(releases)- out.append(' return JS_UNDEFINED;')+ out.append(' return esjs::undefined();')else:# Hold the result, release the scratch, then convert — a wrapper must# not leak the copy on the returning paths.if fn.ret in _BOOL_TYPES:out.append(f' const bool result = {call};')out.extend(releases)- out.append(' return JS_NewBool(ctx, result);')+ out.append(' return esjs::boolean(result);')elif fn.ret in _FLOAT_TYPES:out.append(f' const double result = static_cast<double>({call});')out.extend(releases)- out.append(' return JS_NewFloat64(ctx, result);')+ out.append(' return esjs::number(result);')elif fn.ret == _STRING:out.append(f' const std::string result = {call};')out.extend(releases)- out.append(' return JS_NewStringLen(ctx, result.data(), result.size());')+ out.append(' return esjs::string(result);')elif fn.ret == _CSTR:# The module owns the storage (a static scratch string), so the value# is copied into a JS string here rather than published to the heap.# A null answers as empty, which is what UTF8ToString(0) reads as.out.append(f' const char* result = {call};')out.extend(releases)- out.append(' return JS_NewString(ctx, result ? result : "");')+ out.append(' return esjs::string(result ? result : "");')elif fn.ret == 'uintptr_t':# Module-owned memory: copy `@heapreturn` bytes into this entry# point's own heap slot and answer the offset, so the SDK reads the@@ -383,12 +375,12 @@ class NativeFunctionsGenerator:out.append(f' const uintptr_t src = {call};')out.append(f' const size_t bytes = static_cast<size_t>({fn.heap_return});')out.extend(releases)- out.append(' return JS_NewUint32(ctx, esn_publish(slot, '+ out.append(' return esjs::uint32(esn_publish(slot, ''reinterpret_cast<const void*>(src), bytes));')else:out.append(f' const int64_t result = static_cast<int64_t>({call});')out.extend(releases)- out.append(' return JS_NewInt64(ctx, result);')+ out.append(' return esjs::int64(result);')out.append('}')out.extend('#endif' for _ in fn.guards)out.append('')@@ -443,7 +435,7 @@ class NativeFunctionsGenerator:lines.append('}')lines.append('')lines.extend([- '/** Build the API over a host scope (the QuickJS global object; a plain object',+ '/** Build the API over a host scope (the native host global object; a plain object',' * in tests). A name the host did not bind simply stays absent. */','export function createNativeEngineApi(',' scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,',@@ -479,7 +471,7 @@ class NativeFunctionsGenerator:def generate(self) -> str:lines = ['// Auto-generated by EHT (native_functions) — DO NOT EDIT.',- '// QuickJS wrappers for the engine binding entry points embind also registers,',+ '// Native wrappers for the engine binding entry points embind also registers,','// from the SAME declarations. The bodies live in the binding TUs, which this','// build compiles too — one implementation, two registration layers.',f'#include "{self.shim_header}"',@@ -501,13 +493,12 @@ class NativeFunctionsGenerator:self.emitted.append(fn.name)lines.extend(self._wrapper(fn))- lines.append('void esn_register_functions(JSContext* ctx, JSValue global) {')+ lines.append('void esn_register_functions(esjs::Val global) {')for fn in sorted(functions, key=lambda f: f.name):js_arity = len([p for p in fn.params if p.cpp_type not in _IMPLICIT_REFS])lines.extend(f'#ifdef {g}' for g in fn.guards)js = self._js_name(fn.name)- lines.append(f' JS_SetPropertyStr(ctx, global, "{js}", '- f'JS_NewCFunction(ctx, {js}, "{js}", {js_arity}));')+ lines.append(f' esjs::setFunction(global, "{js}", {js}, {js_arity});')lines.extend('#endif' for _ in fn.guards)lines.append('}')lines.append('')diff --git a/tools/eht/test_native_layout.py b/tools/eht/test_native_layout.pyindex f21a2ca54..4cca4f114 100644--- a/tools/eht/test_native_layout.py+++ b/tools/eht/test_native_layout.py@@ -19,9 +19,12 @@ class NativeLayoutTests(unittest.TestCase):self.assertIn('std::is_trivially_copyable_v<esengine::ecs::Fixture>', code)self.assertIn('std::is_standard_layout_v<esengine::ecs::Fixture>', code)self.assertIn('offsetof(esengine::ecs::Fixture, speed) == 12', code)- self.assertIn('c.text.assign(s, len)', code)- self.assertIn('JS_NewStringLen(ctx, c->text.data(), c->text.size())', code)+ self.assertIn('c.text.assign(s.c_str(), s.size())', code)+ self.assertIn('esjs::string(std::string_view(c->text.data(), c->text.size()))', code)self.assertIn('es_get_Fixture', code)+ # Engine-neutral: the generated TU names no engine API.+ self.assertNotIn('JS_', code)+ self.assertNotIn('JSContext', code)def test_vector_following_scalar_is_guarded_and_members_use_names(self):code = self.generate([Property('path', 'std::vector<glm::vec2>'),@@ -29,7 +32,7 @@ class NativeLayoutTests(unittest.TestCase):self.assertIn('offsetof(esengine::ecs::Fixture, enabled) == 12', code)self.assertIn('es_Fixture_path_set', code)self.assertIn('c.rotation.w', code)- self.assertIn('JS_IsArray(v) ? "3" : "w"', code)+ self.assertIn('esjs::isArray(v) ? "3" : "w"', code)def test_member_path_respects_readonly_and_shared_transform_write_hook(self):code = NativeBindingsGenerator([Component('Transform', 'esengine::ecs', [diff --git a/tools/lib/nativeBytecode.mjs b/tools/lib/nativeBytecode.mjsindex 0d2d643b6..e6e9f7571 100644--- a/tools/lib/nativeBytecode.mjs+++ b/tools/lib/nativeBytecode.mjs@@ -1,15 +1,48 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';++/** The identity Runtime.cpp keys its compile caches by, and native/tools/mkbc.c+ * stores ahead of shipped bytecode: FNV-1a 64 of what the host compiles, which is+ * the bundle behind one leading newline (generateSdkBundle embeds it that way). */+export function bundleIdentity(bundle) {+ let hash = 1469598103934665603n;+ for (const byte of Buffer.concat([Buffer.from('\n'), Buffer.from(bundle)])) {+ hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 1099511628211n);+ }+ return hash;+}++/** The same identity, as the 16 hex digits a template manifest records. */+export function bundleIdentityHex(bundle) {+ return bundleIdentity(bundle).toString(16).padStart(16, '0');+}+/** Match the source identity already stored by native/tools/mkbc.c and checked* by native/host/Runtime.cpp. Artifact extraction and rebuilding an unchanged SDK* alter file times, but neither changes which SDK the bytecode contains. */export function bytecodeMatchesBundle(bytecode, bundle) {if (bytecode.length <= 8) return false;- // generateSdkBundle embeds one leading newline before the UTF-8 bundle.- let hash = 1469598103934665603n;- for (const byte of Buffer.concat([Buffer.from('\n'), Buffer.from(bundle)])) {- hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 1099511628211n);+ return bytecode.readBigUInt64LE(0) === bundleIdentity(bundle);+}++/**+ * Whether the host in @p templateDir embeds @p bundle — whichever engine it runs.+ * A template records the identity of the SDK it embeds (`sdkBundle` in+ * template.json); an older one is read off its QuickJS bytecode, which carries the+ * same identity. A V8 template has no bytecode, so without the manifest field+ * there is nothing to answer with.+ *+ * @returns {boolean | null} null when the template cannot say.+ */+export function templateEmbedsBundle(templateDir, bundle) {+ const manifest = path.join(templateDir, 'template.json');+ if (existsSync(manifest)) {+ const recorded = JSON.parse(readFileSync(manifest, 'utf8')).sdkBundle;+ if (typeof recorded === 'string') return recorded === bundleIdentityHex(bundle);}- return bytecode.readBigUInt64LE(0) === hash;+ const bytecode = path.join(templateDir, 'esengine.native.qjsbc');+ return existsSync(bytecode) ? bytecodeMatchesBundle(readFileSync(bytecode), bundle) : null;}diff --git a/tools/tests/native-bytecode.test.ts b/tools/tests/native-bytecode.test.tsindex 0d4b892e4..094262549 100644--- a/tools/tests/native-bytecode.test.ts+++ b/tools/tests/native-bytecode.test.ts@@ -1,7 +1,10 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, expect, it } from 'vitest';-import { bytecodeMatchesBundle } from '../lib/nativeBytecode.mjs';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { bundleIdentityHex, bytecodeMatchesBundle, templateEmbedsBundle } from '../lib/nativeBytecode.mjs';describe('native bytecode source identity', () => {// mkbc's 64-bit source header for the newline-prefixed UTF-8 bundle below.@@ -18,3 +21,30 @@ describe('native bytecode source identity', () => {expect(bytecodeMatchesBundle(corrupt, bundle)).toBe(false);});});++describe('which SDK a template embeds, whichever engine it runs', () => {+ const bundle = Buffer.from('globalThis.ESEngine = {};');+ let dir: string | null = null;+ afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = null; });+ const template = (files: Record<string, string | Buffer>) => {+ dir = mkdtempSync(path.join(tmpdir(), 'es-embeds-'));+ for (const [name, body] of Object.entries(files)) writeFileSync(path.join(dir, name), body);+ return dir;+ };++ it('is the identity the bytecode header carries', () => {+ expect(bundleIdentityHex(bundle)).toBe('b8967e9155f7fe4e');+ });+ it('reads a V8 template off its manifest, which has no bytecode to read', () => {+ const at = template({ 'template.json': JSON.stringify({ jsEngine: 'v8', sdkBundle: bundleIdentityHex(bundle) }) });+ expect(templateEmbedsBundle(at, bundle)).toBe(true);+ expect(templateEmbedsBundle(at, Buffer.from('globalThis.ESEngine = {changed: true};'))).toBe(false);+ });+ it('falls back to the bytecode of a template that predates the manifest field', () => {+ const at = template({ 'template.json': '{}', 'esengine.native.qjsbc': Buffer.from('4efef755917e96b8010203', 'hex') });+ expect(templateEmbedsBundle(at, bundle)).toBe(true);+ });+ it('cannot say for a template with neither', () => {+ expect(templateEmbedsBundle(template({ 'template.json': '{}' }), bundle)).toBeNull();+ });+});diff --git a/tools/verify-aot-native.mjs b/tools/verify-aot-native.mjsindex 83845b762..df6f47d26 100644--- a/tools/verify-aot-native.mjs+++ b/tools/verify-aot-native.mjs@@ -80,6 +80,8 @@ try {cwd: path.dirname(exe),env: {...process.env,+ // Drawn and presented as in a visible run, never put on the screen.+ ESTELLA_HIDDEN_WINDOW: process.env.ESTELLA_HIDDEN_WINDOW ?? '1',ESTELLA_SHOT: path.join(out, 'frame.raw'),ESTELLA_SHOT_FRAME: SHOT_FRAME,ESTELLA_SHOT_QUIT: '1',diff --git a/tools/verify-desktop-render.mjs b/tools/verify-desktop-render.mjsindex 13b44918a..07e652c78 100644--- a/tools/verify-desktop-render.mjs+++ b/tools/verify-desktop-render.mjs@@ -106,7 +106,7 @@ function packageAndRun(project, templateDir, work) {// to itself passes here and fails on their machine.const run = spawnSync(exe, [], {cwd: ROOT,- env: { ...process.env, ESTELLA_SHOT: path.join(out, 'frame.raw'), ESTELLA_SHOT_FRAME: String(SHOT_FRAME), ESTELLA_SHOT_QUIT: '1' },+ env: { ...process.env, ESTELLA_HIDDEN_WINDOW: process.env.ESTELLA_HIDDEN_WINDOW ?? '1', ESTELLA_SHOT: path.join(out, 'frame.raw'), ESTELLA_SHOT_FRAME: String(SHOT_FRAME), ESTELLA_SHOT_QUIT: '1' },encoding: 'utf8',timeout: 120_000,});diff --git a/tools/verify-native-conformance.mjs b/tools/verify-native-conformance.mjsindex cfa44dabe..8ddd9ea06 100644--- a/tools/verify-native-conformance.mjs+++ b/tools/verify-native-conformance.mjs@@ -6,7 +6,7 @@* The suite compares closures against a wasm module, and `test_aot_conformance`* compares the emitted C against the same answer. Both run in a test process.* Neither says what a PLAYER gets: a packaged game, on the host that embeds- * QuickJS and the engine, stepping frames the way a frame is stepped.+ * its JS engine and the engine, stepping frames the way a frame is stepped.** So the fixture ships as a project and runs twice on this machine's runtime* template — interpreted, and with its systems compiled — printing what the two@@ -29,7 +29,7 @@ import { fileURLToPath } from 'node:url';import { installedTemplateDir } from '../build-tools/utils/nativeTemplate.js';import { desktopExecutableIn } from '../build-tools/utils/desktopApp.js';import { requireNativeHostSuccess } from './lib/nativeHostResult.mjs';-import { bytecodeMatchesBundle } from './lib/nativeBytecode.mjs';+import { templateEmbedsBundle } from './lib/nativeBytecode.mjs';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const PROJECT = path.join(ROOT, 'fixtures', 'aot-conformance');@@ -45,7 +45,9 @@ const version = JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8')const os = process.platform === 'darwin' ? 'macos': process.platform === 'win32' ? 'windows' : 'linux';-const template = installedTemplateDir(version, os);+// NATIVE_TEMPLATE checks a template that is not the installed one — how a second+// build of the host (the interpreter one, which iOS ships) is held to the trace too.+const template = process.env.NATIVE_TEMPLATE || installedTemplateDir(version, os);if (!template || !existsSync(template)) {// 2, not 0: a machine that cannot answer has not answered, and a criterion// that reads as met on every runner without a template says nothing anywhere.@@ -70,16 +72,16 @@ function newestSource(dir) {return newest;}-// The template EMBEDS the SDK as QuickJS bytecode, so a template built before an-// SDK edit runs the previous engine and answers for it — green on a defect the-// run was started to find. Exactly that happened while sabotaging markChanged_.-const bytecode = path.join(template, 'esengine.native.qjsbc');+// The template EMBEDS the SDK, so a template built before an SDK edit runs the+// previous engine and answers for it — green on a defect the run was started to+// find. Exactly that happened while sabotaging markChanged_.const bundle = path.join(ROOT, 'sdk', 'dist', 'index.native.bundled.js');-const stale = !existsSync(bytecode) || !existsSync(bundle)- ? { why: 'SDK bundle or template bytecode is missing', fix: `pnpm --filter ./sdk build && node build-tools/cli.js native --target ${os}` }+const embeds = existsSync(bundle) ? templateEmbedsBundle(template, readFileSync(bundle)) : null;+const stale = embeds === null+ ? { why: 'SDK bundle, or the template record of the SDK it embeds, is missing', fix: `pnpm --filter ./sdk build && node build-tools/cli.js native --target ${os}` }: newestSource(path.join(ROOT, 'sdk', 'src')) > statSync(bundle).mtimeMs? { why: 'sdk/dist is older than sdk/src', fix: 'pnpm --filter ./sdk build' }- : !bytecodeMatchesBundle(readFileSync(bytecode), readFileSync(bundle))+ : !embeds? { why: `the ${os} template embeds a different SDK from sdk/dist`,fix: `node build-tools/cli.js native --target ${os}` }: null;@@ -132,6 +134,8 @@ function play(compiled) {ESTELLA_BENCH_DT: String(want.delta),ESTELLA_BENCH_QUIT: '1',ESTELLA_BENCH_LABEL: compiled ? 'conformance-aot' : 'conformance-interpreted',+ // Drawn as in a visible run, never put on the screen.+ ESTELLA_HIDDEN_WINDOW: process.env.ESTELLA_HIDDEN_WINDOW ?? '1',},});requireNativeHostSuccess(run, compiled ? 'compiled conformance' : 'interpreted conformance');