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(net): replication takes a link it can trust, or none

yhhba1fd75a26e6
diff --git a/docs/astro/src/content/docs/scripting/networking.mdx b/docs/astro/src/content/docs/scripting/networking.mdx
index c72b3681f..e6207acd2 100644
--- a/docs/astro/src/content/docs/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/scripting/networking.mdx
@@ -113,6 +113,11 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // per-tick input uplin
live entity sends its full state; removing one removes it from every ghost.
Spawn → component add → updates → component remove → despawn all cross the
wire, and arrive in the order the authority sent them.
+- **The link must be reliable and ordered**: the client applies what arrives in
+ arrival order, because that is the authority's order. `startServer().attachConnection`
+ and `Net.connect` take a `ReliableOrderedTransport` — every built-in socket is
+ one; a transport you write yourself declares `delivery: 'reliable-ordered'`,
+ and one that cannot make that promise is a compile error rather than a desync.
- **Ownership**: `Replicated.owner` routes a connection's `sendInput` commands to
its entities; `client.ownsEntity(e)` answers "is this ghost mine".
- **Editor preview**: pick **2–4 Players** in the Play-mode dropdown — a listen
diff --git a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
index cd46c6534..726fc01c0 100644
--- a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
@@ -109,6 +109,10 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // 每 tick 输入上
- **结构本身也会复制,不只是值**:给活着的实体加一个 replicated 组件会发送
它的完整状态,移除则会从每个 ghost 上移除。spawn → 组件加入 → 更新 →
组件移除 → despawn 全部过线,并按权威端发出的顺序抵达。
+- **链路必须可靠且有序**:客户端按到达顺序应用收到的东西,因为那就是权威端
+ 的顺序。`attachConnection` 和 `Net.connect` 收的是 `ReliableOrderedTransport`
+ ——内置 socket 都是;自己写的 transport 声明 `delivery: 'reliable-ordered'`,
+ 做不到这个保证的会是编译错误,而不是一次静默失步。
- **归属**:`Replicated.owner` 把某连接的 `sendInput` 命令路由到它的实体;
`client.ownsEntity(e)` 回答"这个 ghost 是不是我的"。
- **编辑器预览**:在 Play 模式下拉里选 **2–4 Players**——listen server 和
diff --git a/examples/multiplayer-arena/server/main.ts b/examples/multiplayer-arena/server/main.ts
index b6df39ed4..a104487f0 100644
--- a/examples/multiplayer-arena/server/main.ts
+++ b/examples/multiplayer-arena/server/main.ts
@@ -23,7 +23,7 @@
import { WebSocketServer, type WebSocket } from 'ws';
import {
loadEsengineModule, createHeadlessApp, runHeadless,
- flushPendingRegistrations, Net, type NetTransport,
+ flushPendingRegistrations, Net, type ReliableOrderedTransport,
} from 'esengine/node';
import { arena } from '../src/net';
// Side-effect import: `src/main.ts` registers the arena's systems at module
@@ -41,12 +41,12 @@ interface ServerOptions {
}
/**
- * One accepted `ws` connection as a {@link NetTransport}. The replication layer
- * asks a transport for exactly two things — send a frame, subscribe to frames —
- * so any ordered, reliable link can carry a session; `ws` is simply the one a
- * browser can dial.
+ * One accepted `ws` connection, as the transport replication asks for: send a
+ * frame, subscribe to frames, and a claim that the link loses and reorders
+ * nothing. A WebSocket does neither, so the claim is honest here; a transport
+ * that cannot make it is refused at compile time rather than desynchronizing.
*/
-function wsTransport(socket: WebSocket): NetTransport {
+function wsTransport(socket: WebSocket): ReliableOrderedTransport {
const handlers = new Set<(data: string | ArrayBuffer) => void>();
socket.on('message', (data: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
// Binary frames are the delta stream and must reach the channel as an
@@ -56,6 +56,7 @@ function wsTransport(socket: WebSocket): NetTransport {
for (const handler of [...handlers]) handler(frame);
});
return {
+ delivery: 'reliable-ordered',
send: (data) => socket.send(data),
on: (_event, handler) => {
handlers.add(handler);
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 965144976..7115d8323 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: 113 public · 84 beta · 1514 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1515 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3519,6 +3519,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -4593,6 +4594,7 @@ static prototype: MeasuredLinearLayoutProvider
## MemoryTransport — class @experimental
```
+delivery: "reliable-ordered"
dropPending: () => void
flush: (limit?: number) => void
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
@@ -4720,6 +4722,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class @experimental
```
close: () => void
+delivery: "reliable-ordered"
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
@@ -4738,6 +4741,7 @@ toVersion: string
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -5094,7 +5098,7 @@ ComponentDef<{}>
## NetSession — class @experimental
```
client: ReplicationClient | null
-connect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
+connect: (transport: ReliableOrderedTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
role: NetRoleKind
server: ReplicationServer | null
startServer: () => ReplicationServer
@@ -5753,6 +5757,7 @@ title: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -6346,6 +6351,13 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## ReliableOrderedTransport — interface @experimental
+```
+delivery: "reliable-ordered"
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
## Removed — function @experimental
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -6492,7 +6504,7 @@ owner: number
```
@internal setFixedDelta: (dt: number) => void
applyPending: () => void
-connect: (transport: NetTransport) => Promise<void>
+connect: (transport: ReliableOrderedTransport) => Promise<void>
connected: boolean
connectionId: number
disconnect: () => void
@@ -6518,7 +6530,7 @@ static prototype: ReplicationPlugin
## ReplicationServer — class @experimental
```
-attachConnection: (transport: NetTransport) => number
+attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
@@ -9418,6 +9430,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 539ca47ab..f00436f7a 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: 113 public · 89 beta · 1533 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1534 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3527,6 +3527,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -4606,6 +4607,7 @@ resolveComponentHeap: (cppName: string) => ComponentHeapResolver | null
## MemoryTransport — class @experimental
```
+delivery: "reliable-ordered"
dropPending: () => void
flush: (limit?: number) => void
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
@@ -4733,6 +4735,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class @experimental
```
close: () => void
+delivery: "reliable-ordered"
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
@@ -4751,6 +4754,7 @@ toVersion: string
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -5272,7 +5276,7 @@ ComponentDef<{}>
## NetSession — class @experimental
```
client: ReplicationClient | null
-connect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
+connect: (transport: ReliableOrderedTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
role: NetRoleKind
server: ReplicationServer | null
startServer: () => ReplicationServer
@@ -5936,6 +5940,7 @@ title: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -6539,6 +6544,13 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## ReliableOrderedTransport — interface @experimental
+```
+delivery: "reliable-ordered"
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
## Removed — function @experimental
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -6685,7 +6697,7 @@ owner: number
```
@internal setFixedDelta: (dt: number) => void
applyPending: () => void
-connect: (transport: NetTransport) => Promise<void>
+connect: (transport: ReliableOrderedTransport) => Promise<void>
connected: boolean
connectionId: number
disconnect: () => void
@@ -6711,7 +6723,7 @@ static prototype: ReplicationPlugin
## ReplicationServer — class @experimental
```
-attachConnection: (transport: NetTransport) => number
+attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
@@ -9611,6 +9623,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 5a839901b..f2356bc08 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: 113 public · 86 beta · 1513 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1514 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3514,6 +3514,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -4588,6 +4589,7 @@ static prototype: MeasuredLinearLayoutProvider
## MemoryTransport — class @experimental
```
+delivery: "reliable-ordered"
dropPending: () => void
flush: (limit?: number) => void
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
@@ -4715,6 +4717,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class @experimental
```
close: () => void
+delivery: "reliable-ordered"
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
@@ -4733,6 +4736,7 @@ toVersion: string
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -5089,7 +5093,7 @@ ComponentDef<{}>
## NetSession — class @experimental
```
client: ReplicationClient | null
-connect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
+connect: (transport: ReliableOrderedTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
role: NetRoleKind
server: ReplicationServer | null
startServer: () => ReplicationServer
@@ -5748,6 +5752,7 @@ title: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -6341,6 +6346,13 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## ReliableOrderedTransport — interface @experimental
+```
+delivery: "reliable-ordered"
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
## Removed — function @experimental
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -6487,7 +6499,7 @@ owner: number
```
@internal setFixedDelta: (dt: number) => void
applyPending: () => void
-connect: (transport: NetTransport) => Promise<void>
+connect: (transport: ReliableOrderedTransport) => Promise<void>
connected: boolean
connectionId: number
disconnect: () => void
@@ -6513,7 +6525,7 @@ static prototype: ReplicationPlugin
## ReplicationServer — class @experimental
```
-attachConnection: (transport: NetTransport) => number
+attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
@@ -9413,6 +9425,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index c188b38e7..14a927ac3 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: 113 public · 84 beta · 1535 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1536 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3514,6 +3514,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -4588,6 +4589,7 @@ static prototype: MeasuredLinearLayoutProvider
## MemoryTransport — class @experimental
```
+delivery: "reliable-ordered"
dropPending: () => void
flush: (limit?: number) => void
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
@@ -4715,6 +4717,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class @experimental
```
close: () => void
+delivery: "reliable-ordered"
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
@@ -4938,6 +4941,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -5335,7 +5339,7 @@ ComponentDef<{}>
## NetSession — class @experimental
```
client: ReplicationClient | null
-connect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
+connect: (transport: ReliableOrderedTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
role: NetRoleKind
server: ReplicationServer | null
startServer: () => ReplicationServer
@@ -5994,6 +5998,7 @@ title: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -6587,6 +6592,13 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## ReliableOrderedTransport — interface @experimental
+```
+delivery: "reliable-ordered"
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
## Removed — function @experimental
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -6733,7 +6745,7 @@ owner: number
```
@internal setFixedDelta: (dt: number) => void
applyPending: () => void
-connect: (transport: NetTransport) => Promise<void>
+connect: (transport: ReliableOrderedTransport) => Promise<void>
connected: boolean
connectionId: number
disconnect: () => void
@@ -6759,7 +6771,7 @@ static prototype: ReplicationPlugin
## ReplicationServer — class @experimental
```
-attachConnection: (transport: NetTransport) => number
+attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
@@ -9665,6 +9677,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 62ecc320e..3ef7785d5 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: 113 public · 84 beta · 1525 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1526 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3514,6 +3514,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -4595,6 +4596,7 @@ static prototype: MeasuredLinearLayoutProvider
## MemoryTransport — class @experimental
```
+delivery: "reliable-ordered"
dropPending: () => void
flush: (limit?: number) => void
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
@@ -4722,6 +4724,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class @experimental
```
close: () => void
+delivery: "reliable-ordered"
on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
@@ -4740,6 +4743,7 @@ toVersion: string
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -5096,7 +5100,7 @@ ComponentDef<{}>
## NetSession — class @experimental
```
client: ReplicationClient | null
-connect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
+connect: (transport: ReliableOrderedTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>
role: NetRoleKind
server: ReplicationServer | null
startServer: () => ReplicationServer
@@ -5755,6 +5759,7 @@ title: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
@@ -6348,6 +6353,13 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## ReliableOrderedTransport — interface @experimental
+```
+delivery: "reliable-ordered"
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
+send: (data: string | ArrayBuffer) => void
+```
+
## Removed — function @experimental
```
<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>
@@ -6494,7 +6506,7 @@ owner: number
```
@internal setFixedDelta: (dt: number) => void
applyPending: () => void
-connect: (transport: NetTransport) => Promise<void>
+connect: (transport: ReliableOrderedTransport) => Promise<void>
connected: boolean
connectionId: number
disconnect: () => void
@@ -6520,7 +6532,7 @@ static prototype: ReplicationPlugin
## ReplicationServer — class @experimental
```
-attachConnection: (transport: NetTransport) => number
+attachConnection: (transport: ReliableOrderedTransport) => number
beginTick: (fixedDelta: number) => void
clientIds: number[]
connectionCount: number
@@ -9441,6 +9453,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
+delivery: "reliable-ordered"
on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 43ac348a3..a2c061541 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -89,6 +89,7 @@ export {
MemoryTransport, createMemoryTransportPair,
MessagePortTransport, type MessagePortLike,
type GameSocketOptions, type SocketReadyState, type NetTransport,
+ type ReliableOrderedTransport,
type NetChannelOptions, type MessageHandler, type RequestHandler,
type BinaryHandler, type PlatformSocket, type PlatformSocketEvents,
type PlatformSocketOptions, type PlatformSocketReadyState,
diff --git a/sdk/src/net/GameSocket.ts b/sdk/src/net/GameSocket.ts
index cc7dd3f67..83e2a082a 100644
--- a/sdk/src/net/GameSocket.ts
+++ b/sdk/src/net/GameSocket.ts
@@ -23,6 +23,8 @@ export class GameSocket implements PlatformSocket {
private sendQueue_: (string | ArrayBuffer)[] = [];
private events_ = new Emitter<PlatformSocketEvents>();
+ /** A WebSocket: nothing is lost and nothing overtakes. */
+ readonly delivery = 'reliable-ordered' as const;
readyState: SocketReadyState = 'closed';
constructor(options: GameSocketOptions) {
diff --git a/sdk/src/net/MemoryTransport.ts b/sdk/src/net/MemoryTransport.ts
index 87613fd97..fe036a355 100644
--- a/sdk/src/net/MemoryTransport.ts
+++ b/sdk/src/net/MemoryTransport.ts
@@ -10,14 +10,18 @@
* interleaving are simulated.
*/
import { Emitter } from '../ecs/emitter';
-import type { NetTransport } from './NetChannel';
+import type { ReliableOrderedTransport } from './NetChannel';
export interface MemoryTransportOptions {
/** Queue outgoing frames until flush() instead of delivering synchronously. */
manualFlush?: boolean;
}
-export class MemoryTransport implements NetTransport {
+export class MemoryTransport implements ReliableOrderedTransport {
+ /** In-process: `flush` delivers the queue in send order, so it models the
+ * real thing rather than being merely convenient. */
+ readonly delivery = 'reliable-ordered' as const;
+
private events_ = new Emitter<{ message: [data: string | ArrayBuffer] }>();
private peer_: MemoryTransport | null = null;
private readonly manualFlush_: boolean;
diff --git a/sdk/src/net/MessagePortTransport.ts b/sdk/src/net/MessagePortTransport.ts
index 1f1f9572d..6ea17e058 100644
--- a/sdk/src/net/MessagePortTransport.ts
+++ b/sdk/src/net/MessagePortTransport.ts
@@ -9,7 +9,7 @@
* messages until the other end attaches, so wiring order is free.
*/
import { Emitter } from '../ecs/emitter';
-import type { NetTransport } from './NetChannel';
+import type { ReliableOrderedTransport } from './NetChannel';
/** The minimal MessagePort surface (structural — works for window and worker
* ports). A real DOM MessagePort types its `onmessage` against the full
@@ -21,7 +21,10 @@ export interface MessagePortLike {
close?(): void;
}
-export class MessagePortTransport implements NetTransport {
+export class MessagePortTransport implements ReliableOrderedTransport {
+ /** A MessagePort is a FIFO between two realms on one machine. */
+ readonly delivery = 'reliable-ordered' as const;
+
private events_ = new Emitter<{ message: [data: string | ArrayBuffer] }>();
private readonly port_: MessagePortLike;
diff --git a/sdk/src/net/MiniGameSocket.ts b/sdk/src/net/MiniGameSocket.ts
index 656e02016..38f35a874 100644
--- a/sdk/src/net/MiniGameSocket.ts
+++ b/sdk/src/net/MiniGameSocket.ts
@@ -23,6 +23,8 @@ export class MiniGameSocket implements PlatformSocket {
private sendQueue_: (string | ArrayBuffer)[] = [];
private events_ = new Emitter<PlatformSocketEvents>();
+ /** `wx.connectSocket` and its siblings are WebSockets like any other. */
+ readonly delivery = 'reliable-ordered' as const;
readyState: SocketReadyState = 'closed';
constructor(options: GameSocketOptions, global: MiniGameGlobal) {
diff --git a/sdk/src/net/NetChannel.ts b/sdk/src/net/NetChannel.ts
index d8528d8e1..54dccc18a 100644
--- a/sdk/src/net/NetChannel.ts
+++ b/sdk/src/net/NetChannel.ts
@@ -16,6 +16,16 @@ export interface NetTransport {
on(event: 'message', handler: (data: string | ArrayBuffer) => void): () => void;
}
+/**
+ * A transport that delivers every frame, once, in send order. {@link NetChannel}
+ * needs no such promise; replication does — its client applies the inbox in
+ * ARRIVAL order because that IS the authority's order. Declaring the marker is
+ * a claim about the link, not a feature to switch on.
+ */
+export interface ReliableOrderedTransport extends NetTransport {
+ readonly delivery: 'reliable-ordered';
+}
+
export type MessageHandler<T = unknown> = (payload: T) => void;
export type RequestHandler<Req = unknown, Res = unknown> = (payload: Req) => Res | Promise<Res>;
export type BinaryHandler = (payload: Uint8Array) => void;
diff --git a/sdk/src/net/index.ts b/sdk/src/net/index.ts
index f88e89e7a..47256839f 100644
--- a/sdk/src/net/index.ts
+++ b/sdk/src/net/index.ts
@@ -10,6 +10,7 @@ export { WeChatSocket } from './WeChatSocket';
export {
NetChannel,
type NetTransport,
+ type ReliableOrderedTransport,
type NetChannelOptions,
type MessageHandler,
type RequestHandler,
diff --git a/sdk/src/net/replication/ReplicationPlugin.ts b/sdk/src/net/replication/ReplicationPlugin.ts
index 62916e5c1..1b9af2524 100644
--- a/sdk/src/net/replication/ReplicationPlugin.ts
+++ b/sdk/src/net/replication/ReplicationPlugin.ts
@@ -12,7 +12,7 @@
import type { App, Plugin } from '../../app/app';
import { defineSystem, Schedule } from '../../ecs/system';
import { defineResource, Res, Time, type TimeData } from '../../ecs/resource';
-import type { NetTransport } from '../NetChannel';
+import type { ReliableOrderedTransport } from '../NetChannel';
import { ReplicationServer } from './server';
import { ReplicationClient, type ReplicationClientOptions } from './client';
import { ensureReplicationComponentsRegistered } from './components';
@@ -53,7 +53,7 @@ export class NetSession {
* first few ticks of a client realm and spawn local state that then
* lingered beside the replicated ghosts.) A failed handshake reverts to
* offline. */
- async connect(transport: NetTransport, options?: ReplicationClientOptions): Promise<ReplicationClient> {
+ async connect(transport: ReliableOrderedTransport, options?: ReplicationClientOptions): Promise<ReplicationClient> {
if (this.role_ !== 'offline') throw new Error(`[repl] session already ${this.role_}`);
const client = new ReplicationClient(this.app_.world, options);
this.role_ = 'client';
diff --git a/sdk/src/net/replication/client.ts b/sdk/src/net/replication/client.ts
index 2edd9ef83..fdfac7295 100644
--- a/sdk/src/net/replication/client.ts
+++ b/sdk/src/net/replication/client.ts
@@ -26,7 +26,7 @@ import type { Entity } from '../../types';
import { getComponent } from '../../ecs/component';
import { ABI_LAYOUT_HASH } from '../../ecs/component.generated';
import { loadComponent } from '../../scene/scene';
-import { NetChannel, type NetTransport } from '../NetChannel';
+import { NetChannel, type ReliableOrderedTransport } from '../NetChannel';
import { log } from '../../util/logger';
import {
REPLICATION_CHANNEL, REPLICATION_PROTOCOL_VERSION, ReplMsg,
@@ -181,7 +181,7 @@ export class ReplicationClient {
}
/** Handshake over the transport; rejects (and detaches) on any mismatch. */
- async connect(transport: NetTransport): Promise<void> {
+ async connect(transport: ReliableOrderedTransport): Promise<void> {
if (this.channel_) throw new Error('[repl] client already connected');
const channel = new NetChannel(transport);
this.channel_ = channel;
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.ts
index 955ee1503..0e1ddff37 100644
--- a/sdk/src/net/replication/server.ts
+++ b/sdk/src/net/replication/server.ts
@@ -21,7 +21,7 @@ import type { Entity } from '../../types';
import { Name, Parent, getComponent } from '../../ecs/component';
import { ABI_LAYOUT_HASH } from '../../ecs/component.generated';
import { serializeEntityComponents, type SceneComponentData } from '../../scene/scene';
-import { NetChannel, type NetTransport } from '../NetChannel';
+import { NetChannel, type ReliableOrderedTransport } from '../NetChannel';
import { log } from '../../util/logger';
import {
REPLICATION_CHANNEL, REPLICATION_PROTOCOL_VERSION, ReplMsg,
@@ -182,7 +182,7 @@ export class ReplicationServer {
}
/** Accept a transport (server-side end of one client link). */
- attachConnection(transport: NetTransport): number {
+ attachConnection(transport: ReliableOrderedTransport): number {
const id = this.nextConnectionId_++;
const channel = new NetChannel(transport);
const conn: Connection = {
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 927f16bac..7788b8b62 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -109,6 +109,10 @@ export interface PlatformSocketEvents {
* until open, moves string|ArrayBuffer frames.
*/
export interface PlatformSocket {
+ /** Every platform socket is a WebSocket (browser, `wx.connectSocket`, Node
+ * `ws`), so every one of them delivers in order and loses nothing — which
+ * is what lets a socket be handed straight to replication. */
+ readonly delivery: 'reliable-ordered';
readyState: PlatformSocketReadyState;
on<K extends keyof PlatformSocketEvents>(
event: K,
diff --git a/sdk/tests/replication-e2e-ws.test.ts b/sdk/tests/replication-e2e-ws.test.ts
index 35392446e..37ab0dc17 100644
--- a/sdk/tests/replication-e2e-ws.test.ts
+++ b/sdk/tests/replication-e2e-ws.test.ts
@@ -16,7 +16,7 @@ import { defineComponent, clearUserComponents, Transform } from '../src/ecs/comp
import type { ESEngineModule } from '../src/wasm';
import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
import { GameSocket } from '../src/net/GameSocket';
-import type { NetTransport } from '../src/net/NetChannel';
+import type { ReliableOrderedTransport } from '../src/net/NetChannel';
import { replicationPlugin, Net, Replicated } from '../src/net/replication';
import { setPlatform } from '../src/platform/base';
import { nodeAdapter } from '../src/platform/node';
@@ -28,7 +28,7 @@ const STEP = 1 / 60;
const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** Server-side end of one accepted `ws` connection as a NetTransport. */
-function wsServerTransport(conn: WsSocket): NetTransport {
+function wsServerTransport(conn: WsSocket): ReliableOrderedTransport {
const handlers = new Set<(d: string | ArrayBuffer) => void>();
conn.on('message', (data, isBinary) => {
const frame = isBinary
@@ -40,6 +40,7 @@ function wsServerTransport(conn: WsSocket): NetTransport {
for (const h of [...handlers]) h(frame);
});
return {
+ delivery: 'reliable-ordered',
send: (d) => conn.send(d),
on: (_event, handler) => {
handlers.add(handler);
diff --git a/sdk/tests/replication.test.ts b/sdk/tests/replication.test.ts
index c5fa3286e..5f1c9cda0 100644
--- a/sdk/tests/replication.test.ts
+++ b/sdk/tests/replication.test.ts
@@ -375,11 +375,12 @@ describe('codec round trip', () => {
});
it('diffSchemas pinpoints drift', () => {
- const a = [{ name: 'A', fields: ['x'] }];
- expect(diffSchemas(a, [{ name: 'A', fields: ['x'] }])).toBeNull();
+ const a = [{ name: 'A', fields: ['x'], shapes: ['f32'] }];
+ expect(diffSchemas(a, [{ name: 'A', fields: ['x'], shapes: ['f32'] }])).toBeNull();
expect(diffSchemas(a, [])).toMatch(/size/);
- expect(diffSchemas(a, [{ name: 'B', fields: ['x'] }])).toMatch(/differs/);
- expect(diffSchemas(a, [{ name: 'A', fields: ['x', 'y'] }])).toMatch(/field list/);
+ expect(diffSchemas(a, [{ name: 'B', fields: ['x'], shapes: ['f32'] }])).toMatch(/differs/);
+ expect(diffSchemas(a, [{ name: 'A', fields: ['x', 'y'], shapes: ['f32', 'f32'] }])).toMatch(/field list/);
+ expect(diffSchemas(a, [{ name: 'A', fields: ['x'], shapes: ['bool'] }])).toMatch(/wire shape/);
});
});
diff --git a/tools/check-transport-contract.mjs b/tools/check-transport-contract.mjs
new file mode 100644
index 000000000..364bab61c
--- /dev/null
+++ b/tools/check-transport-contract.mjs
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-transport-contract.mjs — replication cannot be handed a link it
+ * cannot trust.
+ *
+ * The client applies its inbox in ARRIVAL order because that IS the authority's
+ * order. That makes reliable, ordered delivery a correctness condition, not a
+ * preference — and until `ReliableOrderedTransport` existed, the type system
+ * would hand replication any `NetTransport` at all.
+ *
+ * A type rule nothing compiles is a comment. So this compiles two fixtures
+ * against the SHIPPED declarations — what a user actually faces — and requires
+ * one to pass and the other to be REFUSED, for the stated reason:
+ *
+ * accept: every built-in transport, and a hand-written one that declares it
+ * reject: a transport that makes no delivery claim
+ *
+ * It does not try to defeat a deliberate `as ReliableOrderedTransport`. The job
+ * of the contract is that correct code cannot wire this up wrong by accident.
+ *
+ * node tools/check-transport-contract.mjs
+ */
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const TSC = path.join(ROOT, 'sdk', 'node_modules', 'typescript', 'bin', 'tsc');
+const DTS = path.join(ROOT, 'sdk', 'dist', 'index.d.ts');
+const posix = (p) => p.split(path.sep).join('/');
+
+const work = mkdtempSync(path.join(tmpdir(), 'estella-transport-'));
+
+function fail(message, detail) {
+ console.error(`check-transport-contract: ${message}`);
+ if (detail) console.error(detail.trim());
+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ process.exit(1);
+}
+
+if (!existsSync(DTS)) fail(`no SDK declarations at ${DTS} — build the SDK first.`);
+
+/** Type-check one fixture on its own; returns tsc's combined output. */
+function check(name, source) {
+ const dir = path.join(work, name);
+ const file = path.join(dir, 'fixture.ts');
+ const config = path.join(dir, 'tsconfig.json');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(file, source);
+ writeFileSync(config, JSON.stringify({
+ compilerOptions: {
+ target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler',
+ strict: true, skipLibCheck: true, noEmit: true, types: [],
+ lib: ['ES2022', 'DOM'],
+ baseUrl: '.', paths: { esengine: [posix(DTS)] },
+ },
+ include: [posix(file)],
+ }));
+ const run = spawnSync(process.execPath, [TSC, '-p', config], { encoding: 'utf8', cwd: ROOT });
+ return { status: run.status, out: `${run.stdout ?? ''}${run.stderr ?? ''}` };
+}
+
+// ---------------------------------------------------------------------------
+
+const ACCEPT = `
+import {
+ MemoryTransport, GameSocket, createSocket,
+ type ReliableOrderedTransport, type ReplicationServer, type NetSession,
+} from 'esengine';
+
+declare const server: ReplicationServer;
+declare const session: NetSession;
+
+// Built-ins: each already delivers this way and now says so.
+const [a, b] = MemoryTransport.pair();
+server.attachConnection(a);
+void session.connect(b);
+server.attachConnection(new GameSocket({ url: 'ws://127.0.0.1:1' }));
+server.attachConnection(createSocket({ url: 'ws://127.0.0.1:1' }));
+
+// A server author's own transport — the shape the dedicated-server example
+// writes by hand around \`ws\`.
+const mine: ReliableOrderedTransport = {
+ delivery: 'reliable-ordered',
+ send: () => {},
+ on: () => () => {},
+};
+server.attachConnection(mine);
+void session.connect(mine);
+`;
+
+/** One fixture per door: tsc reports a line, not a method, so guarding both
+ * has to be two compilations or the second one is unproven. */
+const REJECT = (call) => `
+import { type NetTransport, type ReplicationServer, type NetSession } from 'esengine';
+
+declare const server: ReplicationServer;
+declare const session: NetSession;
+
+// Delivers frames, promises nothing about losing or reordering them.
+const datagram: NetTransport = { send: () => {}, on: () => () => {} };
+
+${call}
+`;
+
+const accepted = check('accept', ACCEPT);
+if (accepted.status !== 0) {
+ fail('a transport that DOES declare reliable-ordered delivery was rejected.', accepted.out);
+}
+
+const DOORS = {
+ attachConnection: 'server.attachConnection(datagram);',
+ connect: 'void session.connect(datagram);',
+};
+for (const [door, call] of Object.entries(DOORS)) {
+ const rejected = check(`reject-${door}`, REJECT(call));
+ if (rejected.status === 0) {
+ fail(`\`${door}\` accepted a transport that makes no delivery claim.`
+ + ' The inbox is applied in arrival order, so an unordered link desynchronizes it silently.');
+ }
+ if (!/delivery/.test(rejected.out)) {
+ fail(`\`${door}\` refused it, but not for the missing delivery claim —`
+ + ' the fixture may be failing on something else.', rejected.out);
+ }
+}
+
+rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+console.log('check-transport-contract: replication takes reliable-ordered links only —'
+ + ' built-ins and a hand-written one compile, an unclaimed transport is refused at both doors.');
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 6290946c5..1a8906ff2 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -113,6 +113,10 @@ export const GATES = [
// And the boundary holds in practice: a real project packages from the command
// line with no editor built.
{ id: 'headless-export', run: 'node tools/check-headless-export.mjs' },
+ // Replication applies its inbox in arrival order, so reliable+ordered is a
+ // correctness condition. This compiles the claim: a transport that does not
+ // make it cannot reach replication.
+ { id: 'transport-contract', run: 'node tools/check-transport-contract.mjs' },
// The multiplayer half of that claim: an authority runs as a plain Node
// process over a real socket. Also the only check of two facts the editor's
// preview has no way to reach — no local player, and a connection that LEAVES.