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 shipped game can say what went wrong

yhh9d87f32f4412
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 34c4b4e09..2a38a581b 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: 1406 stable · 17 beta · 1 deprecated
+Symbols: 1419 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2077,6 +2077,93 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
+## DiagnosticEvent — interface
+```
+context: Record<string, unknown> | undefined
+count: number
+firstAt: number
+id: string
+kind: DiagnosticKind
+lastAt: number
+message: string
+source: string | undefined
+stack: string | undefined
+```
+
+## DiagnosticKind — type
+```
+| 'engine'
+ /** Reached the host with nobody catching it: `window.onerror`,
+ * `unhandledrejection`, `wx.onError`. Usually game code outside a system —
+ * a callback, a promise, a timer. */
+ | 'unhandled'
+ /** The GPU took the context away (backgrounded, driver reset, too many
+ * contexts). The frame after this one draws nothing. */
+ | 'context-lost'
+ /** The OS says memory is running out. Not yet a failure — it is the warning
+ * that arrives before the process is killed, which is the crash no report
+ * ever gets sent for. */
+ | 'memory'
+ /** The game itself called `Diagnostics.report` — a failed purchase, a save
+ * that would not write, whatever it considers worth knowing. */
+ | 'game'
+```
+
+## DiagnosticReport — interface
+```
+context: Record<string, unknown> | undefined
+error: unknown
+kind: DiagnosticKind
+message: string
+source: string | undefined
+```
+
+## Diagnostics — const
+```
+ResourceDef<DiagnosticsAPI>
+```
+
+## DiagnosticsAPI — class
+```
+clear: () => void
+dropped: number
+events: readonly DiagnosticEvent[]
+flush: () => void
+report: (report: DiagnosticReport) => void
+reportError: (kind: DiagnosticReport["kind"], error: unknown, source?: string) => void
+setSink: (sink: DiagnosticsSink | null) => void
+tick: (deltaSeconds: number) => void
+static new (options?: DiagnosticsOptions): DiagnosticsAPI
+static prototype: DiagnosticsAPI
+```
+
+## DiagnosticsOptions — interface
+```
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsPlugin — class
+```
+build: (app: App) => void
+cleanup: (app: App) => void
+name: string
+static new (options_?: DiagnosticsPluginOptions): DiagnosticsPlugin
+static prototype: DiagnosticsPlugin
+```
+
+## DiagnosticsPluginOptions — interface
+```
+captureLevel: LogLevel | undefined
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsSink — type
+```
+(events: readonly DiagnosticEvent[]) => void
+```
+
## DialogHandle — interface
```
close: () => void
@@ -4869,8 +4956,10 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+onUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefined
openDataCanvas: (() => PlatformCanvas | null) | undefined
openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -9039,6 +9128,11 @@ PluralSelector
(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
```
+## diagnosticsPlugin — const
+```
+DiagnosticsPlugin
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -9179,6 +9273,11 @@ EventBindingPlugin
(grid: NavGrid, start: Cell, goal: Cell, opts?: PathfindOptions): Cell[] | null
```
+## fingerprint — function
+```
+(report: DiagnosticReport): string
+```
+
## flattenPrefab — function
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
@@ -9724,6 +9823,11 @@ Logger
Mesh2DPlugin
```
+## messageOf — function
+```
+(error: unknown): string
+```
+
## migratePrefabData — function
```
(raw: unknown): MigrationResult
@@ -10509,6 +10613,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## stackOf — function
+```
+(error: unknown): string | undefined
+```
+
## statsPlugin — const
```
StatsPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 118687e10..4027019cc 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: 1425 stable · 22 beta · 1 deprecated
+Symbols: 1438 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2085,6 +2085,93 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
+## DiagnosticEvent — interface
+```
+context: Record<string, unknown> | undefined
+count: number
+firstAt: number
+id: string
+kind: DiagnosticKind
+lastAt: number
+message: string
+source: string | undefined
+stack: string | undefined
+```
+
+## DiagnosticKind — type
+```
+| 'engine'
+ /** Reached the host with nobody catching it: `window.onerror`,
+ * `unhandledrejection`, `wx.onError`. Usually game code outside a system —
+ * a callback, a promise, a timer. */
+ | 'unhandled'
+ /** The GPU took the context away (backgrounded, driver reset, too many
+ * contexts). The frame after this one draws nothing. */
+ | 'context-lost'
+ /** The OS says memory is running out. Not yet a failure — it is the warning
+ * that arrives before the process is killed, which is the crash no report
+ * ever gets sent for. */
+ | 'memory'
+ /** The game itself called `Diagnostics.report` — a failed purchase, a save
+ * that would not write, whatever it considers worth knowing. */
+ | 'game'
+```
+
+## DiagnosticReport — interface
+```
+context: Record<string, unknown> | undefined
+error: unknown
+kind: DiagnosticKind
+message: string
+source: string | undefined
+```
+
+## Diagnostics — const
+```
+ResourceDef<DiagnosticsAPI>
+```
+
+## DiagnosticsAPI — class
+```
+clear: () => void
+dropped: number
+events: readonly DiagnosticEvent[]
+flush: () => void
+report: (report: DiagnosticReport) => void
+reportError: (kind: DiagnosticReport["kind"], error: unknown, source?: string) => void
+setSink: (sink: DiagnosticsSink | null) => void
+tick: (deltaSeconds: number) => void
+static new (options?: DiagnosticsOptions): DiagnosticsAPI
+static prototype: DiagnosticsAPI
+```
+
+## DiagnosticsOptions — interface
+```
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsPlugin — class
+```
+build: (app: App) => void
+cleanup: (app: App) => void
+name: string
+static new (options_?: DiagnosticsPluginOptions): DiagnosticsPlugin
+static prototype: DiagnosticsPlugin
+```
+
+## DiagnosticsPluginOptions — interface
+```
+captureLevel: LogLevel | undefined
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsSink — type
+```
+(events: readonly DiagnosticEvent[]) => void
+```
+
## DialogHandle — interface
```
close: () => void
@@ -5025,8 +5112,10 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+onUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefined
openDataCanvas: (() => PlatformCanvas | null) | undefined
openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -9245,6 +9334,11 @@ PluralSelector
(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
```
+## diagnosticsPlugin — const
+```
+DiagnosticsPlugin
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -9385,6 +9479,11 @@ EventBindingPlugin
(grid: NavGrid, start: Cell, goal: Cell, opts?: PathfindOptions): Cell[] | null
```
+## fingerprint — function
+```
+(report: DiagnosticReport): string
+```
+
## flattenPrefab — function
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
@@ -9940,6 +10039,11 @@ Logger
Mesh2DPlugin
```
+## messageOf — function
+```
+(error: unknown): string
+```
+
## migratePrefabData — function
```
(raw: unknown): MigrationResult
@@ -10725,6 +10829,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## stackOf — function
+```
+(error: unknown): string | undefined
+```
+
## statsPlugin — const
```
StatsPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 45b7d6dd4..2783ae7ad 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: 1405 stable · 19 beta · 1 deprecated
+Symbols: 1418 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2072,6 +2072,93 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
+## DiagnosticEvent — interface
+```
+context: Record<string, unknown> | undefined
+count: number
+firstAt: number
+id: string
+kind: DiagnosticKind
+lastAt: number
+message: string
+source: string | undefined
+stack: string | undefined
+```
+
+## DiagnosticKind — type
+```
+| 'engine'
+ /** Reached the host with nobody catching it: `window.onerror`,
+ * `unhandledrejection`, `wx.onError`. Usually game code outside a system —
+ * a callback, a promise, a timer. */
+ | 'unhandled'
+ /** The GPU took the context away (backgrounded, driver reset, too many
+ * contexts). The frame after this one draws nothing. */
+ | 'context-lost'
+ /** The OS says memory is running out. Not yet a failure — it is the warning
+ * that arrives before the process is killed, which is the crash no report
+ * ever gets sent for. */
+ | 'memory'
+ /** The game itself called `Diagnostics.report` — a failed purchase, a save
+ * that would not write, whatever it considers worth knowing. */
+ | 'game'
+```
+
+## DiagnosticReport — interface
+```
+context: Record<string, unknown> | undefined
+error: unknown
+kind: DiagnosticKind
+message: string
+source: string | undefined
+```
+
+## Diagnostics — const
+```
+ResourceDef<DiagnosticsAPI>
+```
+
+## DiagnosticsAPI — class
+```
+clear: () => void
+dropped: number
+events: readonly DiagnosticEvent[]
+flush: () => void
+report: (report: DiagnosticReport) => void
+reportError: (kind: DiagnosticReport["kind"], error: unknown, source?: string) => void
+setSink: (sink: DiagnosticsSink | null) => void
+tick: (deltaSeconds: number) => void
+static new (options?: DiagnosticsOptions): DiagnosticsAPI
+static prototype: DiagnosticsAPI
+```
+
+## DiagnosticsOptions — interface
+```
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsPlugin — class
+```
+build: (app: App) => void
+cleanup: (app: App) => void
+name: string
+static new (options_?: DiagnosticsPluginOptions): DiagnosticsPlugin
+static prototype: DiagnosticsPlugin
+```
+
+## DiagnosticsPluginOptions — interface
+```
+captureLevel: LogLevel | undefined
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsSink — type
+```
+(events: readonly DiagnosticEvent[]) => void
+```
+
## DialogHandle — interface
```
close: () => void
@@ -4864,8 +4951,10 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+onUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefined
openDataCanvas: (() => PlatformCanvas | null) | undefined
openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -9034,6 +9123,11 @@ PluralSelector
(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
```
+## diagnosticsPlugin — const
+```
+DiagnosticsPlugin
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -9174,6 +9268,11 @@ EventBindingPlugin
(grid: NavGrid, start: Cell, goal: Cell, opts?: PathfindOptions): Cell[] | null
```
+## fingerprint — function
+```
+(report: DiagnosticReport): string
+```
+
## flattenPrefab — function
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
@@ -9724,6 +9823,11 @@ Logger
Mesh2DPlugin
```
+## messageOf — function
+```
+(error: unknown): string
+```
+
## migratePrefabData — function
```
(raw: unknown): MigrationResult
@@ -10514,6 +10618,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## stackOf — function
+```
+(error: unknown): string | undefined
+```
+
## statsPlugin — const
```
StatsPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 49d7497d7..dce2664d9 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: 1426 stable · 17 beta · 1 deprecated
+Symbols: 1439 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2072,6 +2072,93 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
+## DiagnosticEvent — interface
+```
+context: Record<string, unknown> | undefined
+count: number
+firstAt: number
+id: string
+kind: DiagnosticKind
+lastAt: number
+message: string
+source: string | undefined
+stack: string | undefined
+```
+
+## DiagnosticKind — type
+```
+| 'engine'
+ /** Reached the host with nobody catching it: `window.onerror`,
+ * `unhandledrejection`, `wx.onError`. Usually game code outside a system —
+ * a callback, a promise, a timer. */
+ | 'unhandled'
+ /** The GPU took the context away (backgrounded, driver reset, too many
+ * contexts). The frame after this one draws nothing. */
+ | 'context-lost'
+ /** The OS says memory is running out. Not yet a failure — it is the warning
+ * that arrives before the process is killed, which is the crash no report
+ * ever gets sent for. */
+ | 'memory'
+ /** The game itself called `Diagnostics.report` — a failed purchase, a save
+ * that would not write, whatever it considers worth knowing. */
+ | 'game'
+```
+
+## DiagnosticReport — interface
+```
+context: Record<string, unknown> | undefined
+error: unknown
+kind: DiagnosticKind
+message: string
+source: string | undefined
+```
+
+## Diagnostics — const
+```
+ResourceDef<DiagnosticsAPI>
+```
+
+## DiagnosticsAPI — class
+```
+clear: () => void
+dropped: number
+events: readonly DiagnosticEvent[]
+flush: () => void
+report: (report: DiagnosticReport) => void
+reportError: (kind: DiagnosticReport["kind"], error: unknown, source?: string) => void
+setSink: (sink: DiagnosticsSink | null) => void
+tick: (deltaSeconds: number) => void
+static new (options?: DiagnosticsOptions): DiagnosticsAPI
+static prototype: DiagnosticsAPI
+```
+
+## DiagnosticsOptions — interface
+```
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsPlugin — class
+```
+build: (app: App) => void
+cleanup: (app: App) => void
+name: string
+static new (options_?: DiagnosticsPluginOptions): DiagnosticsPlugin
+static prototype: DiagnosticsPlugin
+```
+
+## DiagnosticsPluginOptions — interface
+```
+captureLevel: LogLevel | undefined
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsSink — type
+```
+(events: readonly DiagnosticEvent[]) => void
+```
+
## DialogHandle — interface
```
close: () => void
@@ -4220,6 +4307,7 @@ getStorageSync: (key: string) => unknown
getSystemInfoSync: () => MiniGameSystemInfo
loadSubpackage: ((opts: { name: string; success?: () => void; fail?: (err: unknown) => void; complete?: () => void; }) => void) | undefined
login: ((opts: { success?: (res: { code: string; }) => void; fail?: (err: unknown) => void; timeout?: number; }) => void) | undefined
+offError: ((cb: (error: string | { message?: string; stack?: string; }) => void) => void) | undefined
offKeyDown: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefined
offKeyUp: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefined
offMemoryWarning: ((cb: () => void) => void) | undefined
@@ -4227,6 +4315,8 @@ offTouchCancel: ((cb: (res: MiniGameTouchEvent) => void) => void) | undefined
offTouchEnd: (cb: (res: MiniGameTouchEvent) => void) => void
offTouchMove: (cb: (res: MiniGameTouchEvent) => void) => void
offTouchStart: (cb: (res: MiniGameTouchEvent) => void) => void
+offUnhandledRejection: ((cb: (res: { reason?: unknown; }) => void) => void) | undefined
+onError: ((cb: (error: string | { message?: string; stack?: string; }) => void) => void) | undefined
onHide: ((cb: () => void) => void) | undefined
onKeyDown: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefined
onKeyUp: ((cb: (res: MiniGameKeyEvent) => void) => void) | undefined
@@ -4237,6 +4327,7 @@ onTouchCancel: ((cb: (res: MiniGameTouchEvent) => void) => void) | undefined
onTouchEnd: (cb: (res: MiniGameTouchEvent) => void) => void
onTouchMove: (cb: (res: MiniGameTouchEvent) => void) => void
onTouchStart: (cb: (res: MiniGameTouchEvent) => void) => void
+onUnhandledRejection: ((cb: (res: { reason?: unknown; }) => void) => void) | undefined
removeStorageSync: (key: string) => void
request: (opts: MiniGameRequestOptions) => void
requestMidasPayment: ((opts: { mode: string; offerId: string; buyQuantity: number; zoneId?: string; currencyType?: string; platform?: string; env?: number; success?: () => void; fail?: (err: { errMsg?: string; errCode?: number; }) => void; }) => void) | undefined
@@ -4307,6 +4398,7 @@ name: PlatformName
now: () => number
onMemoryWarning: (callback: () => void) => () => void
onShareRequest: (provide: () => PlatformShareOptions) => void
+onUnhandledError: (callback: (error: unknown) => void) => () => void
openDataCanvas: () => PlatformCanvas | null
openDataPostMessage: (message: Record<string, unknown>) => void
readFile: (path: string) => Promise<ArrayBuffer>
@@ -5101,8 +5193,10 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+onUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefined
openDataCanvas: (() => PlatformCanvas | null) | undefined
openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -9276,6 +9370,11 @@ PluralSelector
(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
```
+## diagnosticsPlugin — const
+```
+DiagnosticsPlugin
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -9416,6 +9515,11 @@ EventBindingPlugin
(grid: NavGrid, start: Cell, goal: Cell, opts?: PathfindOptions): Cell[] | null
```
+## fingerprint — function
+```
+(report: DiagnosticReport): string
+```
+
## flattenPrefab — function
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
@@ -9971,6 +10075,11 @@ Logger
Mesh2DPlugin
```
+## messageOf — function
+```
+(error: unknown): string
+```
+
## migratePrefabData — function
```
(raw: unknown): MigrationResult
@@ -10756,6 +10865,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## stackOf — function
+```
+(error: unknown): string | undefined
+```
+
## statsPlugin — const
```
StatsPlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 9f15b711d..fb9a67063 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: 1416 stable · 17 beta · 1 deprecated
+Symbols: 1429 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2072,6 +2072,93 @@ pixels: Uint8Array<ArrayBufferLike>
width: number
```
+## DiagnosticEvent — interface
+```
+context: Record<string, unknown> | undefined
+count: number
+firstAt: number
+id: string
+kind: DiagnosticKind
+lastAt: number
+message: string
+source: string | undefined
+stack: string | undefined
+```
+
+## DiagnosticKind — type
+```
+| 'engine'
+ /** Reached the host with nobody catching it: `window.onerror`,
+ * `unhandledrejection`, `wx.onError`. Usually game code outside a system —
+ * a callback, a promise, a timer. */
+ | 'unhandled'
+ /** The GPU took the context away (backgrounded, driver reset, too many
+ * contexts). The frame after this one draws nothing. */
+ | 'context-lost'
+ /** The OS says memory is running out. Not yet a failure — it is the warning
+ * that arrives before the process is killed, which is the crash no report
+ * ever gets sent for. */
+ | 'memory'
+ /** The game itself called `Diagnostics.report` — a failed purchase, a save
+ * that would not write, whatever it considers worth knowing. */
+ | 'game'
+```
+
+## DiagnosticReport — interface
+```
+context: Record<string, unknown> | undefined
+error: unknown
+kind: DiagnosticKind
+message: string
+source: string | undefined
+```
+
+## Diagnostics — const
+```
+ResourceDef<DiagnosticsAPI>
+```
+
+## DiagnosticsAPI — class
+```
+clear: () => void
+dropped: number
+events: readonly DiagnosticEvent[]
+flush: () => void
+report: (report: DiagnosticReport) => void
+reportError: (kind: DiagnosticReport["kind"], error: unknown, source?: string) => void
+setSink: (sink: DiagnosticsSink | null) => void
+tick: (deltaSeconds: number) => void
+static new (options?: DiagnosticsOptions): DiagnosticsAPI
+static prototype: DiagnosticsAPI
+```
+
+## DiagnosticsOptions — interface
+```
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsPlugin — class
+```
+build: (app: App) => void
+cleanup: (app: App) => void
+name: string
+static new (options_?: DiagnosticsPluginOptions): DiagnosticsPlugin
+static prototype: DiagnosticsPlugin
+```
+
+## DiagnosticsPluginOptions — interface
+```
+captureLevel: LogLevel | undefined
+flushIntervalSec: number | undefined
+maxDistinct: number | undefined
+```
+
+## DiagnosticsSink — type
+```
+(events: readonly DiagnosticEvent[]) => void
+```
+
## DialogHandle — interface
```
close: () => void
@@ -4871,8 +4958,10 @@ name: PlatformName
now: () => number
onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
+onContextLost: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+onUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefined
openDataCanvas: (() => PlatformCanvas | null) | undefined
openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -9058,6 +9147,11 @@ PluralSelector
(node: UINodeData): { h: AnchorAxis | null; v: AnchorAxis | null; }
```
+## diagnosticsPlugin — const
+```
+DiagnosticsPlugin
+```
+
## diffAgainstSource — function
```
(source: PrefabData, instance: readonly ProcessedEntity[], options?: DiffOptions): { overrides: PrefabOverride[]; untracked: ProcessedEntity[]; orphanedSourceIds: PrefabEntityId[]; }
@@ -9198,6 +9292,11 @@ EventBindingPlugin
(grid: NavGrid, start: Cell, goal: Cell, opts?: PathfindOptions): Cell[] | null
```
+## fingerprint — function
+```
+(report: DiagnosticReport): string
+```
+
## flattenPrefab — function
```
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
@@ -9748,6 +9847,11 @@ Logger
Mesh2DPlugin
```
+## messageOf — function
+```
+(error: unknown): string
+```
+
## migratePrefabData — function
```
(raw: unknown): MigrationResult
@@ -10533,6 +10637,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## stackOf — function
+```
+(error: unknown): string | undefined
+```
+
## statsPlugin — const
```
StatsPlugin
diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.ts
index df43568d0..3d940f16e 100644
--- a/sdk/src/app/pluginSets.ts
+++ b/sdk/src/app/pluginSets.ts
@@ -37,14 +37,21 @@ import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from '../ai';
import { eventBindingPlugin } from '../eventBinding';
import { replicationPlugin } from '../net/replication';
import { servicesPlugin } from '../services';
+import { diagnosticsPlugin } from '../diagnostics';
/**
* The simulation: timers/lifecycle, gameplay AI, audio (silent on a host with no
* device), replication, and platform services (ads/share — unavailable on a host
* with no such surface, and gameplay code gates on `Ads.available` the same way
* audio degrades). What an authoritative server runs.
+ *
+ * Diagnostics is FIRST, and that position is the point: it starts listening
+ * before anything else builds, so a plugin that fails on the way up is recorded
+ * rather than being the one failure the reporter was installed too late to see.
+ * It sends nothing anywhere until a game installs a sink.
*/
export const simulationBasePlugins = (): Plugin[] => [
+ diagnosticsPlugin,
timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,
perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
servicesPlugin,
@@ -62,6 +69,7 @@ export const presentationBasePlugins = (): Plugin[] => [
* exactly rather than derived by concatenation).
*/
export const webBasePlugins = (): Plugin[] => [
+ diagnosticsPlugin,
timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,
particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin,
perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index d7052cc5f..d1f837c28 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -144,6 +144,18 @@ export {
type LogHandler,
} from './util/logger';
+// =============================================================================
+// Diagnostics — what went wrong in a game nobody is watching
+// =============================================================================
+
+export {
+ Diagnostics, DiagnosticsAPI,
+ DiagnosticsPlugin, diagnosticsPlugin,
+ fingerprint, messageOf, stackOf,
+ type DiagnosticEvent, type DiagnosticKind, type DiagnosticReport,
+ type DiagnosticsOptions, type DiagnosticsPluginOptions, type DiagnosticsSink,
+} from './diagnostics';
+
// =============================================================================
// GL Debug
// =============================================================================
diff --git a/sdk/src/diagnostics/Diagnostics.ts b/sdk/src/diagnostics/Diagnostics.ts
new file mode 100644
index 000000000..6d52164e4
--- /dev/null
+++ b/sdk/src/diagnostics/Diagnostics.ts
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Diagnostics.ts
+ * @brief What went wrong in a shipped game, aggregated — and deliberately
+ * not sent anywhere the game did not ask for.
+ *
+ * THE ENGINE NEVER PICKS A DESTINATION. There is no default endpoint, no
+ * bundled vendor, and nothing here opens a socket. A game engine that phoned
+ * home by default would be shipping every one of its users' players into a
+ * decision their developer never made, and "it is only error text" is not a
+ * defence — stacks carry file paths, messages carry whatever was interpolated
+ * into them. So the sink is a function the GAME installs, and with none
+ * installed this still does its whole job locally: events aggregate, the
+ * counters are readable, and a debug overlay can show them. Nothing leaves.
+ *
+ * What it collects is what the engine already knew and dropped on the floor:
+ * every `log.error` (see DiagnosticsPlugin — the logger has been a broadcast
+ * for a long time, it just had no listener that outlived the console), plus the
+ * three failures that never reach a log because they happen outside the frame —
+ * unhandled host errors, a lost GL context, and OS memory pressure.
+ *
+ * Two properties make it safe to leave on:
+ *
+ * It cannot flood. Occurrences of one problem collapse into one event with a
+ * count (see events.ts), and the number of DISTINCT events is capped.
+ *
+ * It cannot become the crash. A sink that throws is caught, and — the part
+ * that is easy to miss — its failure is NOT logged, because this listens to
+ * the log and would report its own report forever.
+ */
+import { defineResource } from '../ecs/resource';
+import {
+ fingerprint, messageOf, stackOf,
+ type DiagnosticEvent, type DiagnosticReport,
+} from './events';
+
+/**
+ * Where a game sends its diagnostics. Receives DISTINCT events with counts, not
+ * individual occurrences.
+ *
+ * Called on the game's own thread with whatever has accumulated. It must not
+ * throw — one that does is caught and dropped — and it should not block: a sink
+ * that awaits a network round-trip inside the frame has traded a bug report for
+ * a stutter. Batch and send it yourself.
+ */
+export type DiagnosticsSink = (events: readonly DiagnosticEvent[]) => void;
+
+export interface DiagnosticsOptions {
+ /**
+ * How many distinct problems to track at once. Reached, further NEW problems
+ * are dropped (counted in {@link DiagnosticsAPI.dropped}) while the ones
+ * already known keep counting.
+ *
+ * Keeping the earliest rather than the newest is deliberate: when a game
+ * comes apart it comes apart in cascade, and the first distinct failure is
+ * the one that explains the next fifty. An LRU here would evict the cause
+ * and keep the consequences.
+ */
+ maxDistinct?: number;
+ /** Seconds between handing what has accumulated to the sink. Zero delivers
+ * on the next frame, which is rarely what a network sink wants. */
+ flushIntervalSec?: number;
+}
+
+const DEFAULTS = { maxDistinct: 64, flushIntervalSec: 10 };
+
+export class DiagnosticsAPI {
+ private events_ = new Map<string, DiagnosticEvent>();
+ private sink_: DiagnosticsSink | null = null;
+ private maxDistinct_: number;
+ private flushInterval_: number;
+ private sinceFlush_ = 0;
+ private dropped_ = 0;
+ /** Re-entrancy guard — see the file header. Set while a sink runs, so
+ * anything reported from inside it (or from the logger it touched) is
+ * ignored instead of recursing. */
+ private inSink_ = false;
+
+ constructor(options: DiagnosticsOptions = {}) {
+ this.maxDistinct_ = Math.max(1, options.maxDistinct ?? DEFAULTS.maxDistinct);
+ this.flushInterval_ = Math.max(0, options.flushIntervalSec ?? DEFAULTS.flushIntervalSec);
+ }
+
+ /**
+ * Install where diagnostics go, or `null` to stop sending (events still
+ * aggregate locally). Installing a sink hands it whatever has already
+ * accumulated — a game that installs one after boot does not lose the boot.
+ */
+ setSink(sink: DiagnosticsSink | null): void {
+ this.sink_ = sink;
+ if (sink && this.events_.size > 0) this.flush();
+ }
+
+ /** Report a problem. Repeats of one already seen increment its count. */
+ report(report: DiagnosticReport): void {
+ if (this.inSink_) return;
+ const id = fingerprint(report);
+ const now = Date.now();
+ const existing = this.events_.get(id);
+ if (existing) {
+ existing.count++;
+ existing.lastAt = now;
+ // The newest context wins: for a repeating failure, the state it is
+ // in NOW is the one someone will try to reproduce.
+ if (report.context) existing.context = report.context;
+ return;
+ }
+ if (this.events_.size >= this.maxDistinct_) {
+ this.dropped_++;
+ return;
+ }
+ const event: DiagnosticEvent = {
+ kind: report.kind,
+ id,
+ message: report.message,
+ count: 1,
+ firstAt: now,
+ lastAt: now,
+ };
+ if (report.source) event.source = report.source;
+ const stack = stackOf(report.error);
+ if (stack) event.stack = stack;
+ if (report.context) event.context = report.context;
+ this.events_.set(id, event);
+ }
+
+ /** Report something thrown, taking the message and stack off it. */
+ reportError(kind: DiagnosticReport['kind'], error: unknown, source?: string): void {
+ this.report({ kind, message: messageOf(error), error, source });
+ }
+
+ /** The distinct problems seen since the last flush, oldest first. */
+ get events(): readonly DiagnosticEvent[] {
+ return [...this.events_.values()];
+ }
+
+ /** New problems that were not tracked because {@link DiagnosticsOptions.maxDistinct}
+ * was reached. A non-zero value here means the report is incomplete, and a
+ * sink should say so rather than let it read as the whole picture. */
+ get dropped(): number {
+ return this.dropped_;
+ }
+
+ /**
+ * Hand everything accumulated to the sink and start a new window.
+ *
+ * Clears even when there is no sink: the alternative is a game that never
+ * installs one accumulating counts forever, and a count since boot is not
+ * what the API promises. What survives with no sink is the aggregation, not
+ * an unbounded history.
+ */
+ flush(): void {
+ this.sinceFlush_ = 0;
+ if (this.events_.size === 0) return;
+ const batch = [...this.events_.values()];
+ this.events_.clear();
+ this.dropped_ = 0;
+ const sink = this.sink_;
+ if (!sink) return;
+ this.inSink_ = true;
+ try {
+ sink(batch);
+ } catch {
+ // A failing sink is not a reason to fail a frame, and reporting it
+ // would be reporting into the thing that just broke.
+ } finally {
+ this.inSink_ = false;
+ }
+ }
+
+ /** Advance the flush clock. Driven by the plugin's system, not a timer —
+ * a background tab or a suspended mini-game should not be flushing. */
+ tick(deltaSeconds: number): void {
+ if (this.events_.size === 0) return;
+ this.sinceFlush_ += deltaSeconds;
+ if (this.sinceFlush_ >= this.flushInterval_) this.flush();
+ }
+
+ /** Drop everything without sending. */
+ clear(): void {
+ this.events_.clear();
+ this.dropped_ = 0;
+ this.sinceFlush_ = 0;
+ }
+}
+
+export const Diagnostics = defineResource<DiagnosticsAPI>(null!, 'Diagnostics');
diff --git a/sdk/src/diagnostics/DiagnosticsPlugin.ts b/sdk/src/diagnostics/DiagnosticsPlugin.ts
new file mode 100644
index 000000000..b4ead4297
--- /dev/null
+++ b/sdk/src/diagnostics/DiagnosticsPlugin.ts
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file DiagnosticsPlugin.ts
+ * @brief Installs the diagnostics resource and subscribes it to everything
+ * that already knew something had gone wrong.
+ *
+ * Nothing here is a NEW error channel. The engine has had four for a long time
+ * — `app.onError`, `app.onSystemError`, `app.onWasmError`, and the logger — and
+ * a fifth would just be a fifth place to remember to look. Three of those are
+ * single-slot setters that belong to the GAME: taking one would silently
+ * replace whatever the developer had installed, which is a bad trade for a
+ * feature whose whole promise is that it does not get in the way.
+ *
+ * The logger is the one that was already right for this. It has always been a
+ * broadcast (`addHandler`), every error the engine raises goes through it —
+ * including the system-threw path, which logs before it consults either
+ * handler — and adding a listener takes nothing away from anyone. So the bridge
+ * is a `LogHandler`, and the game's own error handlers keep working exactly as
+ * they did.
+ *
+ * That leaves the failures that never reach a log because they happen outside
+ * the frame, which is why the platform grew three optional subscriptions:
+ * uncaught host errors, a lost render context, and OS memory pressure. Each is
+ * absent on the platforms that cannot signal it, and absent is fine — what is
+ * collected degrades, the API does not.
+ *
+ * Flushing is driven by a system rather than a timer. A backgrounded tab or a
+ * suspended mini-game stops stepping, and a diagnostics batch that kept firing
+ * into a frozen host would be reporting from a game that is not running.
+ */
+import type { App, Plugin } from '../app/app';
+import { Schedule, defineSystem } from '../ecs/system';
+import { Time } from '../core-runtime';
+import { log, LogLevel, type LogEntry, type LogHandler } from '../util/logger';
+import {
+ platformOnContextLost, platformOnMemoryWarning, platformOnUnhandledError,
+} from '../platform';
+import { Diagnostics, DiagnosticsAPI, type DiagnosticsOptions } from './Diagnostics';
+
+export interface DiagnosticsPluginOptions extends DiagnosticsOptions {
+ /**
+ * The lowest log level to collect. `Error` by default — a warning is
+ * something the engine handled, and a report full of them buries the one
+ * line that says a texture never loaded. `Warn` is the useful widening when
+ * chasing a specific complaint.
+ */
+ captureLevel?: LogLevel;
+}
+
+/** Bridges the engine's log broadcast into the diagnostics aggregator. */
+class DiagnosticsLogHandler implements LogHandler {
+ constructor(
+ private readonly api_: DiagnosticsAPI,
+ private readonly minLevel_: LogLevel,
+ ) {}
+
+ handle(entry: LogEntry): void {
+ if (entry.level < this.minLevel_) return;
+ this.api_.report({
+ kind: 'engine',
+ message: entry.message,
+ source: entry.category,
+ error: entry.data,
+ });
+ }
+}
+
+export class DiagnosticsPlugin implements Plugin {
+ name = 'Diagnostics';
+
+ private unsubscribes_: (() => void)[] = [];
+ private handler_: DiagnosticsLogHandler | null = null;
+
+ constructor(private readonly options_: DiagnosticsPluginOptions = {}) {}
+
+ build(app: App): void {
+ const api = new DiagnosticsAPI(this.options_);
+ app.insertResource(Diagnostics, api);
+
+ this.handler_ = new DiagnosticsLogHandler(api, this.options_.captureLevel ?? LogLevel.Error);
+ log.addHandler(this.handler_);
+
+ this.unsubscribes_.push(
+ platformOnUnhandledError((error) => api.reportError('unhandled', error)),
+ // No error object and nothing to name: what matters is that it
+ // happened, and when. The frames after it draw nothing.
+ platformOnContextLost(() => api.report({
+ kind: 'context-lost',
+ message: 'The rendering context was lost',
+ })),
+ // Reported rather than acted on — the residency caches already
+ // subscribe to this and trim themselves. What this adds is the
+ // record, because the process being killed a moment later is the
+ // crash that never gets a report of its own.
+ platformOnMemoryWarning(() => api.report({
+ kind: 'memory',
+ message: 'The host warned that memory is running low',
+ })),
+ );
+
+ app.addSystemToSchedule(Schedule.Last, defineSystem(
+ [],
+ () => {
+ const time = app.getResource(Time);
+ app.getResource(Diagnostics)?.tick(time?.delta ?? 0);
+ },
+ { name: 'DiagnosticsFlush' },
+ ));
+ }
+
+ cleanup(app: App): void {
+ for (const unsubscribe of this.unsubscribes_) {
+ try {
+ unsubscribe();
+ } catch { /* a host that cannot unsubscribe is not worth failing shutdown over */ }
+ }
+ this.unsubscribes_ = [];
+ if (this.handler_) {
+ log.removeHandler(this.handler_);
+ this.handler_ = null;
+ }
+ // Last chance to deliver: a game closing is exactly when the report of
+ // why it closed is worth having.
+ app.getResource(Diagnostics)?.flush();
+ }
+}
+
+export const diagnosticsPlugin = new DiagnosticsPlugin();
diff --git a/sdk/src/diagnostics/events.ts b/sdk/src/diagnostics/events.ts
new file mode 100644
index 000000000..9355b82a1
--- /dev/null
+++ b/sdk/src/diagnostics/events.ts
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file events.ts
+ * @brief What a shipped game reports about going wrong, and why it is
+ * AGGREGATED before anyone sees it.
+ *
+ * The failures that matter in a released game are the ones nobody is watching:
+ * a device that loses its GL context, an asset that 404s for players in one
+ * region, a system that throws on frame 12,000. None of them reach the person
+ * who could fix them, because the console they would print to is on a phone.
+ *
+ * The reason this is not simply "send every error somewhere" is the shape those
+ * errors have. A system that throws does it EVERY FRAME — sixty identical
+ * reports a second, from every player at once. Sent one by one that is not
+ * telemetry, it is an outage the engine caused: the network queue grows without
+ * bound, the sink's rate limit trips, and the one distinct error that would have
+ * explained everything arrives after the flood, if at all.
+ *
+ * So the unit here is not the error, it is the DISTINCT error with a count. Two
+ * throws from the same system with the same message are one event seen twice,
+ * carrying `firstAt`/`lastAt`, and the report says "1,842 times over 31s" —
+ * which is more diagnostic than 1,842 copies would be, and is the difference
+ * between a feature that can be left on in production and one that cannot.
+ *
+ * Nothing in this file talks to a network. See `Diagnostics.ts` for why the
+ * engine never picks a destination.
+ */
+
+/** Where an event came from. Not a severity — every kind here is something the
+ * game did not intend, and what differs is who can act on it. */
+export type DiagnosticKind =
+ /**
+ * Anything the engine logged as an error: a system that threw during a
+ * schedule, an asset that would not load, a subsystem that refused to start.
+ *
+ * One kind rather than several, because the split a developer acts on is
+ * carried by `source` (the log category, or the system's name) — and the
+ * alternative was recognizing a system throw by pattern-matching the
+ * sentence the logger happened to print, which would break the first time
+ * anyone rephrased it.
+ */
+ | 'engine'
+ /** Reached the host with nobody catching it: `window.onerror`,
+ * `unhandledrejection`, `wx.onError`. Usually game code outside a system —
+ * a callback, a promise, a timer. */
+ | 'unhandled'
+ /** The GPU took the context away (backgrounded, driver reset, too many
+ * contexts). The frame after this one draws nothing. */
+ | 'context-lost'
+ /** The OS says memory is running out. Not yet a failure — it is the warning
+ * that arrives before the process is killed, which is the crash no report
+ * ever gets sent for. */
+ | 'memory'
+ /** The game itself called `Diagnostics.report` — a failed purchase, a save
+ * that would not write, whatever it considers worth knowing. */
+ | 'game';
+
+/** One distinct problem, however many times it happened. */
+export interface DiagnosticEvent {
+ kind: DiagnosticKind;
+ /** Stable identity across repeats — see {@link fingerprint}. */
+ id: string;
+ message: string;
+ /** The engine subsystem or the system's name, when there is one. */
+ source?: string;
+ stack?: string;
+ /** How many times this exact problem has occurred since it was first seen. */
+ count: number;
+ /** Epoch ms of the first and most recent occurrence. */
+ firstAt: number;
+ lastAt: number;
+ /** Whatever the reporter attached. The engine never puts anything
+ * identifying here, and neither should a game — see the file header of
+ * `Diagnostics.ts`. */
+ context?: Record<string, unknown>;
+}
+
+/** A problem as it is reported, before aggregation gives it a count. */
+export interface DiagnosticReport {
+ kind: DiagnosticKind;
+ message: string;
+ source?: string;
+ /** An Error, or anything thrown — the stack is taken from it when there is
+ * one. Strings and non-Errors are tolerated: `throw 'nope'` is legal JS and
+ * is exactly the kind of code that ships. */
+ error?: unknown;
+ context?: Record<string, unknown>;
+}
+
+/** The stack of anything that was thrown, including the cross-realm case: an
+ * Error from a WeChat sub-context or an iframe fails `instanceof` but still
+ * carries `stack` (the same reason the console log handler checks for it). */
+export function stackOf(error: unknown): string | undefined {
+ if (!error || typeof error !== 'object') return undefined;
+ const stack = (error as { stack?: unknown }).stack;
+ return typeof stack === 'string' ? stack : undefined;
+}
+
+export function messageOf(error: unknown): string {
+ if (typeof error === 'string') return error;
+ if (error && typeof error === 'object') {
+ const message = (error as { message?: unknown }).message;
+ if (typeof message === 'string') return message;
+ }
+ return String(error);
+}
+
+/**
+ * The identity two occurrences of the same problem share.
+ *
+ * Message + source + the first stack frame. The message alone would merge two
+ * unrelated "Cannot read properties of undefined" into one event and hide a
+ * second bug behind the first; the WHOLE stack would split one bug into a dozen
+ * events whenever it is reached through different callers, which is the failure
+ * that makes a crash reporter useless at exactly the moment it is needed.
+ *
+ * Numbers in the message are normalized away, because an error carrying an
+ * entity id or a frame count would otherwise be a brand-new problem every time
+ * it happened.
+ */
+export function fingerprint(report: DiagnosticReport): string {
+ const frame = firstFrame(stackOf(report.error));
+ return [report.kind, report.source ?? '', normalize(report.message), frame].join('|');
+}
+
+const normalize = (message: string): string =>
+ message.replace(/\b\d[\d.]*\b/g, '#').replace(/\s+/g, ' ').trim().slice(0, 200);
+
+function firstFrame(stack: string | undefined): string {
+ if (!stack) return '';
+ for (const line of stack.split('\n')) {
+ const trimmed = line.trim();
+ // Skip the header ("Error: message") — V8 puts it first, other engines
+ // do not, so it is recognized rather than counted past.
+ if (!trimmed || (!trimmed.startsWith('at ') && !trimmed.includes('@'))) continue;
+ return trimmed.slice(0, 200);
+ }
+ return '';
+}
diff --git a/sdk/src/diagnostics/index.ts b/sdk/src/diagnostics/index.ts
new file mode 100644
index 000000000..fb9aa6780
--- /dev/null
+++ b/sdk/src/diagnostics/index.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export {
+ Diagnostics, DiagnosticsAPI,
+ type DiagnosticsOptions, type DiagnosticsSink,
+} from './Diagnostics';
+export {
+ DiagnosticsPlugin, diagnosticsPlugin,
+ type DiagnosticsPluginOptions,
+} from './DiagnosticsPlugin';
+export {
+ fingerprint, messageOf, stackOf,
+ type DiagnosticEvent, type DiagnosticKind, type DiagnosticReport,
+} from './events';
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index f151cee60..7c1bdbac1 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -222,6 +222,24 @@ export function platformOnMemoryWarning(callback: () => void): () => void {
return p.onMemoryWarning ? p.onMemoryWarning(callback) : () => {};
}
+/** Subscribe to errors that reached the host uncaught (window.onerror /
+ * wx.onError and the promise equivalents). Returns an unsubscribe. A platform
+ * without the signal never fires; tolerates an uninitialized platform (tests). */
+export function platformOnUnhandledError(callback: (error: unknown) => void): () => void {
+ if (!isPlatformInitialized()) return () => {};
+ const p = getPlatform();
+ return p.onUnhandledError ? p.onUnhandledError(callback) : () => {};
+}
+
+/** Subscribe to the render context being lost. Returns an unsubscribe. A
+ * platform whose surface cannot be lost never fires; tolerates an
+ * uninitialized platform (tests). */
+export function platformOnContextLost(callback: () => void): () => void {
+ if (!isPlatformInitialized()) return () => {};
+ const p = getPlatform();
+ return p.onContextLost ? p.onContextLost(callback) : () => {};
+}
+
/** Subscribe to the app returning to foreground / going to background — the
* native shell's push signals (no DOM visibility on native). Return an
* unsubscribe; a platform without the signal never fires. Tolerates an
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index d22609715..2a4160d6a 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -48,6 +48,8 @@ export {
platformReadCacheFile,
platformWriteCacheFile,
platformOnMemoryWarning,
+ platformOnUnhandledError,
+ platformOnContextLost,
platformOnAppShow,
platformOnAppHide,
platformGetStorageItem,
diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.ts
index 3cdcc90e6..63a89ed5f 100644
--- a/sdk/src/platform/minigame/adapter.ts
+++ b/sdk/src/platform/minigame/adapter.ts
@@ -322,6 +322,31 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
return () => off?.call(this.g_, listener);
}
+ /**
+ * The host's two uncaught channels, each subscribed only if this base
+ * library has it.
+ *
+ * A script error arrives as a STRING on WeChat rather than an Error, so the
+ * stack is in the text and there is nothing to take a `.stack` off — which
+ * is why the diagnostics layer tolerates non-Errors instead of assuming one.
+ * `onUnhandledRejection` is newer than `onError`; a base without it loses
+ * only the promise half.
+ */
+ onUnhandledError(callback: (error: unknown) => void): () => void {
+ const onError = this.g_.onError;
+ const offError = this.g_.offError;
+ const onRejection = this.g_.onUnhandledRejection;
+ const offRejection = this.g_.offUnhandledRejection;
+ const errorListener = (e: string | { message?: string; stack?: string }): void => { callback(e); };
+ const rejectionListener = (res: { reason?: unknown }): void => { callback(res?.reason ?? res); };
+ if (onError) onError.call(this.g_, errorListener);
+ if (onRejection) onRejection.call(this.g_, rejectionListener);
+ return () => {
+ if (onError) offError?.call(this.g_, errorListener);
+ if (onRejection) offRejection?.call(this.g_, rejectionListener);
+ };
+ }
+
createCanvas(width: number, height: number): PlatformCanvas {
// One honest cast: MiniGameCanvas.getContext returns `unknown`, so it is not
// structurally assignable to PlatformCanvas's typed 2D getContext.
diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.ts
index f9f5155a0..f300fa94d 100644
--- a/sdk/src/platform/minigame/api.ts
+++ b/sdk/src/platform/minigame/api.ts
@@ -237,6 +237,15 @@ export interface MiniGameGlobal {
onMemoryWarning?(cb: () => void): void;
offMemoryWarning?(cb: () => void): void;
+ /** Errors that reached the host uncaught. WeChat reports the script error as
+ * a string (plus a structured second argument on newer bases, which this
+ * does not rely on); an unhandled rejection arrives separately, and only on
+ * bases new enough to have it — hence both optional. */
+ onError?(cb: (error: string | { message?: string; stack?: string }) => void): void;
+ offError?(cb: (error: string | { message?: string; stack?: string }) => void): void;
+ onUnhandledRejection?(cb: (res: { reason?: unknown }) => void): void;
+ offUnhandledRejection?(cb: (res: { reason?: unknown }) => void): void;
+
onShow?(cb: () => void): void;
onHide?(cb: () => void): void;
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 4820ecf16..1ae443b0e 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -479,6 +479,32 @@ export interface PlatformAdapter {
* omit it. Residency caches subscribe to drop their evictable entries. */
onMemoryWarning?(callback: () => void): () => void;
+ /**
+ * Subscribe to errors that reached the host with nobody catching them —
+ * `window.onerror` + `unhandledrejection` on the web, `wx.onError` +
+ * `wx.onUnhandledRejection` on a mini-game. Returns an unsubscribe.
+ *
+ * This is the only channel for the failures that happen OUTSIDE a system:
+ * a throw in a `setTimeout`, a promise nobody awaited, a callback from the
+ * host. The engine's own errors go through the logger and need no platform.
+ * Optional — a platform without the signal simply never fires, and the
+ * diagnostics plugin still collects everything else.
+ */
+ onUnhandledError?(callback: (error: unknown) => void): () => void;
+
+ /**
+ * Subscribe to the GPU taking the rendering context away — backgrounding,
+ * a driver reset, too many live contexts on the page. Returns an
+ * unsubscribe.
+ *
+ * Worth its own channel because it is invisible from everywhere else: no
+ * error is thrown and no log is written, the frames simply stop containing
+ * anything. A game whose players report "it went black" has no other way to
+ * find out that this is what happened. Optional — a platform whose surface
+ * cannot be lost (native, node) omits it.
+ */
+ onContextLost?(callback: () => void): () => void;
+
/** App foreground/background signals, for platforms with no DOM visibility
* event. The native shell pushes them through its bridge; the Lifecycle
* plugin subscribes and auto-pauses on hide. Web/WeChat read visibility from
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index 70014ca04..8be6eca8c 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -304,6 +304,43 @@ class WebPlatformAdapter implements PlatformAdapter {
return typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;
}
+ /**
+ * Both ways an error reaches the browser with nobody holding it.
+ *
+ * `error` carries the thrown value on the event; `unhandledrejection`
+ * carries the rejection reason, which is the more common one in practice —
+ * a promise chain in game code with no `.catch` fails completely silently
+ * otherwise. Neither is prevented: this observes, and the browser still
+ * logs to the console the way the developer expects.
+ */
+ onUnhandledError(callback: (error: unknown) => void): () => void {
+ if (typeof window === 'undefined') return () => {};
+ const onError = (e: ErrorEvent): void => { callback(e.error ?? e.message); };
+ const onRejection = (e: PromiseRejectionEvent): void => { callback(e.reason); };
+ window.addEventListener('error', onError);
+ window.addEventListener('unhandledrejection', onRejection);
+ return () => {
+ window.removeEventListener('error', onError);
+ window.removeEventListener('unhandledrejection', onRejection);
+ };
+ }
+
+ /**
+ * Context loss, without needing to be told which canvas.
+ *
+ * `webglcontextlost` does not bubble, so a listener on `window` looks like
+ * it could not work — but a non-bubbling event still travels the CAPTURE
+ * phase down to its target, and `window` is the first stop. One listener
+ * therefore sees every canvas on the page, including one the engine did not
+ * create, and the plugin needs no canvas handed to it.
+ */
+ onContextLost(callback: () => void): () => void {
+ if (typeof window === 'undefined') return () => {};
+ const onLost = (): void => { callback(); };
+ window.addEventListener('webglcontextlost', onLost, true);
+ return () => window.removeEventListener('webglcontextlost', onLost, true);
+ }
+
clearStorage(prefix: string): void {
const toRemove: string[] = [];
for (let i = 0; i < localStorage.length; i++) {
diff --git a/sdk/tests/diagnostics.test.ts b/sdk/tests/diagnostics.test.ts
new file mode 100644
index 000000000..50fe481b8
--- /dev/null
+++ b/sdk/tests/diagnostics.test.ts
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Diagnostics: the properties that decide whether this can be left on.
+ *
+ * A crash reporter in a game engine is judged on how it behaves when things are
+ * already going badly — a system throwing every frame, a sink that is itself
+ * broken, an error whose message is different every time. Each of those has a
+ * naive implementation that works fine in a demo and takes the game down in
+ * production, so they are what this file is about.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { DiagnosticsAPI } from '../src/diagnostics/Diagnostics';
+import { fingerprint, messageOf, stackOf } from '../src/diagnostics/events';
+import type { DiagnosticEvent } from '../src/diagnostics/events';
+
+const drain = (): { sink: (e: readonly DiagnosticEvent[]) => void; batches: DiagnosticEvent[][] } => {
+ const batches: DiagnosticEvent[][] = [];
+ return { sink: (e) => { batches.push([...e]); }, batches };
+};
+
+describe('aggregation', () => {
+ it('collapses repeats of one problem into a single event with a count', () => {
+ const api = new DiagnosticsAPI();
+ for (let i = 0; i < 500; i++) {
+ api.report({ kind: 'engine', message: 'System "Move" threw an error', source: 'app' });
+ }
+ expect(api.events).toHaveLength(1);
+ expect(api.events[0].count).toBe(500);
+ expect(api.events[0].lastAt).toBeGreaterThanOrEqual(api.events[0].firstAt);
+ });
+
+ it('keeps genuinely different problems apart', () => {
+ const api = new DiagnosticsAPI();
+ api.report({ kind: 'engine', message: 'texture missing', source: 'assets' });
+ api.report({ kind: 'engine', message: 'texture missing', source: 'render' });
+ api.report({ kind: 'unhandled', message: 'texture missing', source: 'assets' });
+ expect(api.events).toHaveLength(3);
+ });
+
+ it('does not treat an id in the message as a new problem every time', () => {
+ // "Entity 41 has no Transform" repeated across a thousand entities is one
+ // bug, and a reporter that files a thousand events has hidden it.
+ const api = new DiagnosticsAPI();
+ for (let id = 0; id < 100; id++) {
+ api.report({ kind: 'engine', message: `Entity ${id} has no Transform`, source: 'app' });
+ }
+ expect(api.events).toHaveLength(1);
+ expect(api.events[0].count).toBe(100);
+ });
+
+ it('splits on the throw site, not on the whole stack', () => {
+ // Same message, same first frame, different callers below it: one bug.
+ const deep = (tail: string): Error => {
+ const e = new Error('boom');
+ e.stack = `Error: boom\n at doWork (game.js:10:5)\n at ${tail}`;
+ return e;
+ };
+ const api = new DiagnosticsAPI();
+ api.report({ kind: 'engine', message: 'boom', error: deep('a (game.js:1:1)') });
+ api.report({ kind: 'engine', message: 'boom', error: deep('b (game.js:2:2)') });
+ expect(api.events).toHaveLength(1);
+
+ // A different throw site IS a different bug.
+ const other = new Error('boom');
+ other.stack = 'Error: boom\n at somewhereElse (game.js:99:1)';
+ api.report({ kind: 'engine', message: 'boom', error: other });
+ expect(api.events).toHaveLength(2);
+ });
+
+ it('caps distinct events, keeping the cause rather than the cascade', () => {
+ const api = new DiagnosticsAPI({ maxDistinct: 3 });
+ for (let i = 0; i < 10; i++) api.report({ kind: 'engine', message: `problem ${i}`, source: `s${i}` });
+ expect(api.events.map((e) => e.source)).toEqual(['s0', 's1', 's2']);
+ expect(api.dropped).toBe(7);
+ // A capped aggregator still counts what it already knows.
+ api.report({ kind: 'engine', message: 'problem 0', source: 's0' });
+ expect(api.events[0].count).toBe(2);
+ });
+
+ it('carries the newest context, since that is the state to reproduce', () => {
+ const api = new DiagnosticsAPI();
+ api.report({ kind: 'game', message: 'save failed', context: { attempt: 1 } });
+ api.report({ kind: 'game', message: 'save failed', context: { attempt: 2 } });
+ expect(api.events[0].context).toEqual({ attempt: 2 });
+ expect(api.events[0].count).toBe(2);
+ });
+});
+
+describe('the sink', () => {
+ it('is absent by default — the engine picks no destination', () => {
+ const api = new DiagnosticsAPI();
+ api.report({ kind: 'game', message: 'x' });
+ // Still aggregated and readable locally; simply not sent.
+ expect(api.events).toHaveLength(1);
+ expect(() => api.flush()).not.toThrow();
+ });
+
+ it('receives distinct events with counts, not occurrences', () => {
+ const { sink, batches } = drain();
+ const api = new DiagnosticsAPI();
+ api.setSink(sink);
+ for (let i = 0; i < 3; i++) api.report({ kind: 'engine', message: 'same' });
+ api.flush();
+ expect(batches).toHaveLength(1);
+ expect(batches[0]).toHaveLength(1);
+ expect(batches[0][0].count).toBe(3);
+ });
+
+ it('hands over what accumulated before it was installed', () => {
+ const { sink, batches } = drain();
+ const api = new DiagnosticsAPI();
+ api.report({ kind: 'engine', message: 'happened during boot' });
+ api.setSink(sink);
+ expect(batches[0][0].message).toBe('happened during boot');
+ });
+
+ it('starts a new window after a flush', () => {
+ const { sink, batches } = drain();
+ const api = new DiagnosticsAPI();
+ api.setSink(sink);
+ api.report({ kind: 'engine', message: 'a' });
+ api.flush();
+ api.report({ kind: 'engine', message: 'a' });
+ api.flush();
+ expect(batches).toHaveLength(2);
+ expect(batches[1][0].count).toBe(1); // not 2 — the window restarted
+ });
+
+ it('survives a sink that throws, and does not report its failure', () => {
+ // The trap this guards: reporting a broken sink goes through the logger,
+ // the logger is what feeds this, and the game spins until it dies.
+ const api = new DiagnosticsAPI();
+ let calls = 0;
+ api.setSink(() => { calls++; throw new Error('the reporting service is down'); });
+ api.report({ kind: 'engine', message: 'a real bug' });
+ expect(() => api.flush()).not.toThrow();
+ expect(calls).toBe(1);
+ expect(api.events).toHaveLength(0); // the batch is gone, not retried forever
+ });
+
+ it('ignores anything reported from inside the sink', () => {
+ const api = new DiagnosticsAPI();
+ let depth = 0;
+ let maxDepth = 0;
+ api.setSink(() => {
+ depth++;
+ maxDepth = Math.max(maxDepth, depth);
+ api.report({ kind: 'engine', message: 'reported from inside the sink' });
+ api.flush();
+ depth--;
+ });
+ api.report({ kind: 'engine', message: 'first' });
+ api.flush();
+ expect(maxDepth).toBe(1);
+ expect(api.events).toHaveLength(0);
+ });
+});
+
+describe('flush cadence', () => {
+ it('flushes on the engine clock, not a timer', () => {
+ const { sink, batches } = drain();
+ const api = new DiagnosticsAPI({ flushIntervalSec: 10 });
+ api.setSink(sink);
+ api.report({ kind: 'engine', message: 'a' });
+ api.tick(4);
+ expect(batches).toHaveLength(0);
+ api.tick(4);
+ expect(batches).toHaveLength(0);
+ api.tick(4);
+ expect(batches).toHaveLength(1);
+ });
+
+ it('does not tick the clock forward with nothing to send', () => {
+ const { sink, batches } = drain();
+ const api = new DiagnosticsAPI({ flushIntervalSec: 1 });
+ api.setSink(sink);
+ api.tick(60); // an hour of quiet
+ api.report({ kind: 'engine', message: 'a' });
+ api.tick(0.5);
+ expect(batches).toHaveLength(0); // …does not make this urgent
+ api.tick(0.6);
+ expect(batches).toHaveLength(1);
+ });
+});
+
+describe('what was thrown', () => {
+ it('tolerates a thrown non-Error, which is legal and does ship', () => {
+ const api = new DiagnosticsAPI();
+ api.reportError('unhandled', 'nope');
+ expect(api.events[0].message).toBe('nope');
+ expect(api.events[0].stack).toBeUndefined();
+ });
+
+ it('reads a cross-realm error, which fails instanceof but has the fields', () => {
+ // A WeChat sub-context or an iframe throws these; `instanceof Error` is
+ // false and JSON.stringify renders `{}`.
+ const alien = { message: 'from another realm', stack: 'Error: from another realm\n at x (a.js:1:1)' };
+ expect(messageOf(alien)).toBe('from another realm');
+ expect(stackOf(alien)).toContain('at x');
+ const api = new DiagnosticsAPI();
+ api.reportError('unhandled', alien, 'host');
+ expect(api.events[0].source).toBe('host');
+ expect(api.events[0].stack).toBeDefined();
+ });
+
+ it('fingerprints identically for the same problem reported twice', () => {
+ const report = { kind: 'engine' as const, message: 'x', source: 'app' };
+ expect(fingerprint(report)).toBe(fingerprint({ ...report }));
+ });
+});
+
+describe('the log bridge', () => {
+ let api: DiagnosticsAPI;
+ let plugin: { build: (app: unknown) => void; cleanup: (app: unknown) => void };
+
+ beforeEach(async () => {
+ const { DiagnosticsPlugin } = await import('../src/diagnostics/DiagnosticsPlugin');
+ const p = new DiagnosticsPlugin();
+ const resources = new Map<unknown, unknown>();
+ const app = {
+ insertResource: (key: unknown, value: unknown) => { resources.set(key, value); },
+ getResource: (key: unknown) => resources.get(key),
+ addSystemToSchedule: () => {},
+ };
+ p.build(app as never);
+ const { Diagnostics } = await import('../src/diagnostics/Diagnostics');
+ api = app.getResource(Diagnostics) as DiagnosticsAPI;
+ plugin = { build: () => {}, cleanup: () => p.cleanup(app as never) };
+ });
+
+ afterEach(() => { plugin.cleanup(null); });
+
+ it('collects every engine error without taking a handler from the game', async () => {
+ const { log } = await import('../src/util/logger');
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ log.error('physics', 'the world could not step', new Error('bad body'));
+ spy.mockRestore();
+ expect(api.events).toHaveLength(1);
+ expect(api.events[0].source).toBe('physics');
+ expect(api.events[0].kind).toBe('engine');
+ });
+
+ it('leaves warnings out by default — a handled problem is not a report', async () => {
+ const { log } = await import('../src/util/logger');
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ log.warn('assets', 'texture missing, using placeholder');
+ spy.mockRestore();
+ expect(api.events).toHaveLength(0);
+ });
+
+ it('stops listening once the plugin is cleaned up', async () => {
+ const { log } = await import('../src/util/logger');
+ plugin.cleanup(null);
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ log.error('physics', 'after shutdown');
+ spy.mockRestore();
+ expect(api.events).toHaveLength(0);
+ });
+});