A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(sdk): the headless entry joins the shared chunk graph
esengine27440f6bd373
diff --git a/bench/lib/sdkBuild.mjs b/bench/lib/sdkBuild.mjsnew file mode 100644index 000000000..b645eadfe--- /dev/null+++ b/bench/lib/sdkBuild.mjs@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The headless SDK a benchmark measures, and what build it was.+ *+ * One author: three replication benchmarks had each written this out, and a+ * benchmark that loads the wrong build does not fail — it reports very stable+ * numbers for yesterday's code.+ */+import { pathToFileURL } from 'node:url';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import path from 'node:path';++const NODE_ENTRY = ['sdk', 'dist', 'index.node.js'];+/** Replication is a subpath, on the headless entry as on every other. */+const REPLICATION = ['sdk', 'dist', 'net', 'replication', 'index.js'];++/** The newest hand-written .ts under `dir`, in epoch ms. */+function newestSource(dir) {+ let newest = 0;+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules' || entry.name === 'dist') continue;+ const full = path.join(dir, entry.name);+ newest = Math.max(newest, entry.isDirectory() ? newestSource(full)+ : entry.name.endsWith('.ts') ? statSync(full).mtimeMs : 0);+ }+ return newest;+}++/**+ * What was actually measured: the commit, and the artifact the arms imported.+ * A benchmark cannot tell a stale build from a fast one, so the identity ships+ * with the result.+ */+export function sdkIdentity(root) {+ const entry = path.join(root, ...NODE_ENTRY);+ const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();+ const dirty = execFileSync('git', ['status', '--porcelain'], { cwd: root, encoding: 'utf8' }).trim();+ return {+ gitHead: head,+ workingTreeClean: dirty.length === 0,+ sdkArtifactSha256: createHash('sha256').update(readFileSync(entry)).digest('hex').slice(0, 16),+ sdkBuiltAt: new Date(statSync(entry).mtimeMs).toISOString(),+ };+}++/**+ * Load the SDK's headless build, refusing one older than the sources it is+ * built from. The replication subpath comes with it: both entries share one+ * chunk graph, so this is one core — merged rather than returned separately so+ * an arm names `sdk.Net` the way it always did.+ */+export async function loadSdk(root) {+ const entry = path.join(root, ...NODE_ENTRY);+ if (newestSource(path.join(root, 'sdk', 'src')) > statSync(entry).mtimeMs) {+ throw new Error('sdk/dist is older than sdk/src — this run would measure the previous'+ + ' commit. Build it with `pnpm --filter ./sdk build`.');+ }+ const [core, replication] = await Promise.all([+ import(pathToFileURL(entry).href),+ import(pathToFileURL(path.join(root, ...REPLICATION)).href),+ ]);+ return { ...core, ...replication };+}diff --git a/bench/replication-dirty/workload.mjs b/bench/replication-dirty/workload.mjsindex 7b151434a..656e037a6 100644--- a/bench/replication-dirty/workload.mjs+++ b/bench/replication-dirty/workload.mjs@@ -17,46 +17,10 @@ import { execFileSync } from 'node:child_process';import { readdirSync, readFileSync, statSync } from 'node:fs';import path from 'node:path';-const STRIDE = 7919; // coprime with every entity count used here+export { loadSdk, sdkIdentity } from '../lib/sdkBuild.mjs';-/** The newest hand-written .ts under `dir`, in epoch ms. */-function newestSource(dir) {- let newest = 0;- for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (entry.name === 'node_modules' || entry.name === 'dist') continue;- const full = path.join(dir, entry.name);- newest = Math.max(newest, entry.isDirectory() ? newestSource(full)- : entry.name.endsWith('.ts') ? statSync(full).mtimeMs : 0);- }- return newest;-}--/**- * What was actually measured: the commit, and the artifact the arms imported.- * A benchmark cannot tell a stale build from a fast one — it just reports very- * stable numbers for yesterday's code — so the identity ships with the result.- */-export function sdkIdentity(root) {- const entry = path.join(root, 'sdk', 'dist', 'index.node.js');- const head = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();- const dirty = execFileSync('git', ['status', '--porcelain'], { cwd: root, encoding: 'utf8' }).trim();- return {- gitHead: head,- workingTreeClean: dirty.length === 0,- sdkArtifactSha256: createHash('sha256').update(readFileSync(entry)).digest('hex').slice(0, 16),- sdkBuiltAt: new Date(statSync(entry).mtimeMs).toISOString(),- };-}+const STRIDE = 7919; // coprime with every entity count used here-/** Load the SDK's headless build, refusing one older than the sources it is built from. */-export async function loadSdk(root) {- const entry = path.join(root, 'sdk', 'dist', 'index.node.js');- if (newestSource(path.join(root, 'sdk', 'src')) > statSync(entry).mtimeMs) {- throw new Error('sdk/dist is older than sdk/src — this run would measure the previous'- + ' commit. Build it with `pnpm --filter ./sdk build`.');- }- return import(pathToFileURL(entry).href);-}/*** Four replicated components per entity, of which THREE are mutated and one isdiff --git a/bench/replication-interest/workload.mjs b/bench/replication-interest/workload.mjsindex 0d4b41d34..8b85c8819 100644--- a/bench/replication-interest/workload.mjs+++ b/bench/replication-interest/workload.mjs@@ -16,28 +16,8 @@ import { pathToFileURL } from 'node:url';import { readdirSync, statSync } from 'node:fs';import path from 'node:path';-export { sdkIdentity } from '../replication-dirty/workload.mjs';--function newestSource(dir) {- let newest = 0;- for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (entry.name === 'node_modules' || entry.name === 'dist') continue;- const full = path.join(dir, entry.name);- newest = Math.max(newest, entry.isDirectory() ? newestSource(full)- : entry.name.endsWith('.ts') && !entry.name.endsWith('.generated.ts')- ? statSync(full).mtimeMs : 0);- }- return newest;-}+export { loadSdk, sdkIdentity } from '../lib/sdkBuild.mjs';-export async function loadSdk(root) {- const entry = path.join(root, 'sdk', 'dist', 'index.node.js');- if (newestSource(path.join(root, 'sdk', 'src')) > statSync(entry).mtimeMs) {- throw new Error('sdk/dist is older than sdk/src — this run would measure the previous'- + ' commit. Build it with `pnpm --filter ./sdk build`.');- }- return import(pathToFileURL(entry).href);-}/** The engine module, so `Transform` is the real builtin the default reads. */export async function connectEngine(sdk, app, root) {diff --git a/bench/replication-topology/workload.mjs b/bench/replication-topology/workload.mjsindex 1bf3aac6f..01be82d0e 100644--- a/bench/replication-topology/workload.mjs+++ b/bench/replication-topology/workload.mjs@@ -12,29 +12,8 @@ import { pathToFileURL } from 'node:url';import { readdirSync, statSync } from 'node:fs';import path from 'node:path';-export { sdkIdentity } from '../replication-dirty/workload.mjs';+export { loadSdk, sdkIdentity } from '../lib/sdkBuild.mjs';-/** The newest hand-written .ts under `dir`, in epoch ms. */-function newestSource(dir) {- let newest = 0;- for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (entry.name === 'node_modules' || entry.name === 'dist') continue;- const full = path.join(dir, entry.name);- newest = Math.max(newest, entry.isDirectory() ? newestSource(full)- : entry.name.endsWith('.ts') && !entry.name.endsWith('.generated.ts')- ? statSync(full).mtimeMs : 0);- }- return newest;-}--export async function loadSdk(root) {- const entry = path.join(root, 'sdk', 'dist', 'index.node.js');- if (newestSource(path.join(root, 'sdk', 'src')) > statSync(entry).mtimeMs) {- throw new Error('sdk/dist is older than sdk/src — this run would measure the previous'- + ' commit. Build it with `pnpm --filter ./sdk build`.');- }- return import(pathToFileURL(entry).href);-}/*** For each component, the entities whose MEMBERSHIP moved, and from which tickdiff --git a/bench/spawn-contract/probe.mjs b/bench/spawn-contract/probe.mjsindex a575ca514..74a520581 100644--- a/bench/spawn-contract/probe.mjs+++ b/bench/spawn-contract/probe.mjs@@ -24,6 +24,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');const PROJECT = path.join(ROOT, 'examples', 'multiplayer-arena');const SDK = path.join(ROOT, 'sdk', 'dist', 'index.node.js');+const REPLICATION = path.join(ROOT, 'sdk', 'dist', 'net', 'replication', 'index.js');const WASM = process.env.ESENGINE_WASM_DIR ?? path.join(ROOT, 'build', 'wasm', 'web');const posix = (p) => p.split(path.sep).join('/');const work = mkdtempSync(path.join(tmpdir(), 'estella-spawn-'));@@ -36,6 +37,7 @@ const work = mkdtempSync(path.join(tmpdir(), 'estella-spawn-'));*/writeFileSync(path.join(work, 'entry.ts'), `export * from 'esengine';+export * from 'esengine/replication';import ${JSON.stringify(posix(path.join(PROJECT, 'src', 'main.ts')))};`);const out = path.join(work, 'bundle.mjs');@@ -43,7 +45,11 @@ const { build } = await import('esbuild');await build({entryPoints: [path.join(work, 'entry.ts')],outfile: out, bundle: true, format: 'esm', platform: 'node', target: 'node20',- logLevel: 'silent', alias: { esengine: SDK, 'esengine/node': SDK },+ logLevel: 'silent',+ // One core on both ends: the headless entry and the replication subpath share+ // the SDK's chunk graph, and two copies would make the handshake reject the+ // server's own client.+ alias: { esengine: SDK, 'esengine/node': SDK, 'esengine/replication': REPLICATION },});const sdk = await import(pathToFileURL(out).href);diff --git a/examples/multiplayer-arena/server/main.ts b/examples/multiplayer-arena/server/main.tsindex a104487f0..a0e18b5c4 100644--- a/examples/multiplayer-arena/server/main.ts+++ b/examples/multiplayer-arena/server/main.ts@@ -23,8 +23,11 @@import { WebSocketServer, type WebSocket } from 'ws';import {loadEsengineModule, createHeadlessApp, runHeadless,- flushPendingRegistrations, Net, type ReliableOrderedTransport,+ flushPendingRegistrations, type ReliableOrderedTransport,} from 'esengine/node';+// Replication is a subpath on every entry, the headless one included: importing+// it is what installs the authority this process exists to run.+import { Net } from 'esengine/replication';import { arena } from '../src/net';// Side-effect import: `src/main.ts` registers the arena's systems at module// scope, exactly as it does in the browser. The server runs the project's realdiff --git a/examples/multiplayer-arena/server/run.mjs b/examples/multiplayer-arena/server/run.mjsindex de3df6aa4..a6b227d2a 100644--- a/examples/multiplayer-arena/server/run.mjs+++ b/examples/multiplayer-arena/server/run.mjs@@ -84,7 +84,12 @@ await build({+ 'const require = __estellaCreateRequire(import.meta.url);',},// One SDK instance, whichever specifier reached it.- alias: { esengine: sdkEntry, 'esengine/node': sdkEntry },+ alias: {+ esengine: sdkEntry, 'esengine/node': sdkEntry,+ // The same shared chunks as the entry beside it — one core, or the+ // handshake compares two copies of the schema.+ 'esengine/replication': path.join(sdkDir, 'net', 'replication', 'index.js'),+ },// `ws` is a real dependency of the server (and only of the server): resolve it// from the server's own install first, then from the engine checkout.nodePaths: [diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex e4d479031..d6b6f6b9e 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -74,12 +74,16 @@ const minify = { compress: true, mangle: true, codegen: { removeWhitespace: trueexport default defineConfig([{// ONE code-split graph for every ESM entry a bundler can combine:- // `esengine` (web or wechat) and the `esengine/*` subpaths must resolve- // into the SAME shared chunks, or a game bundle that imports both gets+ // `esengine` (web, wechat or node) and the `esengine/*` subpaths must+ // resolve into the SAME shared chunks, or a bundle that imports both gets// two copies of the core — and identity-keyed resources (Res(Spine))// split-brain: the runtime inserts into one copy, systems read the other.+ // The dedicated-server example proved it: `esengine/node` built on its own+ // registered the replication plugin in a registry `esengine/replication`+ // could not see, and the authority came up with no Net resource.input: {'index': 'src/index.ts',+ 'index.node': 'src/index.node.ts','index.wechat': 'src/index.wechat.ts','index.wechat.lean': 'src/index.wechat.lean.ts','index.minigame': 'src/index.minigame.ts',@@ -95,6 +99,9 @@ export default defineConfig(['douyin/index': 'src/platform/douyin/index.ts','wasm': 'src/wasm.ts',},+ // Only the node entry reaches these; a browser entry that did would fail+ // to bundle, which is the point.+ external: (id) => id.startsWith('node:'),output: {dir: 'dist',format: 'esm',@@ -127,11 +134,4 @@ export default defineConfig([plugins: [preserveViteIgnore()],treeshake,},- {- input: 'src/index.node.ts',- output: { file: 'dist/index.node.js', format: 'esm', sourcemap: true, minify },- external: (id) => id.startsWith('node:'),- plugins: [preserveViteIgnore()],- treeshake,- },]);diff --git a/tools/check-arena-server.mjs b/tools/check-arena-server.mjsindex 09b3a99e0..81d2bf97a 100644--- a/tools/check-arena-server.mjs+++ b/tools/check-arena-server.mjs@@ -95,6 +95,7 @@ writeFileSync(tsconfig, JSON.stringify({paths: {esengine: [posix(path.join(ROOT, 'sdk', 'dist', 'index.d.ts'))],'esengine/node': [posix(path.join(ROOT, 'sdk', 'dist', 'index.node.d.ts'))],+ 'esengine/replication': [posix(path.join(ROOT, 'sdk', 'dist', 'net', 'replication', 'index.d.ts'))],ws: [posix(path.join(SDK_TYPES, 'ws', 'index.d.ts'))],},},@@ -120,7 +121,8 @@ if (built.status !== 0) fail('the server bundle failed to build.', built.stderrconst probeSource = `// 'esengine' rather than a path: the alias below points it at the same headless// SDK the server bundle uses, so probe and project share one module instance.-export { loadEsengineModule, createHeadlessApp, flushPendingRegistrations, GameSocket, Net, Input, Replicated, Transform } from 'esengine';+export { loadEsengineModule, createHeadlessApp, flushPendingRegistrations, GameSocket, Input, Transform } from 'esengine';+export { Net, Replicated } from 'esengine/replication';import ${JSON.stringify(posix(path.join(PROJECT, 'src', 'main.ts')))};`;writeFileSync(path.join(work, 'probe.entry.ts'), probeSource);@@ -138,7 +140,10 @@ await build({// The project's `import ... from 'esengine'` resolves to the same headless SDK// the server bundle uses — one build on both ends, which is what the// handshake's ABI/schema check insists on.- alias: { esengine: SDK, 'esengine/node': SDK },+ alias: {+ esengine: SDK, 'esengine/node': SDK,+ 'esengine/replication': path.join(path.dirname(SDK), 'net', 'replication', 'index.js'),+ },});const probe = await import(pathToFileURL(probeOut).href);diff --git a/tools/check-transport-contract.mjs b/tools/check-transport-contract.mjsindex 364bab61c..f3e885054 100644--- a/tools/check-transport-contract.mjs+++ b/tools/check-transport-contract.mjs@@ -30,6 +30,7 @@ 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 REPL_DTS = path.join(ROOT, 'sdk', 'dist', 'net', 'replication', 'index.d.ts');const posix = (p) => p.split(path.sep).join('/');const work = mkdtempSync(path.join(tmpdir(), 'estella-transport-'));@@ -42,6 +43,7 @@ function fail(message, detail) {}if (!existsSync(DTS)) fail(`no SDK declarations at ${DTS} — build the SDK first.`);+if (!existsSync(REPL_DTS)) fail(`no replication declarations at ${REPL_DTS} — build the SDK first.`);/** Type-check one fixture on its own; returns tsc's combined output. */function check(name, source) {@@ -55,7 +57,7 @@ function check(name, source) {target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler',strict: true, skipLibCheck: true, noEmit: true, types: [],lib: ['ES2022', 'DOM'],- baseUrl: '.', paths: { esengine: [posix(DTS)] },+ baseUrl: '.', paths: { esengine: [posix(DTS)], 'esengine/replication': [posix(REPL_DTS)] },},include: [posix(file)],}));@@ -66,10 +68,10 @@ function check(name, source) {// ---------------------------------------------------------------------------const ACCEPT = `+import { GameSocket, createSocket, type ReliableOrderedTransport } from 'esengine';import {- MemoryTransport, GameSocket, createSocket,- type ReliableOrderedTransport, type ReplicationServer, type NetSession,-} from 'esengine';+ MemoryTransport, type ReplicationServer, type NetSession,+} from 'esengine/replication';declare const server: ReplicationServer;declare const session: NetSession;@@ -95,7 +97,8 @@ 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';+import type { NetTransport } from 'esengine';+import type { ReplicationServer, NetSession } from 'esengine/replication';declare const server: ReplicationServer;declare const session: NetSession;