Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): a game's own data is an asset, not a file you fetch

yhh8434345a5069
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ff66e933..26a9e3120 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,25 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **A game's own data is an asset.** A `.json` that is not a Spine skeleton or a
+ DragonBones pair — a level table, a tuning file, dialogue — was not an asset at all:
+ no `.meta`, no uuid, nothing in the registry, so the only way to read one was to fetch
+ its path by hand. That works in the editor, which serves the whole project, and 404s in
+ the build, which ships only assets. The failure appears after release and nowhere else.
+
+ It is a type now, `json`, with `assets.loadJson<T>(ref)`. Being a type is the point: a
+ data file gets ref resolution (`@uuid:` and manifest paths, so moving it breaks
+ nothing), one parse shared by every caller, group and subpackage delivery, and hot
+ update — none of which a hand-rolled fetch can have. It is also always included in a
+ build, like locale tables and for the same reason: the code that loads it is the only
+ thing that names it, so reachability would cull every one.
+
+ Two edges, deliberately: the content sniff still asks Spine and DragonBones first, so
+ nothing that was already a skeleton becomes data; and the project's own configuration
+ (`package.json`, `tsconfig.json` and their kind) never becomes an asset.
+
### Fixed
- **Checking for updates showed nothing, and could show nothing forever.** The toast was
diff --git a/desktop/electron/assetDb.ts b/desktop/electron/assetDb.ts
index 94b93fc33..c9334caaf 100644
--- a/desktop/electron/assetDb.ts
+++ b/desktop/electron/assetDb.ts
@@ -132,8 +132,14 @@ async function adoptOrphans(root: string, rel = '', adopted: string[] = []): Pro
// so the cook keeps the textures instead of shipping an atlas that 404s them.
const SKELETAL_ATLAS_TYPES = new Set(['spine-atlas', 'dragonbones-atlas']);
+// 'json' is a game's own data table. It is scanned like the rest because a
+// data-driven game names assets FROM its data — a spawn table holding `@uuid:`
+// refs is the ordinary way to do that — and an unscanned table means the cook
+// culls what only it points at, which surfaces as a missing asset in the build
+// and nowhere else.
const JSON_REF_TYPES = new Set([
'scene', 'prefab', 'material', 'tileset', 'tilemap', 'animclip', 'animation', 'statemachine', 'behaviortree',
+ 'json',
]);
/**
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index 4a95c27a7..d8b65074b 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -313,6 +313,13 @@ export async function cookAssets(
for (const e of index.entries) {
if (e.path.toLowerCase().endsWith('.eslocale')) seed(e.uuid);
}
+ // …and data assets, for the same reason one step further: a `.json` table is
+ // named by the code that loads it, so nothing in the scene graph points at it.
+ // Culling it produces the worst failure this pipeline can produce — it works in
+ // the editor, which serves the whole project, and 404s only in the build.
+ for (const e of index.entries) {
+ if (e.type === 'json') seed(e.uuid);
+ }
// …then take the transitive closure over the dependency graph.
while (queue.length > 0) {
const uuid = queue.shift()!;
diff --git a/desktop/tests/asset-db.test.ts b/desktop/tests/asset-db.test.ts
index 3f2ab95b9..d87c6bda7 100644
--- a/desktop/tests/asset-db.test.ts
+++ b/desktop/tests/asset-db.test.ts
@@ -151,16 +151,31 @@ describe('scanAssetDatabase — orphan adoption', () => {
// all Spine 2.1 can export. Nothing in the NAME says the `.json` is a skeleton,
// so a name-only adoption left it out of the registry entirely and its component
// slot had nothing to offer.
- it('adopts a JSON Spine skeleton as spine, and leaves plain data JSON alone', async () => {
+ it('adopts a JSON Spine skeleton as spine and a plain one as data', async () => {
const skel = path.join(root, 'assets/skeleton.json');
const data = path.join(root, 'assets/levels.json');
writeFileSync(skel, '{"skeleton":{"hash":"h","spine":"2.1.27"},"bones":[{"name":"root"}]}');
writeFileSync(data, '{"levels":[1,2,3]}');
const res = await scanAssetDatabase(root, { write: false });
- expect(res.adopted).toEqual(['assets/skeleton.json']);
+ expect(res.adopted.sort()).toEqual(['assets/levels.json', 'assets/skeleton.json']);
+ // The marker inside the file wins; a `.json` nobody else claims is data.
expect(JSON.parse(readFileSync(`${skel}.meta`, 'utf8')).type).toBe('spine');
- expect(existsSync(`${data}.meta`)).toBe(false);
+ expect(JSON.parse(readFileSync(`${data}.meta`, 'utf8')).type).toBe('json');
expect(res.index.entries.find((e) => e.path === 'assets/skeleton.json')?.type).toBe('spine');
- rmSync(skel); rmSync(`${skel}.meta`); rmSync(data);
+ expect(res.index.entries.find((e) => e.path === 'assets/levels.json')?.type).toBe('json');
+ rmSync(skel); rmSync(`${skel}.meta`); rmSync(data); rmSync(`${data}.meta`);
+ });
+
+ it("leaves the project's own config files alone", async () => {
+ // Every project has these, and a `.meta` beside them is pure noise.
+ const ts = path.join(root, 'tsconfig.json');
+ const pkg = path.join(root, 'package.json');
+ writeFileSync(ts, '{"compilerOptions":{}}');
+ writeFileSync(pkg, '{"name":"game"}');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted).toEqual([]);
+ expect(existsSync(`${ts}.meta`)).toBe(false);
+ expect(existsSync(`${pkg}.meta`)).toBe(false);
+ rmSync(ts); rmSync(pkg);
});
});
diff --git a/desktop/tests/asset-meta-table.test.ts b/desktop/tests/asset-meta-table.test.ts
index 0e85eeed3..02de216d0 100644
--- a/desktop/tests/asset-meta-table.test.ts
+++ b/desktop/tests/asset-meta-table.test.ts
@@ -10,7 +10,7 @@
import { describe, it, expect } from 'vitest';
import { EXT_TO_TYPE, metaTypeFor } from '../electron/assetMeta';
import {
- EXT_TO_TYPE as SHARED, metaTypeForContent, needsContentType,
+ EXT_TO_TYPE as SHARED, metaTypeForContent, needsContentType, isProjectPlumbing,
} from '../../tools/assetMetaTable.js';
describe('.meta type table (single source)', () => {
@@ -70,10 +70,28 @@ describe('content-typed assets', () => {
expect(metaTypeForContent('x.json', '{\n "skeleton": {\n "spine": "3.8.99"\n }\n}')).toBe('spine');
});
- it('leaves project data alone — a `.json` is not an asset just for being JSON', () => {
- expect(metaTypeForContent('levels.json', '{"levels":[1,2,3]}')).toBeNull();
- // "spine" outside a skeleton header is not a skeleton.
- expect(metaTypeForContent('notes.json', '{"about":"the spine: 4.2 runtime"}')).toBeNull();
+ it('types a `.json` nobody else claims as data', () => {
+ // The game's own tables are assets: that is what gives them a uuid, a
+ // place in the manifest, and a seat in the build.
+ expect(metaTypeForContent('levels.json', '{"levels":[1,2,3]}')).toBe('json');
+ // "spine" outside a skeleton header is not a skeleton — it is data.
+ expect(metaTypeForContent('notes.json', '{"about":"the spine: 4.2 runtime"}')).toBe('json');
+ });
+
+ it('leaves the project\'s own plumbing alone', () => {
+ // These are read by the toolchain, not the game; a `.meta` beside them
+ // is noise in every project that has ever existed.
+ for (const name of ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json']) {
+ expect(needsContentType(name)).toBe(false);
+ expect(metaTypeForContent(name, '{}')).toBeNull();
+ }
+ expect(isProjectPlumbing('a/b/tsconfig.json')).toBe(true);
+ expect(isProjectPlumbing('assets/data/levels.json')).toBe(false);
+ });
+
+ it('never types a name that is not JSON at all', () => {
+ expect(metaTypeForContent('README.md', '# hi')).toBeNull();
+ expect(metaTypeForContent('main.ts', 'export {}')).toBeNull();
});
it('never overrides a name that already typed the file', () => {
diff --git a/desktop/tests/import-assets.test.ts b/desktop/tests/import-assets.test.ts
index 5136f046c..ee348b5b9 100644
--- a/desktop/tests/import-assets.test.ts
+++ b/desktop/tests/import-assets.test.ts
@@ -97,12 +97,21 @@ describe('importAssets', () => {
expect(meta(path.join(root, 'assets/spine/skeleton.json')).type).toBe('spine');
});
- it('still skips a plain data .json — being JSON does not make a file an asset', async () => {
+ it('imports a plain data .json as a data asset', async () => {
const src = path.join(outside, 'levels.json');
writeFileSync(src, '{"levels":[1,2,3]}');
const res = await importAssets(root, 'assets', [src]);
+ expect(res.imported).toEqual(['assets/levels.json']);
+ expect(res.skipped).toEqual([]);
+ expect(JSON.parse(readFileSync(path.join(root, 'assets/levels.json.meta'), 'utf8')).type).toBe('json');
+ });
+
+ it("skips the project's own config files", async () => {
+ const src = path.join(outside, 'tsconfig.json');
+ writeFileSync(src, '{"compilerOptions":{}}');
+ const res = await importAssets(root, 'assets', [src]);
expect(res.imported).toEqual([]);
- expect(res.skipped).toEqual(['levels.json']);
+ expect(res.skipped).toEqual(['tsconfig.json']);
});
it('offers the content-typed extensions in the dialog filter', () => {
diff --git a/docs/astro/src/content/docs/guides/assets.mdx b/docs/astro/src/content/docs/guides/assets.mdx
index 62f6414f6..a288ca9e6 100644
--- a/docs/astro/src/content/docs/guides/assets.mdx
+++ b/docs/astro/src/content/docs/guides/assets.mdx
@@ -52,6 +52,33 @@ const loadArt = defineSystem([Query(Mut(Sprite)), Res(Assets)], async (q, assets
| `loadTilemap(ref)` / `loadTileset(ref)` | `{ sourceId }` / `{ tilesetId }` |
| `loadTimeline(ref)` | `{ timelineId }` |
| `loadPrefab(ref)` | `{ data }` |
+| `loadJson<T>(ref)` | `{ data: T }` |
+
+## Your own data
+
+A `.json` that is not a Spine skeleton or a DragonBones pair is a **data asset** — the
+game's own tables, tuning and dialogue. It loads like anything else:
+
+```typescript
+const { data } = await assets.loadJson<LevelTable>('data/levels.json');
+```
+
+`T` is what you expect the file to hold; nothing validates it, so this is `JSON.parse`'s
+guarantee and not a schema's.
+
+Loading it as an asset rather than fetching the path yourself is not ceremony. A data
+asset has a uuid, so moving the file does not break what points at it; it is parsed once
+and reference-counted; it can live in a lazy [group](#addressable-groups-lazy-loading) or
+come from a CDN; and [hot update](/docs/guides/hot-update/) can replace it in a shipped
+game. A hand-rolled `fetch` of a project path gets none of that — and it *works in the
+editor*, which serves the whole project, while the build ships only assets.
+
+Data assets ship whether or not anything references them — see
+[Shipping what only code names](#shipping-what-only-code-names), where they are one of
+the two built-in exceptions.
+
+The project's own configuration is not data: `package.json`, `tsconfig.json` and their
+kind never become assets.
There's also a generic `load<T>(type, ref)` when you're driving the type
dynamically, and `register(loader)` to add a loader for a custom asset type.
@@ -169,6 +196,10 @@ model this project already had. **Off by default**, deliberately.
Assets under `subpackages/` are always included even when unreachable — only
their group assignment differs. `alwaysInclude` is what gives any other folder
the same guarantee.
+
+ Two types never need it, because nothing can ever reference them: **locale
+ tables** (`Text` carries keys, not paths) and **data assets** (`.json`, named by
+ the code that loads them). Both always ship.
</Aside>
## Lifetime & reference counting
diff --git a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
index 57b381a1e..d242ee99b 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
@@ -47,10 +47,32 @@ const loadArt = defineSystem([Query(Mut(Sprite)), Res(Assets)], async (q, assets
| `loadTilemap(ref)` / `loadTileset(ref)` | `{ sourceId }` / `{ tilesetId }` |
| `loadTimeline(ref)` | `{ timelineId }` |
| `loadPrefab(ref)` | `{ data }` |
+| `loadJson<T>(ref)` | `{ data: T }` |
还有一个通用的 `load<T>(type, ref)`,当类型是动态决定时用;以及 `register(loader)`
为自定义资源类型添加加载器。
+## 你自己的数据
+
+一个 `.json`,只要不是 Spine 骨架、也不是 DragonBones 的那一对,它就是**数据资源**——
+游戏自己的数值表、配置、对白。和别的资源一样加载:
+
+```typescript
+const { data } = await assets.loadJson<LevelTable>('data/levels.json');
+```
+
+`T` 是你声称这个文件长什么样;没有任何东西校验它,所以这是 `JSON.parse` 的保证,不是 schema 的。
+
+把它当资源加载、而不是自己去 fetch 那个路径,不是走形式。数据资源有 uuid,所以移动文件不会
+让指向它的东西失效;它只解析一次并被引用计数;它可以放进惰性[分组](#寻址组懒加载)或者从 CDN 来;
+[热更新](/docs/zh-cn/guides/hot-update/)能在已发行的游戏里替换它。手写的 `fetch` 一样都拿不到——
+而且它**在编辑器里是通的**(编辑器伺服整个项目),而构建只装资源。
+
+数据资源无论有没有人引用都会进包——见[只有代码点名的资产](#只有代码点名的资产),
+它是那里两个内建例外之一。
+
+项目自己的配置不算数据:`package.json`、`tsconfig.json` 这一类永远不会变成资源。
+
## 清单(manifest)
运行时通过清单把 `@uuid` 引用解析为文件路径:
@@ -149,6 +171,9 @@ const { failed } = await assets.preload(
<Aside type="tip">
`subpackages/` 下的资源即使触达不到也总会被包含——只是分组归属不同。
`alwaysInclude` 让任何其他文件夹也能拿到同样的保证。
+
+ 有两类永远不需要它,因为它们本来就不可能被引用:**多语言字表**(`Text` 带的是 key 不是路径)
+ 和**数据资源**(`.json`,由加载它的代码点名)。这两类总是进包。
</Aside>
## 生命周期与引用计数
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index acbfbb07c..c9105a5d2 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1379 stable · 17 beta · 1 deprecated
+Symbols: 1380 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -3465,6 +3465,11 @@ world: World
(typeof InterpType)[keyof typeof InterpType]
```
+## JsonResult — interface
+```
+data: T
+```
+
## JustifyContent — type
```
(typeof JustifyContent)[keyof typeof JustifyContent]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 45ea2d49e..8770764cc 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1398 stable · 22 beta · 1 deprecated
+Symbols: 1399 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -3473,6 +3473,11 @@ world: World
(typeof InterpType)[keyof typeof InterpType]
```
+## JsonResult — interface
+```
+data: T
+```
+
## JustifyContent — type
```
(typeof JustifyContent)[keyof typeof JustifyContent]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 261043973..e47607f3d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1378 stable · 19 beta · 1 deprecated
+Symbols: 1379 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -3460,6 +3460,11 @@ world: World
(typeof InterpType)[keyof typeof InterpType]
```
+## JsonResult — interface
+```
+data: T
+```
+
## JustifyContent — type
```
(typeof JustifyContent)[keyof typeof JustifyContent]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 96893c000..018a04793 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1399 stable · 17 beta · 1 deprecated
+Symbols: 1400 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -3460,6 +3460,11 @@ world: World
(typeof InterpType)[keyof typeof InterpType]
```
+## JsonResult — interface
+```
+data: T
+```
+
## JustifyContent — type
```
(typeof JustifyContent)[keyof typeof JustifyContent]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 2908afa6c..2ef717ae2 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1389 stable · 17 beta · 1 deprecated
+Symbols: 1390 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -3467,6 +3467,11 @@ world: World
(typeof InterpType)[keyof typeof InterpType]
```
+## JsonResult — interface
+```
+data: T
+```
+
## JustifyContent — type
```
(typeof JustifyContent)[keyof typeof JustifyContent]
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index ad2e6afc5..574d8d5de 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -84,6 +84,15 @@ export interface PrefabResult {
data: unknown;
}
+/**
+ * A data asset's parsed document. `T` is the caller's claim about the file's
+ * shape — the loader parses, it does not validate, so a wrong claim is a wrong
+ * claim about untyped JSON exactly as `JSON.parse` would give.
+ */
+export interface JsonResult<T = unknown> {
+ data: T;
+}
+
export interface LoadContext {
backend: Backend;
catalog: Catalog;
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 6a5f53e61..6b26825f7 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -10,7 +10,7 @@ import type {
AssetLoader, LoadContext, TextureResult, SpineResult,
MaterialResult, FontResult, AudioResult, AnimClipResult,
TilemapResult, TilesetResult, TimelineResult, PrefabResult,
- LocaleResult, FsmResult, BtResult, AnimatorControllerResult,
+ LocaleResult, FsmResult, BtResult, AnimatorControllerResult, JsonResult,
} from './AssetLoader';
import { AsyncCache } from './AsyncCache';
import type { ESEngineModule } from '../wasm';
@@ -31,6 +31,7 @@ import { FsmAssetLoader } from './loaders/FsmAssetLoader';
import { AnimatorControllerAssetLoader } from './loaders/AnimatorControllerAssetLoader';
import { BtAssetLoader } from './loaders/BtAssetLoader';
import { LocaleAssetLoader } from './loaders/LocaleAssetLoader';
+import { JsonAssetLoader } from './loaders/JsonAssetLoader';
import type { SpineModuleController } from '../spine/SpineController';
import { getComponentDefaults } from '../ecs/component';
import { getComponentAssetFieldDescriptors } from '../scene/scene';
@@ -437,6 +438,19 @@ export class Assets {
return this.loadTyped('prefab', ref);
}
+ /**
+ * Load a `.json` data asset — a game's own table, tuning or dialogue file.
+ *
+ * `T` is what the caller expects the document to be; nothing validates it,
+ * so this is `JSON.parse`'s guarantee, not a schema's. What the asset system
+ * adds over fetching the file yourself is everything around the parse: ref
+ * resolution (`@uuid:` and manifest paths), one parse per file, group /
+ * subpackage delivery, and hot update.
+ */
+ async loadJson<T = unknown>(ref: string): Promise<JsonResult<T>> {
+ return this.loadTyped('json', ref);
+ }
+
// =========================================================================
// Generic Load (for custom loaders)
// =========================================================================
@@ -1462,6 +1476,7 @@ export class Assets {
this.register(new AnimatorControllerAssetLoader());
this.register(new BtAssetLoader());
this.register(new LocaleAssetLoader());
+ this.register(new JsonAssetLoader());
}
private textureCacheKey_(path: string, flip: boolean): string {
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 99a4db13b..3514ab014 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -48,6 +48,6 @@ export {
type AssetEntry,
type AssetManifest,
} from './AssetRegistry';
-export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult, type LocaleResult } from './AssetLoader';
+export { type AssetLoader, type LoadContext, type TextureResult, type TextureResult as TextureInfo, type SpineResult, type SpineLoadResult, type MaterialResult, type FontResult, type AudioResult, type LocaleResult, type JsonResult } from './AssetLoader';
export { TextureLoader, type TextureImportSettings, type TextureImportSettingsResolver } from './loaders/TextureLoader';
export { SceneHandle } from './SceneHandle';
diff --git a/sdk/src/asset/loaders/JsonAssetLoader.ts b/sdk/src/asset/loaders/JsonAssetLoader.ts
new file mode 100644
index 000000000..478428651
--- /dev/null
+++ b/sdk/src/asset/loaders/JsonAssetLoader.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file JsonAssetLoader.ts
+ * @brief A game's own data — level tables, tuning, dialogue — as an asset.
+ *
+ * Everything else an engine loads is loaded FOR a subsystem: a texture becomes a
+ * GPU handle, a locale table merges into a catalog. This one hands the parsed
+ * document straight back, because the subsystem is the game.
+ *
+ * Being an asset rather than a `fetch` is the whole point: it resolves `@uuid:`
+ * refs and manifest paths like every other type, so a file that moves does not
+ * break a save; it is cached and reference-counted, so two systems asking for
+ * the same table parse it once; it can live in a lazy subpackage or a remote
+ * group; and hot update can replace it in a shipped game. A hand-rolled fetch of
+ * a project path gets none of that — and worse, it works in the editor (which
+ * serves the whole project) and 404s in the build (which ships only assets).
+ */
+import type { AssetLoader, LoadContext, JsonResult } from '../AssetLoader';
+
+export class JsonAssetLoader implements AssetLoader<JsonResult> {
+ readonly type = 'json';
+ readonly extensions = ['.json'];
+
+ async load(path: string, ctx: LoadContext): Promise<JsonResult> {
+ const buildPath = ctx.catalog.getBuildPath(path);
+ const text = await ctx.loadText(buildPath);
+ try {
+ return { data: JSON.parse(text) as unknown };
+ } catch (err) {
+ // Name the file: the parser's own message is a line and column in a
+ // document the caller never sees.
+ throw new Error(`${path}: not valid JSON — ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+
+ unload(): void {
+ // A parsed document is plain JS memory the caller may still hold; there
+ // is nothing outside the Assets cache to release.
+ }
+}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 29fd48fae..a2df7d0e2 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -88,6 +88,7 @@ export {
type TextureInfo,
type SpineLoadResult,
type LocaleResult,
+ type JsonResult,
type AssetRefInfo,
textureImportSettingsFrom,
type ParsedTextureImportSettings,
diff --git a/sdk/tests/json-asset-loader.test.ts b/sdk/tests/json-asset-loader.test.ts
new file mode 100644
index 000000000..fbb84fa88
--- /dev/null
+++ b/sdk/tests/json-asset-loader.test.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The data asset: a game's own `.json` table, loaded through the asset
+ * system rather than fetched by hand. The point of the type is not the
+ * parse — it is that the parse happens behind ref resolution, caching and
+ * the manifest, like every other asset.
+ */
+import { describe, it, expect, vi } from 'vitest';
+
+// Constructing `Assets` builds a LoadContext, which wants the wasm resource
+// manager — nothing this file exercises touches it (see assets.test.ts).
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => ({}),
+ evictTextureDimensions: vi.fn(),
+}));
+
+import { JsonAssetLoader } from '../src/asset/loaders/JsonAssetLoader';
+import type { LoadContext } from '../src/asset/AssetLoader';
+
+const PATH = 'assets/data/levels.json';
+
+function makeCtx(text: string, buildPath = PATH): LoadContext {
+ return {
+ catalog: { getBuildPath: () => buildPath },
+ loadText: vi.fn(async () => text),
+ } as unknown as LoadContext;
+}
+
+describe('JsonAssetLoader', () => {
+ it('hands back the parsed document', async () => {
+ const loader = new JsonAssetLoader();
+ const { data } = await loader.load(PATH, makeCtx('{"levels":[1,2,3],"name":"forest"}'));
+ expect(data).toEqual({ levels: [1, 2, 3], name: 'forest' });
+ });
+
+ it('reads the COOKED path, so a build that renamed the file still resolves', async () => {
+ // Every other loader goes through the catalog; a data asset that skipped
+ // it would work in the editor and miss in the build.
+ const ctx = makeCtx('[]', 'cooked/ab12cd.json');
+ await new JsonAssetLoader().load(PATH, ctx);
+ expect(ctx.loadText).toHaveBeenCalledWith('cooked/ab12cd.json');
+ });
+
+ it('names the file when the JSON is broken', async () => {
+ // The parser's own message is a line and column in a document the caller
+ // never sees, which is useless when twenty tables are loading.
+ await expect(new JsonAssetLoader().load(PATH, makeCtx('{"levels": [1,'))).rejects.toThrow(PATH);
+ });
+
+ it('claims `.json` and calls itself json', () => {
+ const loader = new JsonAssetLoader();
+ expect(loader.type).toBe('json');
+ expect(loader.extensions).toEqual(['.json']);
+ });
+
+ it('unloads without touching the document it returned', () => {
+ // The caller may still be holding it; there is no subsystem residency to
+ // sever, so unload has nothing to do and must not pretend otherwise.
+ expect(() => new JsonAssetLoader().unload()).not.toThrow();
+ });
+});
+
+// The loader only matters if `Assets` actually offers it — a type nobody
+// registered is a type nobody can load.
+describe('Assets.loadJson', () => {
+ it('is registered as a built-in and reaches the parsed document', async () => {
+ const { Assets } = await import('../src/asset/Assets');
+ const backend = {
+ fetchText: async () => '{"hp":12}',
+ fetchBinary: async () => new ArrayBuffer(0),
+ resolveUrl: (p: string) => p,
+ setBaseUrl: () => {},
+ } as unknown as import('../src/asset/Backend').Backend;
+
+ const assets = Assets.create({ backend });
+ expect(assets.getLoader('json')).toBeDefined();
+
+ const { data } = await assets.loadJson<{ hp: number }>('assets/data/tuning.json');
+ expect(data.hp).toBe(12);
+ });
+});
diff --git a/tools/assetMetaTable.d.ts b/tools/assetMetaTable.d.ts
index 9b8fe8e56..02d72dcb0 100644
--- a/tools/assetMetaTable.d.ts
+++ b/tools/assetMetaTable.d.ts
@@ -7,3 +7,4 @@ export const CONTENT_SNIFF_BYTES: number;
export function metaTypeForExt(fileOrExt: string): string | null;
export function needsContentType(fileOrExt: string): boolean;
export function metaTypeForContent(fileOrExt: string, head: string): string | null;
+export function isProjectPlumbing(fileOrPath: string): boolean;
diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.js
index 992fcd93a..29d29c0aa 100644
--- a/tools/assetMetaTable.js
+++ b/tools/assetMetaTable.js
@@ -114,6 +114,28 @@ export function metaTypeForExt(fileOrExt) {
*/
export const CONTENT_TYPED_EXTENSIONS = Object.freeze(['.json']);
+/**
+ * Files that are the project's own configuration, never its content.
+ *
+ * A plain `.json` is a data asset (see {@link metaTypeForContent}), and these
+ * are the ones that would be swept up by that and should not be: they are read
+ * by the toolchain, not by the game, and a `.meta` beside `package.json` is
+ * noise in every project that has ever existed. Matched by full name, because
+ * `data/package.json` — a file a game genuinely ships — is not this.
+ */
+const PLUMBING_FILES = Object.freeze(new Set([
+ 'package.json',
+ 'package-lock.json',
+ 'tsconfig.json',
+ 'jsconfig.json',
+]));
+
+/** Is this the project's own plumbing rather than a game asset? */
+export function isProjectPlumbing(fileOrPath) {
+ const parts = String(fileOrPath).toLowerCase().replace(/\\/g, '/').split('/');
+ return PLUMBING_FILES.has(parts[parts.length - 1]);
+}
+
/** How much of a file's head the sniff needs. A skeleton's `"skeleton"` header
* is the first thing the exporter writes, and a bound keeps the scan from
* re-reading every unrelated multi-megabyte JSON in the project. */
@@ -122,6 +144,7 @@ export const CONTENT_SNIFF_BYTES = 65536;
/** Whether @p fileOrExt is one the name cannot type but content can. */
export function needsContentType(fileOrExt) {
const lower = fileOrExt.toLowerCase();
+ if (isProjectPlumbing(lower)) return false;
return metaTypeForExt(lower) === null && CONTENT_TYPED_EXTENSIONS.some((ext) => lower.endsWith(ext));
}
@@ -133,13 +156,19 @@ const SPINE_SKELETON_JSON = /"skeleton"\s*:\s*\{[^{}]*"spine"\s*:\s*"\d/;
/**
* The `.meta` type for a file whose head has been read — the name-derived one
- * where a name suffices, else what the content declares. Null means neither
- * could type it (a plain data `.json`), which the callers treat as "not an
- * asset", exactly as an unknown extension is.
+ * where a name suffices, else what the content declares.
+ *
+ * A `.json` nobody else claims is `json`: a data asset, the type a game's own
+ * tables and configuration load as. It is the LAST claim on purpose — Spine's
+ * skeleton and DragonBones' pair are also `.json`, and they are recognised
+ * first, so nothing that was already a skeleton becomes data.
+ *
+ * Null still means "not an asset", but now only for a name nothing can type at
+ * all (a `.md`, a `.ts`) and for the project's own plumbing.
*/
export function metaTypeForContent(fileOrExt, head) {
const byName = metaTypeForExt(fileOrExt);
if (byName) return byName;
if (!needsContentType(fileOrExt)) return null;
- return SPINE_SKELETON_JSON.test(head) ? 'spine' : null;
+ return SPINE_SKELETON_JSON.test(head) ? 'spine' : 'json';
}