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
feat(editor): manifest script-entry convention + manifest-driven schema/bundle entries (editor-realm P3)
esengine35735d5e37ee
diff --git a/desktop/electron/buildScripts.ts b/desktop/electron/buildScripts.tsindex 0e6a8d365..65bb758d3 100644--- a/desktop/electron/buildScripts.ts+++ b/desktop/electron/buildScripts.ts@@ -16,8 +16,8 @@ import path from 'node:path';/** esengine and any subpath import are left for the realm's import map to resolve. */const EXTERNAL = ['esengine', 'esengine/*'];-const DEFAULT_SRC_DIR = 'src';-const DEFAULT_ENTRY = 'main.ts';+/** Default startup entry (project-relative). */+const DEFAULT_ENTRY = 'src/main.ts';/** Local, gitignored build cache inside the project (next to workspace.json). */const CACHE_DIR = '.esengine/cache';const OUTPUT = 'scripts.mjs';@@ -31,14 +31,15 @@ export interface BuildScriptsResult {}/**- * Bundle `<root>/<srcDir>/<entry>` → `<root>/.esengine/cache/scripts.mjs`,- * esengine external. Never throws — failures come back as `{ ok:false, errors }`.+ * Bundle `<root>/<entry>` (project-relative, default `src/main.ts`) →+ * `<root>/.esengine/cache/scripts.mjs`, esengine external. Never throws —+ * failures come back as `{ ok:false, errors }`.*/export async function buildProjectScripts(root: string,- opts?: { srcDir?: string; entry?: string },+ opts?: { entry?: string },): Promise<BuildScriptsResult> {- const entryPath = path.join(root, opts?.srcDir ?? DEFAULT_SRC_DIR, opts?.entry ?? DEFAULT_ENTRY);+ const entryPath = path.join(root, opts?.entry ?? DEFAULT_ENTRY);if (!existsSync(entryPath)) {return { ok: false, outputPath: null, errors: [`script entry not found: ${entryPath}`], warnings: [] };}diff --git a/desktop/electron/extractSchemas.ts b/desktop/electron/extractSchemas.tsindex a2058c310..7b9d4002e 100644--- a/desktop/electron/extractSchemas.ts+++ b/desktop/electron/extractSchemas.ts@@ -24,9 +24,8 @@ import { tmpdir } from 'node:os';import path from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';-const DEFAULT_SRC_DIR = 'src';-/** The pure declaration module (only defineComponent/defineTag, no app startup). */-const DEFAULT_DECL_ENTRY = 'components.ts';+/** Default pure declaration module (only defineComponent/defineTag, no startup). */+const DEFAULT_DECL_ENTRY = 'src/components.ts';/** Local, gitignored cache inside the project (next to workspace.json). */const CACHE_DIR = '.esengine/cache';const OUTPUT = 'schemas.json';@@ -91,17 +90,33 @@ function esengineAnchor(): Plugin {};}+/** Write the schemas artifact and return its absolute path. */+function writeSchemas(root: string, schemas: ComponentSchema[]): string {+ const outputPath = path.join(root, CACHE_DIR, OUTPUT);+ mkdirSync(path.dirname(outputPath), { recursive: true });+ writeFileSync(outputPath, JSON.stringify(schemas, null, 2) + '\n');+ return outputPath;+}+/**- * Extract `<root>/<srcDir>/<entry>` → `<root>/.esengine/cache/schemas.json`.- * Never throws — failures come back as `{ ok:false, errors }`.+ * Extract the project's component schemas from `<root>/<entry>` (project-relative,+ * default `src/components.ts`) → `<root>/.esengine/cache/schemas.json`. Never+ * throws — failures come back as `{ ok:false, errors }`.+ *+ * A missing entry: if `required` (the manifest explicitly named it) it's an+ * error; otherwise the project simply has no custom components → an empty+ * artifact is written and `ok:true` returned.*/export async function extractProjectSchemas(root: string,- opts?: { srcDir?: string; entry?: string },+ opts?: { entry?: string; required?: boolean },): Promise<ExtractSchemasResult> {- const declPath = path.join(root, opts?.srcDir ?? DEFAULT_SRC_DIR, opts?.entry ?? DEFAULT_DECL_ENTRY);+ const declPath = path.join(root, opts?.entry ?? DEFAULT_DECL_ENTRY);if (!existsSync(declPath)) {- return { ok: false, outputPath: null, schemas: [], errors: [`declaration entry not found: ${declPath}`], warnings: [] };+ if (opts?.required) {+ return { ok: false, outputPath: null, schemas: [], errors: [`declaration entry not found: ${declPath}`], warnings: [] };+ }+ return { ok: true, outputPath: writeSchemas(root, []), schemas: [], errors: [], warnings: [] };}// Generated entry: install a fresh context FIRST (top-level, so it runs before@@ -139,11 +154,7 @@ export async function extractProjectSchemas(.map(toSchema).sort((a, b) => a.name.localeCompare(b.name)); // deterministic output- const outputPath = path.join(root, CACHE_DIR, OUTPUT);- mkdirSync(path.dirname(outputPath), { recursive: true });- writeFileSync(outputPath, JSON.stringify(schemas, null, 2) + '\n');-- return { ok: true, outputPath, schemas, errors: [], warnings };+ return { ok: true, outputPath: writeSchemas(root, schemas), schemas, errors: [], warnings };} catch (err) {const e = err as { errors?: { text: string }[]; warnings?: { text: string }[]; message?: string };return {diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex daebdc595..72d891215 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -4,6 +4,7 @@ import { readFile } from 'node:fs/promises';import path from 'node:path';import {openProject,+ readManifest,readInRoot,writeInRoot,readDirInRoot,@@ -13,6 +14,7 @@ import {import { listRecents, addRecent, listTemplates, createFromTemplate } from './launcher';import { buildProjectScripts } from './buildScripts';import { extractProjectSchemas } from './extractSchemas';+import { resolveScripts } from '../src/project/format';import type { WorkspaceState } from '../src/project/format';// Custom scheme that serves files from the open project root (sandboxed). Lets@@ -133,14 +135,26 @@ ipcMain.handle('fs:write', (_e, relPath: string, contents: string) =>ipcMain.handle('fs:readdir', (_e, relPath: string) => readDirInRoot(requireRoot(), relPath));ipcMain.handle('workspace:save', (_e, ws: WorkspaceState) => saveWorkspace(requireRoot(), ws));-// Bundle the open project's scripts (src/main.ts → .esengine/cache, esengine-// external) for the isolated play realm (REARCH_EDITOR_REALM P1 / RC12 §E8-1).-ipcMain.handle('project:buildScripts', () => buildProjectScripts(requireRoot()));+// Bundle the open project's startup script (manifest scripts.main, default+// src/main.ts → .esengine/cache, esengine external) for the isolated play realm+// (REARCH_EDITOR_REALM P1/P3 / RC12 §E8-1).+ipcMain.handle('project:buildScripts', async () => {+ const root = requireRoot();+ const { main } = resolveScripts(await readManifest(root));+ return buildProjectScripts(root, { entry: main });+});-// Extract the open project's component field schemas (src/components.ts →-// .esengine/cache/schemas.json) so the editor main realm can inspect unknown-// components without executing project code (REARCH_EDITOR_REALM P2).-ipcMain.handle('project:extractSchemas', () => extractProjectSchemas(requireRoot()));+// Extract the open project's component field schemas (manifest scripts.register,+// default src/components.ts → .esengine/cache/schemas.json) so the editor main+// realm can inspect unknown components without executing project code. An+// explicitly-declared register that's missing is an error; the default merely+// being absent means the project has no custom components (REARCH_EDITOR_REALM P2/P3).+ipcMain.handle('project:extractSchemas', async () => {+ const root = requireRoot();+ const manifest = await readManifest(root);+ const { register } = resolveScripts(manifest);+ return extractProjectSchemas(root, { entry: register, required: manifest.scripts?.register !== undefined });+});ipcMain.handle('recents:list', () => listRecents());ipcMain.handle('recents:add', (_e, root: string, name: string) => addRecent(root, name));diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.tsindex 14a4bb768..045ff19bf 100644--- a/desktop/electron/projectFs.ts+++ b/desktop/electron/projectFs.ts@@ -14,6 +14,7 @@ import {WORKSPACE_DIR,WORKSPACE_FILE,parseManifest,+ type ProjectManifest,type OpenedProject,type WorkspaceState,type DirEntry,@@ -33,13 +34,18 @@ export function resolveInRoot(root: string, relPath: string): string {return resolved;}-/** Open a project: require + parse `project.esproj`, load workspace if present. */-export async function openProject(root: string): Promise<OpenedProject> {+/** Require + parse a project's `project.esproject` manifest (no workspace load). */+export async function readManifest(root: string): Promise<ProjectManifest> {const manifestPath = path.join(root, PROJECT_MANIFEST_FILE);if (!existsSync(manifestPath)) {throw new Error(`not an Estella project (missing ${PROJECT_MANIFEST_FILE}): ${root}`);}- const manifest = parseManifest(JSON.parse(await readFile(manifestPath, 'utf8')));+ return parseManifest(JSON.parse(await readFile(manifestPath, 'utf8')));+}++/** Open a project: require + parse `project.esproject`, load workspace if present. */+export async function openProject(root: string): Promise<OpenedProject> {+ const manifest = await readManifest(root);let workspace: WorkspaceState = {};const wsPath = path.join(root, WORKSPACE_DIR, WORKSPACE_FILE);diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 19801c00b..de54e1c4b 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -40,6 +40,20 @@ export interface DesignResolution {height: number;}+/**+ * Script entry points (REARCH_EDITOR_REALM §E8 / P3). Splitting declaration from+ * startup is what lets the editor extract a component schema WITHOUT executing+ * project startup: schema extraction imports ONLY `register`, the play-realm+ * bundle is built from `main`. Both default (see {@link DEFAULT_SCRIPTS}) so most+ * projects need no entry here.+ */+export interface ProjectScripts {+ /** Pure declaration module — `defineComponent`/`defineTag` only, no startup. */+ register?: string;+ /** Startup/entry module — `createWebApp`/`run`; the play-realm bundle entry. */+ main?: string;+}+/** Committed project identity + config (`project.esproject`). */export interface ProjectManifest {/** Manifest schema version (migration-aware; rejects newer than supported). */@@ -57,6 +71,8 @@ export interface ProjectManifest {spineVersion?: string;/** Per-path overrides of {@link DEFAULT_LAYOUT}. */layout?: Partial<ProjectLayout>;+ /** Declaration/startup entry points (defaults in {@link DEFAULT_SCRIPTS}). */+ scripts?: ProjectScripts;/** One-line summary, shown when the project is used as a New-project template. */description?: string;/** Short category label for the template gallery (e.g. "2D", "Physics"). */@@ -134,6 +150,13 @@ export function parseManifest(raw: unknown): ProjectManifest {if (o.layout && typeof o.layout === 'object') {manifest.layout = o.layout as Partial<ProjectLayout>;}+ if (o.scripts && typeof o.scripts === 'object') {+ const s = o.scripts as Record<string, unknown>;+ const scripts: ProjectScripts = {};+ if (typeof s.register === 'string') scripts.register = s.register;+ if (typeof s.main === 'string') scripts.main = s.main;+ if (scripts.register !== undefined || scripts.main !== undefined) manifest.scripts = scripts;+ }if (typeof o.description === 'string') manifest.description = o.description;if (typeof o.tag === 'string') manifest.tag = o.tag;return manifest;@@ -144,6 +167,17 @@ export function resolveLayout(manifest: Pick<ProjectManifest, 'layout'>): Projecreturn { ...DEFAULT_LAYOUT, ...(manifest.layout ?? {}) };}+/** Default script entries — the convention most projects follow without config. */+export const DEFAULT_SCRIPTS: Required<ProjectScripts> = {+ register: 'src/components.ts',+ main: 'src/main.ts',+};++/** Effective script entries = defaults overlaid with the manifest's overrides. */+export function resolveScripts(manifest: Pick<ProjectManifest, 'scripts'>): Required<ProjectScripts> {+ return { ...DEFAULT_SCRIPTS, ...(manifest.scripts ?? {}) };+}+/** A fresh manifest for `new project`. */export function defaultManifest(name: string): ProjectManifest {return { formatVersion: PROJECT_FORMAT_VERSION, name, defaultScene: 'assets/scenes/main.esscene' };diff --git a/desktop/tests/extract-schemas.test.ts b/desktop/tests/extract-schemas.test.tsindex 82dc02d18..8a37f4ac6 100644--- a/desktop/tests/extract-schemas.test.ts+++ b/desktop/tests/extract-schemas.test.ts@@ -73,16 +73,46 @@ describe('extractProjectSchemas (P2)', () => {expect(onDisk).toEqual(res.schemas);});- it('reports a clean failure when the declaration entry is missing', async () => {+ it('treats a missing DEFAULT declaration as a component-less project (empty artifact, ok)', async () => {const empty = mkdtempSync(path.join(tmpdir(), 'estella-schema-empty-'));try {const res = await extractProjectSchemas(empty);+ expect(res.ok).toBe(true);+ expect(res.schemas).toEqual([]);+ expect(res.outputPath).toBe(path.join(empty, '.esengine/cache/schemas.json'));+ expect(JSON.parse(readFileSync(res.outputPath!, 'utf8'))).toEqual([]);+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+ });++ it('errors when an EXPLICITLY-declared entry is missing (required)', async () => {+ const empty = mkdtempSync(path.join(tmpdir(), 'estella-schema-req-'));+ try {+ const res = await extractProjectSchemas(empty, { entry: 'src/decls.ts', required: true });expect(res.ok).toBe(false);expect(res.outputPath).toBeNull();- expect(res.schemas).toEqual([]);expect(res.errors.join(' ')).toMatch(/declaration entry not found/);} finally {rmSync(empty, { recursive: true, force: true });}});++ it('honors a custom declaration entry path', async () => {+ const proj = mkdtempSync(path.join(tmpdir(), 'estella-schema-custom-'));+ try {+ mkdirSync(path.join(proj, 'game'), { recursive: true });+ writeFileSync(+ path.join(proj, 'game', 'decls.ts'),+ `import { defineComponent } from 'esengine';\n` ++ `export const Spin = defineComponent('Spin', { rpm: 33 });\n`,+ );+ const res = await extractProjectSchemas(proj, { entry: 'game/decls.ts' });+ expect(res.ok).toBe(true);+ expect(res.schemas.map((s) => s.name)).toEqual(['Spin']);+ expect(res.schemas[0].default).toEqual({ rpm: 33 });+ } finally {+ rmSync(proj, { recursive: true, force: true });+ }+ });});diff --git a/desktop/tests/project-scripts.test.ts b/desktop/tests/project-scripts.test.tsnew file mode 100644index 000000000..e9a5cb377--- /dev/null+++ b/desktop/tests/project-scripts.test.ts@@ -0,0 +1,67 @@+/**+ * @file Project script-entry convention (REARCH_EDITOR_REALM Phase P3).+ *+ * The manifest's `scripts.register` / `scripts.main` (with defaults) name the+ * declaration vs startup modules; this is what lets the editor extract a schema+ * from the declaration WITHOUT executing startup. Also verifies the extractor+ * against REAL example projects (copied to a tmp dir so nothing is written into+ * the repo), proving they already follow declaration/startup separation.+ */+import { describe, it, expect } from 'vitest';+import { cpSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { fileURLToPath } from 'node:url';+import path from 'node:path';+import { parseManifest, resolveScripts, DEFAULT_SCRIPTS } from '../src/project/format';+import { extractProjectSchemas } from '../electron/extractSchemas';++const EXAMPLES = fileURLToPath(new URL('../../examples', import.meta.url));++/** Extract from a throwaway copy of an example's src — never touch the repo. */+async function extractExample(name: string) {+ const tmp = mkdtempSync(path.join(tmpdir(), `estella-ex-${name}-`));+ try {+ cpSync(path.join(EXAMPLES, name, 'src'), path.join(tmp, 'src'), { recursive: true });+ return await extractProjectSchemas(tmp);+ } finally {+ rmSync(tmp, { recursive: true, force: true });+ }+}++describe('manifest scripts convention (P3)', () => {+ it('defaults to src/components.ts + src/main.ts when unspecified', () => {+ expect(resolveScripts({})).toEqual(DEFAULT_SCRIPTS);+ expect(resolveScripts({ scripts: {} })).toEqual({ register: 'src/components.ts', main: 'src/main.ts' });+ });++ it('parses + overlays scripts.register / scripts.main', () => {+ const m = parseManifest({ name: 'x', scripts: { register: 'game/decls.ts' } });+ expect(m.scripts).toEqual({ register: 'game/decls.ts' });+ expect(resolveScripts(m)).toEqual({ register: 'game/decls.ts', main: 'src/main.ts' });+ });++ it('ignores a non-object or empty scripts block (stays on the defaults)', () => {+ expect(parseManifest({ name: 'x', scripts: 'nope' }).scripts).toBeUndefined();+ expect(parseManifest({ name: 'x', scripts: {} }).scripts).toBeUndefined();+ });+});++describe('extraction against real examples (declaration/startup separation)', () => {+ it('extracts space-shooter project components from its src/components.ts', async () => {+ const res = await extractExample('space-shooter');+ expect(res.ok).toBe(true);+ const names = res.schemas.map((s) => s.name);+ expect(names).toEqual(expect.arrayContaining(['Player', 'Enemy', 'Bullet', 'Health']));+ // a defineTag stays a tag:+ expect(res.schemas.find((s) => s.name === 'ScoreDisplay')?.isTag).toBe(true);+ // engine builtins never leak into the project schema:+ expect(names).not.toContain('Sprite');+ expect(names).not.toContain('Transform');+ });++ it('a component-less example (no src/components.ts) yields an empty schema set', async () => {+ const res = await extractExample('particle-demo');+ expect(res.ok).toBe(true);+ expect(res.schemas).toEqual([]);+ });+});