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
fix(native): a save and a cache are not the same directory
esenginea1213ad40b55
diff --git a/docs/astro/src/content/docs/guides/save.mdx b/docs/astro/src/content/docs/guides/save.mdxindex 5f39278b8..e337a054d 100644--- a/docs/astro/src/content/docs/guides/save.mdx+++ b/docs/astro/src/content/docs/guides/save.mdx@@ -94,6 +94,30 @@ backend.limit (a few MB in browsers). Keep saves to game state — not bulk assets.</Aside>+## Where it actually lands++There is no directory to open, and that is deliberate: the web and the mini-game+platforms have no path namespace to hand you, so a `getSaveDirectory()` would be+a function only two of five platforms could answer, and every game calling it+would grow a branch per platform. `Storage` is the portable answer — write through+it and each platform's durable store is used for you.++| Platform | Backing store |+| --- | --- |+| Web | `localStorage` |+| WeChat / mini-games | `wx.setStorageSync` and friends |+| iOS | `Application Support/estella-storage.json` |+| Android | `files/estella-storage.json` (the app's internal data dir) |+| Node | memory only — it does not outlive the process |++On iOS this is Application Support rather than Caches on purpose — iOS empties+Caches whenever it wants the space back, so a save kept there is one the player+can lose. Both mobile directories are private to the app and included in the+device backup a player restores a new phone from.++`platformReadFile()` is **not** a way to reach these. It reads files packaged+*into* the build (the APK's `assets/`, the iOS app bundle) and is read-only.+## See also- [Scenes](/docs/guides/scene/) — loading and switching the scenes a save points at.diff --git a/docs/astro/src/content/docs/zh-cn/guides/save.mdx b/docs/astro/src/content/docs/zh-cn/guides/save.mdxindex 61757709a..b18af46b1 100644--- a/docs/astro/src/content/docs/zh-cn/guides/save.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/save.mdx@@ -87,6 +87,28 @@ Storage.has('keybinds'); // true游戏状态——不要放大块资源。</Aside>+## 实际存在哪里++没有目录可以打开,这是刻意的:Web 和小游戏平台根本没有路径命名空间可给,所以+`getSaveDirectory()` 会是一个五个平台里只有两个答得上来的函数,而每个调用它的游戏+都会因此长出逐平台分支。`Storage` 就是可移植的答案——写进去,各平台的耐久存储会被+替你选好。++| 平台 | 后端存储 |+| --- | --- |+| Web | `localStorage` |+| 微信 / 小游戏 | `wx.setStorageSync` 等 |+| iOS | `Application Support/estella-storage.json` |+| Android | `files/estella-storage.json`(应用内部数据目录) |+| Node | 仅内存——不跨进程存活 |++iOS 上用的是 Application Support 而不是 Caches,这是有意为之——iOS 想要回空间时随时+会清空 Caches,存在那里的存档玩家可能凭空丢失。两个移动平台的目录都是应用私有的,并且+会进入玩家换新手机时恢复的设备备份。++`platformReadFile()` **不是**读它们的途径。它读的是**打包进**构建产物里的文件+(APK 的 `assets/`、iOS 的 app bundle),且只读。+## 参见- [场景](/docs/zh-cn/guides/scene/) —— 加载与切换存档所指向的场景。diff --git a/native/host/Host.hpp b/native/host/Host.hppindex 7ae91accb..86e8f0a4d 100644--- a/native/host/Host.hpp+++ b/native/host/Host.hpp@@ -93,9 +93,27 @@ struct Platform {* app bundle on iOS. Empty when missing. Backs NativeBridge.readFile. */virtual std::vector<esengine::u8> readAsset(const char* path) = 0;- /** Writable private directory for the SDK bytecode cache; empty disables it. */+ /**+ * Writable private directory for things the host can REGENERATE — the SDK+ * bytecode cache, downloaded hot-update content. Empty disables it.+ *+ * The platform is free to delete this whenever it wants the space back, and+ * iOS does. Nothing a player would notice losing belongs here; that is+ * {@link dataDir}, and the split exists because the two were once one+ * directory whose durability quietly differed per platform.+ */virtual std::string cacheDir() = 0;+ /**+ * Writable private directory that SURVIVES — saves, settings, progress.+ *+ * Distinct from {@link cacheDir} in exactly one way that matters: the+ * platform will not reclaim it, and it is included in the device backup a+ * player restores a new phone from. Empty means this platform cannot promise+ * that, and storage falls back to lasting only for the session.+ */+ virtual std::string dataDir() = 0;+/*** Writable directory a PLAYER can reach — where the boot record goes.*diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cppindex e69a2c4d9..0540c72da 100644--- a/native/host/Runtime.cpp+++ b/native/host/Runtime.cpp@@ -52,6 +52,7 @@ void createHost(Platform& platform) {g_host = &state;state.platform = &platform;state.cacheDir = platform.cacheDir();+ state.dataDir = platform.dataDir();}void hostLog(bool error, const char* fmt, ...) {diff --git a/native/host/Runtime.hpp b/native/host/Runtime.hppindex 8fb38e3e5..7d5a89f6a 100644--- a/native/host/Runtime.hpp+++ b/native/host/Runtime.hpp@@ -70,7 +70,8 @@ struct HostState {int nextFetchId = 1;AudioEngine audio; ///< native sound (miniaudio); silent if no device- std::string cacheDir; ///< app private dir — SDK bytecode cache + asset cache+ std::string cacheDir; ///< reclaimable — SDK bytecode cache + hot-update content+ std::string dataDir; ///< durable — saves and settings; survives what cacheDir does notesengine::f32 w = 0, h = 0;bool ready = false; ///< engine + JS booted oncediff --git a/native/host/bindings/AssetBindings.cpp b/native/host/bindings/AssetBindings.cppindex ecc157d50..773b1bd14 100644--- a/native/host/bindings/AssetBindings.cpp+++ b/native/host/bindings/AssetBindings.cpp@@ -2,13 +2,14 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file AssetBindings.cpp- * @brief Packaged files, image decode, the writable cache, and UTF-8 decoding.+ * @brief Packaged files, image decode, the writable stores, and UTF-8 decoding.* @details What the SDK's platform layer reads a game off the device with. The* decode path is "Path 2" — the host decodes an image to RGBA and the* native ResourceManager uploads the bytes — because there is no- * offscreen DOM canvas here. The cache is the hot-update offline store:- * content-addressed keys written after verification, so a returning- * player boots updated content with no network.+ * offscreen DOM canvas here. There are two writable stores, and which+ * one a caller picks is a statement about what may be lost: the cache+ * is the hot-update offline store, content-addressed and refetchable,+ * while data holds what a player would notice gone.** @author ESEngine Team* @date 2026@@ -60,25 +61,19 @@ JSValue js_loadImagePixels(JSContext* ctx, JSValueConst, int, JSValueConst* argvreturn obj;}-// The host's writable store, under Platform::cacheDir(). Backs both the-// hot-update offline cache and (through it) key-value storage. Keys are-// content hashes or plain names; anything else is refused rather than escaping-// the directory.-std::string cachePathFor(const char* key) {- if (!key || !*key || host().cacheDir.empty()) return {};+// A file in one of the host's two writable directories. Keys are content hashes+// or plain names; anything else is refused rather than escaping the directory.+std::string pathIn(const std::string& dir, const char* key) {+ if (!key || !*key || dir.empty()) return {};for (const char* c = key; *c; ++c) {const bool ok = (*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z')|| (*c >= '0' && *c <= '9') || *c == '.' || *c == '_' || *c == '-';if (!ok) return {};}- return host().cacheDir + "/" + key;+ return dir + "/" + key;}-// es_readCacheFile(key) -> ArrayBuffer | null.-JSValue js_readCacheFile(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- const char* key = JS_ToCString(ctx, argv[0]);- const std::string path = cachePathFor(key);- if (key) JS_FreeCString(ctx, key);+JSValue readFileAt(JSContext* ctx, const std::string& path) {if (path.empty()) return JS_NULL;FILE* f = fopen(path.c_str(), "rb");if (!f) return JS_NULL;@@ -92,29 +87,67 @@ JSValue js_readCacheFile(JSContext* ctx, JSValueConst, int, JSValueConst* argv)return JS_NewArrayBufferCopy(ctx, bytes.data(), bytes.size());}-// es_writeCacheFile(key, ArrayBuffer | TypedArray | string) -> bool. A string is-// written as UTF-8, so script-side JSON needs no TextEncoder.-JSValue js_writeCacheFile(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {- if (argc < 2) return JS_FALSE;- const char* key = JS_ToCString(ctx, argv[0]);- const std::string path = cachePathFor(key);- if (key) JS_FreeCString(ctx, key);+// 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;std::vector<u8> bytes;- if (JS_IsString(argv[1])) {+ if (JS_IsString(source)) {size_t len = 0;- if (const char* text = JS_ToCStringLen(ctx, &len, argv[1])) {+ if (const char* text = JS_ToCStringLen(ctx, &len, source)) {bytes.assign(text, text + len);JS_FreeCString(ctx, text);}} else {- readByteSource(ctx, argv[1], bytes);+ readByteSource(ctx, source, bytes);}- FILE* f = fopen(path.c_str(), "wb");+ // 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;- const bool ok = bytes.empty() || fwrite(bytes.data(), 1, bytes.size(), f) == bytes.size();+ const bool wrote = bytes.empty() || fwrite(bytes.data(), 1, bytes.size(), f) == bytes.size();+ const bool flushed = wrote && fflush(f) == 0;fclose(f);- return ok ? JS_TRUE : JS_FALSE;+ if (!flushed || rename(tmp.c_str(), path.c_str()) != 0) {+ remove(tmp.c_str());+ return JS_FALSE;+ }+ return JS_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]);+ const std::string path = pathIn(host().cacheDir, key);+ if (key) JS_FreeCString(ctx, key);+ return readFileAt(ctx, 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]);+ const std::string path = pathIn(host().cacheDir, key);+ if (key) JS_FreeCString(ctx, key);+ return writeFileAt(ctx, path, argv[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]);+ const std::string path = pathIn(host().dataDir, key);+ if (key) JS_FreeCString(ctx, key);+ return readFileAt(ctx, 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]);+ const std::string path = pathIn(host().dataDir, key);+ if (key) JS_FreeCString(ctx, key);+ return writeFileAt(ctx, path, argv[1]);}// es_utf8Decode(ArrayBuffer | TypedArray) -> string. Backs the TextDecoder the@@ -149,6 +182,8 @@ void registerAssetBindings(HostState& h, JSValue global) {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);}diff --git a/native/host/platform/android.cpp b/native/host/platform/android.cppindex 10c525439..f24eeeda4 100644--- a/native/host/platform/android.cpp+++ b/native/host/platform/android.cpp@@ -146,7 +146,8 @@ struct AndroidPlatform final : eshost::Platform {AAssetManager* assets = nullptr; // APK assets/ — the game + its contentANativeWindow* window = nullptr;JavaVM* vm = nullptr; // for JNI HttpURLConnection off-thread- std::string cache; // app private dir — SDK bytecode cache+ std::string cache; // getCacheDir() — the system may reclaim it+ std::string data; // internalDataPath — files/, survivesstd::string logs; // Android/data/<pkg>/files — a player can open this// Read an APK asset (assets/<path>) fully into a buffer; empty if missing.@@ -166,6 +167,8 @@ struct AndroidPlatform final : eshost::Platform {std::string cacheDir() override { return cache; }+ std::string dataDir() override { return data; }+std::string logDir() override { return logs; }/**@@ -805,6 +808,52 @@ void onWindowFocusChanged(ANativeActivity* activity, int hasFocus) {if (g_glueWindowFocusChanged) g_glueWindowFocusChanged(activity, hasFocus);}+/**+ * `Context.getCacheDir()`, asked rather than assembled.+ *+ * ANativeActivity hands over internalDataPath and externalDataPath and stops+ * there, so the cache directory has to come over JNI. Deriving it from+ * internalDataPath by swapping `files` for `cache` would be a guess about a+ * layout that has already moved once (`/data/data` to `/data/user/0`), and the+ * guess fails silently — as a directory that is simply never written.+ *+ * Empty on failure, which disables the bytecode cache and the hot-update store:+ * both regenerate, so a slower boot is the whole cost.+ */+std::string queryCacheDir(ANativeActivity* activity) {+ if (!activity || !activity->vm || !activity->clazz) return {};+ JNIEnv* env = nullptr;+ if (activity->vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {+ if (activity->vm->AttachCurrentThread(&env, nullptr) != JNI_OK || !env) return {};+ }+ std::string out;+ jclass ctxCls = env->GetObjectClass(activity->clazz);+ jmethodID getCacheDir = env->GetMethodID(ctxCls, "getCacheDir", "()Ljava/io/File;");+ if (getCacheDir) {+ if (jobject file = env->CallObjectMethod(activity->clazz, getCacheDir)) {+ jclass fileCls = env->GetObjectClass(file);+ jmethodID getPath = env->GetMethodID(fileCls, "getAbsolutePath", "()Ljava/lang/String;");+ if (getPath) {+ if (jstring path = (jstring)env->CallObjectMethod(file, getPath)) {+ if (const char* utf8 = env->GetStringUTFChars(path, nullptr)) {+ out = utf8;+ env->ReleaseStringUTFChars(path, utf8);+ }+ env->DeleteLocalRef(path);+ }+ }+ env->DeleteLocalRef(fileCls);+ env->DeleteLocalRef(file);+ }+ }+ env->DeleteLocalRef(ctxCls);+ if (env->ExceptionCheck()) {+ env->ExceptionClear();+ return {};+ }+ return out;+}+} // namespacevoid android_main(android_app* app) {@@ -813,7 +862,9 @@ void android_main(android_app* app) {// Before boot: whether there is an editing surface decides whether the// es_textEditor_* entry points are bound at all.attachTextEditor(app->activity);- if (app->activity->internalDataPath) g_platform.cache = app->activity->internalDataPath;+ // files/ holds what a player keeps; cache/ is the system's to reclaim.+ if (app->activity->internalDataPath) g_platform.data = app->activity->internalDataPath;+ g_platform.cache = queryCacheDir(app->activity);// The boot record goes where a person can reach it without a cable.if (app->activity->externalDataPath) g_platform.logs = app->activity->externalDataPath;app->onAppCmd = onAppCmd;diff --git a/native/host/platform/ios.mm b/native/host/platform/ios.mmindex 4a3d1667c..d073807fa 100644--- a/native/host/platform/ios.mm+++ b/native/host/platform/ios.mm@@ -98,6 +98,26 @@ struct IOSPlatform final : eshost::Platform {return std::string([dirs[0] UTF8String]);}+ /** Application Support, not Caches: iOS empties Caches whenever it wants the+ * space back, which is correct for content that refetches and wrong for a+ * save. Unlike the other two this directory does not exist until an app+ * makes it, so create it — and only report it once it is really there,+ * since an empty answer degrades storage to the session rather than+ * handing out a path that every write will fail against. */+ std::string dataDir() override {+ NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);+ if (dirs.count == 0) return {};+ NSString* path = dirs[0];+ NSError* err = nil;+ if (![[NSFileManager defaultManager] createDirectoryAtPath:path+ withIntermediateDirectories:YES+ attributes:nil+ error:&err]) {+ return {};+ }+ return std::string([path UTF8String]);+ }+/** Documents, not Caches: the record exists to be sent, and Documents is the* directory the Files app shows (with UIFileSharingEnabled) and iTunes/Finder* can copy off a device that has none. */diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex ebda86b06..6ef27db04 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4214,6 +4214,7 @@ es_loadImagePixels: (path: string) => { width: number; height: number; pixels: Aes_rasterizeGlyph: ((request: PlatformGlyphRequest) => { pixels: ArrayBuffer; width: number; height: number; advance: number; bearingX: number; bearingY: number; } | null) | undefinedes_readAsset: (path: string) => ArrayBuffer | nulles_readCacheFile: ((key: string) => ArrayBuffer | null) | undefined+es_readDataFile: ((key: string) => ArrayBuffer | null) | undefinedes_removeStorageItem: ((key: string) => void) | undefinedes_setStorageItem: ((key: string, value: string) => void) | undefinedes_storageKeys: (() => string[]) | undefined@@ -4221,6 +4222,7 @@ es_textEditor_blur: (() => void) | undefinedes_textEditor_focus: ((value: string, selectionStart: number, selectionEnd: number, multiline: boolean, maxLength: number, password: boolean) => void) | undefinedes_textEditor_write: ((value: string, selectionStart: number, selectionEnd: number) => void) | undefinedes_writeCacheFile: ((key: string, bytes: ArrayBuffer | Uint8Array | string) => boolean) | undefined+es_writeDataFile: ((key: string, bytes: ArrayBuffer | Uint8Array | string) => boolean) | undefined```## NativeInputListener — interface @betadiff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex 3bded7f00..54005cbcc 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -39,12 +39,18 @@ export interface NativeHostBindings {pixels: ArrayBuffer; width: number; height: number;advance: number; bearingX: number; bearingY: number;} | null;- /** A writable byte store (the host's cache dir). Optional: without it there- * is no offline hot-update cache and no persistence for storage. */+ /** A writable byte store the platform may reclaim (the host's cache dir).+ * Optional: without it there is no offline hot-update cache. */es_readCacheFile?(key: string): ArrayBuffer | null;es_writeCacheFile?(key: string, bytes: ArrayBuffer | Uint8Array | string): boolean;+ /** The durable store, for what a player would notice losing. Separate from the+ * cache pair above because the platform is allowed to empty a cache and iOS+ * does: a host that maps both onto one directory has decided saves are+ * disposable, whether or not it meant to. */+ es_readDataFile?(key: string): ArrayBuffer | null;+ es_writeDataFile?(key: string, bytes: ArrayBuffer | Uint8Array | string): boolean;/** Native key-value store, when the host has one (NSUserDefaults /- * SharedPreferences). Absent hosts persist through es_writeCacheFile. */+ * SharedPreferences). Absent hosts persist through es_writeDataFile. */es_getStorageItem?(key: string): string | null;es_setStorageItem?(key: string, value: string): void;es_removeStorageItem?(key: string): void;@@ -336,9 +342,14 @@ const STORAGE_FILE = 'estella-storage.json';/*** Key-value storage, best available: the host's own store, else a JSON file in- * its writable cache dir, else memory for the session. The API is synchronous+ * its durable directory, else memory for the session. The API is synchronous* (localStorage's shape), so the file variant keeps the map in memory and writes* through on every mutation — storage holds saves and settings, not bulk data.+ *+ * The file goes to the DATA store, never the cache. An older host that binds only+ * the cache pair still persists through it, because a cache that usually survives+ * beats losing the save at every exit — but it is the wrong directory on any+ * platform that reclaims one, so say so once rather than let a player find out.*/function hostStorage(bindings: NativeHostBindings): Pick<NativeBridge, 'getStorageItem' | 'setStorageItem' | 'removeStorageItem' | 'storageKeys'@@ -352,13 +363,20 @@ function hostStorage(bindings: NativeHostBindings): Pick<};}+ const durable = typeof bindings.es_readDataFile === 'function'+ && typeof bindings.es_writeDataFile === 'function';+ const read = durable ? bindings.es_readDataFile! : bindings.es_readCacheFile;+ const write = durable ? bindings.es_writeDataFile! : bindings.es_writeCacheFile;+const entries = new Map<string, string>();- const persistent = typeof bindings.es_readCacheFile === 'function'- && typeof bindings.es_writeCacheFile === 'function';+ const persistent = typeof read === 'function' && typeof write === 'function';if (!persistent) {- log.warn('native', 'host has no storage or cache bindings — saves last only for this session');+ log.warn('native', 'host has no storage or file bindings — saves last only for this session');} else {- const bytes = bindings.es_readCacheFile!(STORAGE_FILE);+ if (!durable) {+ log.warn('native', 'host binds no durable store — saves go to its cache, which the platform may reclaim');+ }+ const bytes = read!(STORAGE_FILE);if (bytes) {try {for (const [k, v] of Object.entries(JSON.parse(new TextDecoder().decode(bytes)) as Record<string, string>)) {@@ -373,7 +391,7 @@ function hostStorage(bindings: NativeHostBindings): Pick<if (!persistent) return;// A string, not encoded bytes: the host writes UTF-8 itself, and a native// JS engine has no TextEncoder to reach for.- bindings.es_writeCacheFile!(STORAGE_FILE, JSON.stringify(Object.fromEntries(entries)));+ write!(STORAGE_FILE, JSON.stringify(Object.fromEntries(entries)));};return {getStorageItem: (key) => entries.get(key) ?? null,diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.tsindex 606b579e3..dbe8c7e7f 100644--- a/sdk/tests/native-host-bridge.test.ts+++ b/sdk/tests/native-host-bridge.test.ts@@ -74,7 +74,52 @@ describe('createHostBridge', () => {expect(sink.onTouchStart).toHaveBeenCalledTimes(1);});- it('persists storage through the host cache file', () => {+ /** A host with both stores, kept apart so a test can say which one was written. */+ const twoStoreScope = (): { scope: ReturnType<typeof hostScope>; cache: Map<string, string>; data: Map<string, string> } => {+ const cache = new Map<string, string>();+ const data = new Map<string, string>();+ const reader = (store: Map<string, string>) => (key: string) => {+ const text = store.get(key);+ return text === undefined ? null : new TextEncoder().encode(text).buffer;+ };+ return {+ cache,+ data,+ scope: hostScope({+ es_readCacheFile: reader(cache),+ es_writeCacheFile: (key: string, bytes: string) => { cache.set(key, bytes); return true; },+ es_readDataFile: reader(data),+ es_writeDataFile: (key: string, bytes: string) => { data.set(key, bytes); return true; },+ }),+ };+ };++ it('persists storage through the host data file', () => {+ const { scope } = twoStoreScope();+ createHostBridge(scope).setStorageItem('save', '{"level":3}');+ // A fresh bridge (the next launch) reads what the previous one wrote.+ expect(createHostBridge(scope).getStorageItem('save')).toBe('{"level":3}');+ });++ // The whole point of the split: a platform is allowed to empty its cache, so a+ // save that lands there is a save the player can lose.+ it('writes saves to the durable store and never to the cache', () => {+ const { scope, cache, data } = twoStoreScope();+ createHostBridge(scope).setStorageItem('save', '{"level":3}');+ expect([...data.keys()]).toEqual(['estella-storage.json']);+ expect(cache.size).toBe(0);+ });++ it('survives a cache the platform reclaimed', () => {+ const { scope, cache } = twoStoreScope();+ createHostBridge(scope).setStorageItem('save', '{"level":3}');+ cache.clear();+ expect(createHostBridge(scope).getStorageItem('save')).toBe('{"level":3}');+ });++ // An older shell binds only the cache pair. Persisting there beats losing the+ // save at every exit, so the fallback stays.+ it('still persists through a host that binds only the cache pair', () => {const files = new Map<string, string>();const scope = hostScope({es_readCacheFile: (key: string) => {@@ -85,7 +130,6 @@ describe('createHostBridge', () => {});createHostBridge(scope).setStorageItem('save', '{"level":3}');- // A fresh bridge (the next launch) reads what the previous one wrote.expect(createHostBridge(scope).getStorageItem('save')).toBe('{"level":3}');});