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(sdk,editor): scene load salvages invalid fields; one bad value never bricks the scene
yhh6f3afa77ecfb
diff --git a/desktop/electron/mcpEndpoint.ts b/desktop/electron/mcpEndpoint.tsindex 81486819b..440e85b73 100644--- a/desktop/electron/mcpEndpoint.ts+++ b/desktop/electron/mcpEndpoint.ts@@ -40,6 +40,18 @@ export function mcpMode(): boolean {export async function startMcpEndpoint(getWin: () => BrowserWindow | null): Promise<void> {const token = process.env.ESTELLA_MCP_TOKEN || randomBytes(24).toString('hex');+ // executeJavaScript rejects a thrown error with an opaque "Script failed to+ // execute" — wrap the expression so the real message crosses the boundary+ // (surface errors like `component "X" is not on entity 5` are the automation+ // client's actual feedback, not a debugging detail).+ const carryError = (expr: string) =>+ `(async () => { try { return { v: await (${expr}) }; } catch (e) { return { __estellaExecError: (e && e.message) || String(e) }; } })()`;+ const unwrap = (res: unknown) => {+ const r = res as { v?: unknown; __estellaExecError?: string } | null;+ if (r && typeof r === 'object' && r.__estellaExecError !== undefined) throw new Error(r.__estellaExecError);+ return r?.v;+ };+const exec = async (code: string) => {const win = getWin();if (!win) throw new Error('no editor window');@@ -48,7 +60,7 @@ export async function startMcpEndpoint(getWin: () => BrowserWindow | null): Promif (win.webContents.isLoading()) {await new Promise<void>((resolve) => win.webContents.once('did-finish-load', () => resolve()));}- return win.webContents.executeJavaScript(code, true);+ return unwrap(await win.webContents.executeJavaScript(carryError(code), true));};const server = await createExecEndpoint({@@ -71,7 +83,7 @@ export async function startMcpEndpoint(getWin: () => BrowserWindow | null): Promconst playFrames = win.webContents.mainFrame.frames.filter((f) => f.url.startsWith('estella://'));const playFrame = playFrames[frame ?? 0];if (!playFrame) throw new Error(`no play realm at index ${frame ?? 0} (${playFrames.length} running — enter play first)`);- return playFrame.executeJavaScript(code ?? 'true');+ return unwrap(await playFrame.executeJavaScript(carryError(code ?? 'true')));}if (js) return exec(js);const target = root === 'editor' ? 'window.__estellaEditor' : 'window.__estellaEditor.surface';diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex 023e1a1fb..bbe58bc3e 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -508,12 +508,34 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompo// Asset-ref fields validate leniently: their serialized string ref and runtime// numeric handle are both legal (a Tiled-imported Tilemap's `source: 0` == "none").+ const context = entityName ? ` (entity "${entityName}")` : '';const errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data, assetFieldNames(comp));if (errors.length > 0) {- const context = entityName ? ` (entity "${entityName}")` : '';- log.warn('scene', formatValidationErrors(compData.type + context, errors));+ // Salvage, not sacrifice: deserialized data is the one input the strict+ // storage validators must not veto wholesale — drop the invalid fields so+ // their defaults apply and the REST of the component still loads. Without+ // this the insert below throws and one stale string in a saved scene+ // bricks the whole scene load.+ for (const err of errors) {+ const root = err.field in compData.data ? err.field : err.field.split('.')[0];+ delete compData.data[root];+ }+ log.warn(+ 'scene',+ `${formatValidationErrors(compData.type + context, errors)}\n → invalid fields dropped, their defaults apply (fix the scene file to silence this)`+ );+ }+ try {+ world.insert(entity, comp, compData.data);+ } catch (err) {+ // Defense in depth: a deeper boundary rejection costs THIS component, not+ // the scene.+ log.error(+ 'scene',+ `component "${compData.type}"${context} failed to insert — skipped: ${err instanceof Error ? err.message : String(err)}`+ );+ return;}- world.insert(entity, comp, compData.data);if (codec?.importData && outOfBand) {codec.importData(entity as unknown as number, outOfBand);diff --git a/sdk/src/validation.ts b/sdk/src/validation.tsindex 507bd19a9..47b2f8d55 100644--- a/sdk/src/validation.ts+++ b/sdk/src/validation.ts@@ -19,16 +19,33 @@ export function validateComponentData(assetFields?: ReadonlySet<string>): ValidationError[] {const errors: ValidationError[] = [];+ validateInto(errors, defaults, data, assetFields, '');+ return errors;+}+function validateInto(+ errors: ValidationError[],+ defaults: Record<string, unknown>,+ data: Record<string, unknown>,+ assetFields: ReadonlySet<string> | undefined,+ prefix: string+): void {for (const [field, value] of Object.entries(data)) {if (field.startsWith('_')) continue;+ const path = prefix ? `${prefix}.${field}` : field;if (!(field in defaults)) {- errors.push({- field,- expected: 'field to exist in component definition',- actual: 'unknown field',- value,- });+ // Unknown members are an error only at the TOP level (a stray key names+ // a field that will silently never apply). Nested objects legally carry+ // extra keys — e.g. colors read back from wasm keep ghost x/y/z/w+ // members beside r/g/b/a — so those pass.+ if (!prefix) {+ errors.push({+ field: path,+ expected: 'field to exist in component definition',+ actual: 'unknown field',+ value,+ });+ }continue;}@@ -37,13 +54,16 @@ export function validateComponentData(const actualType = getType(value);if (expectedType === 'null' || expectedType === 'undefined') continue;+ if (value === null || value === undefined) continue;- if (expectedType !== actualType && value !== null && value !== undefined) {+ if (expectedType !== actualType) {// Asset-ref fields carry two legal shapes: a portable string ref// ("@uuid:…", or "" for none) in serialized/model data, and a numeric// runtime handle (0 for none). A string↔number mismatch on one denotes- // the same asset (or its absence), so it is not an error.+ // the same asset (or its absence), so it is not an error. (Asset refs+ // are top-level fields; the rule never applies at depth.)if (+ !prefix &&assetFields?.has(field) &&((expectedType === 'string' && actualType === 'number') ||(expectedType === 'number' && actualType === 'string'))@@ -51,15 +71,27 @@ export function validateComponentData(continue;}errors.push({- field,+ field: path,expected: expectedType,actual: actualType,value,});+ continue;}- }- return errors;+ // Same-shape plain objects: check member TYPES at depth ("size.x" holding+ // a string would otherwise sail through and reach the ABI as garbage).+ // Arrays are type-matched only — element schemas belong to their consumers.+ if (expectedType === 'object') {+ validateInto(+ errors,+ defaultValue as Record<string, unknown>,+ value as Record<string, unknown>,+ undefined,+ path+ );+ }+ }}/** A component's asset-ref field names — pass to {@link validateComponentData} sodiff --git a/sdk/tests/scene-validation.test.ts b/sdk/tests/scene-validation.test.tsindex e64bfdab3..e62183835 100644--- a/sdk/tests/scene-validation.test.ts+++ b/sdk/tests/scene-validation.test.ts@@ -48,6 +48,39 @@ describe('validateComponentData', () => {expect(errors[0].expected).toBe('object');expect(errors[0].actual).toBe('string');});++ it('detects nested member type mismatches with dotted field paths', () => {+ const defaults = { size: { x: 0, y: 0 } };+ const data = { size: { x: 'garbage', y: 16 } };+ const errors = validateComponentData('Test', defaults, data);+ expect(errors).toHaveLength(1);+ expect(errors[0].field).toBe('size.x');+ expect(errors[0].expected).toBe('number');+ expect(errors[0].actual).toBe('string');+ });++ it('recurses through deeper object nesting', () => {+ const defaults = { a: { b: { c: 0 } } };+ const data = { a: { b: { c: 'nope' } } };+ const errors = validateComponentData('Test', defaults, data);+ expect(errors).toHaveLength(1);+ expect(errors[0].field).toBe('a.b.c');+ });++ it('tolerates unknown NESTED members (wasm colors keep ghost x/y/z/w beside r/g/b/a)', () => {+ const defaults = { color: { r: 1, g: 1, b: 1, a: 1 } };+ const data = { color: { r: 1, g: 0, b: 0, a: 1, x: 1, y: 0, z: 0, w: 1 } };+ expect(validateComponentData('Test', defaults, data)).toEqual([]);+ });++ it('still flags unknown TOP-LEVEL fields while tolerating nested ones', () => {+ const defaults = { size: { x: 0, y: 0 } };+ const data = { 'size.x': '16' };+ const errors = validateComponentData('Test', defaults, data);+ expect(errors).toHaveLength(1);+ expect(errors[0].field).toBe('size.x');+ expect(errors[0].actual).toBe('unknown field');+ });});describe('formatValidationErrors', () => {diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.tsindex 8fc539703..0af5983e7 100644--- a/sdk/tests/scene.test.ts+++ b/sdk/tests/scene.test.ts@@ -258,6 +258,28 @@ describe('Scene', () => {);warnSpy.mockRestore();});++ it('salvages invalid fields — dropped to defaults with a warning, the rest loads', () => {+ // One stale string in a saved scene must cost that FIELD, not the+ // component (the storage validator throws) and never the scene.+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const entity = world.spawn();+ expect(() =>+ loadComponent(world, entity, {+ type: 'Sprite',+ // size.x garbage (nested type mismatch) + a stray top-level key —+ // the exact corruption shape a broken automation client once wrote.+ data: { texture: 0, size: { x: 'garbage', y: 16 }, 'size.x': '16' },+ }, 'ninja'),+ ).not.toThrow();++ expect(world.has(entity, Sprite)).toBe(true);+ const sprite = world.get(entity, Sprite);+ expect(sprite.size).toMatchObject({ x: 100, y: 100 }); // dropped → default+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('invalid fields dropped'));+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('entity "ninja"'));+ warnSpy.mockRestore();+ });});// =========================================================================